]> git.saurik.com Git - cydia.git/blob - MobileCydia.mm
Reimplement APT marking as I finally understand how it works.
[cydia.git] / MobileCydia.mm
1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2010 Jay Freeman (saurik)
3 */
4
5 /* Modified BSD License {{{ */
6 /*
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
10 *
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
18 * distribution.
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 */
38 /* }}} */
39
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
42
43 /* #include Directives {{{ */
44 #include "UICaboodle/UCPlatform.h"
45 #include "UICaboodle/UCLocalize.h"
46
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
49
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
52
53 #if 0
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
57 #endif
58
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
61
62 #include <SystemConfiguration/SystemConfiguration.h>
63
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
66
67 #include <IOKit/IOKitLib.h>
68
69 #include <WebCore/WebCoreThread.h>
70
71 #include <algorithm>
72 #include <iomanip>
73 #include <sstream>
74 #include <string>
75
76 #include <ext/stdio_filebuf.h>
77
78 #undef ABS
79
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
97
98 #include <apr-1/apr_pools.h>
99
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
105
106 #include <fcntl.h>
107 #include <notify.h>
108 #include <dlfcn.h>
109
110 extern "C" {
111 #include <mach-o/nlist.h>
112 }
113
114 #include <cstdio>
115 #include <cstdlib>
116 #include <cstring>
117
118 #include <errno.h>
119 #include <pcre.h>
120
121 #include <ext/hash_map>
122
123 #include "UICaboodle/BrowserView.h"
124
125 #include "substrate.h"
126 /* }}} */
127
128 /* Profiler {{{ */
129 struct timeval _ltv;
130 bool _itv;
131
132 #define _timestamp ({ \
133 struct timeval tv; \
134 gettimeofday(&tv, NULL); \
135 tv.tv_sec * 1000000 + tv.tv_usec; \
136 })
137
138 typedef std::vector<class ProfileTime *> TimeList;
139 TimeList times_;
140
141 class ProfileTime {
142 private:
143 const char *name_;
144 uint64_t total_;
145 uint64_t count_;
146
147 public:
148 ProfileTime(const char *name) :
149 name_(name),
150 total_(0)
151 {
152 times_.push_back(this);
153 }
154
155 void AddTime(uint64_t time) {
156 total_ += time;
157 ++count_;
158 }
159
160 void Print() {
161 if (total_ != 0)
162 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
163 total_ = 0;
164 count_ = 0;
165 }
166 };
167
168 class ProfileTimer {
169 private:
170 ProfileTime &time_;
171 uint64_t start_;
172
173 public:
174 ProfileTimer(ProfileTime &time) :
175 time_(time),
176 start_(_timestamp)
177 {
178 }
179
180 ~ProfileTimer() {
181 time_.AddTime(_timestamp - start_);
182 }
183 };
184
185 void PrintTimes() {
186 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
187 (*i)->Print();
188 std::cerr << "========" << std::endl;
189 }
190
191 #define _profile(name) { \
192 static ProfileTime name(#name); \
193 ProfileTimer _ ## name(name);
194
195 #define _end }
196 /* }}} */
197
198 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
199
200 #define CYPoolStart() \
201 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
202 do
203 #define CYPoolEnd() \
204 while (false); \
205 [_pool release];
206
207 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
208
209 void NSLogPoint(const char *fix, const CGPoint &point) {
210 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
211 }
212
213 void NSLogRect(const char *fix, const CGRect &rect) {
214 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
215 }
216
217 static _finline NSString *CydiaURL(NSString *path) {
218 char page[25];
219 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
220 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
221 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
222 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
223 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
224 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
225 }
226
227 static _finline void UpdateExternalStatus(uint64_t newStatus) {
228 int notify_token;
229 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
230 notify_set_state(notify_token, newStatus);
231 notify_cancel(notify_token);
232 }
233 notify_post("com.saurik.Cydia.status");
234 }
235
236 /* [NSObject yieldToSelector:(withObject:)] {{{*/
237 @interface NSObject (Cydia)
238 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
239 - (id) yieldToSelector:(SEL)selector;
240 @end
241
242 @implementation NSObject (Cydia)
243
244 - (void) doNothing {
245 }
246
247 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
248 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
249 id object([[context objectAtIndex:1] nonretainedObjectValue]);
250 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
251
252 /* XXX: deal with exceptions */
253 id value([self performSelector:selector withObject:object]);
254
255 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
256 [context removeAllObjects];
257 if ([signature methodReturnLength] != 0 && value != nil)
258 [context addObject:value];
259
260 stopped = true;
261
262 [self
263 performSelectorOnMainThread:@selector(doNothing)
264 withObject:nil
265 waitUntilDone:NO
266 ];
267 }
268
269 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
270 /*return [self performSelector:selector withObject:object];*/
271
272 volatile bool stopped(false);
273
274 NSMutableArray *context([NSMutableArray arrayWithObjects:
275 [NSValue valueWithPointer:selector],
276 [NSValue valueWithNonretainedObject:object],
277 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
278 nil]);
279
280 NSThread *thread([[[NSThread alloc]
281 initWithTarget:self
282 selector:@selector(_yieldToContext:)
283 object:context
284 ] autorelease]);
285
286 [thread start];
287
288 NSRunLoop *loop([NSRunLoop currentRunLoop]);
289 NSDate *future([NSDate distantFuture]);
290
291 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
292
293 return [context count] == 0 ? nil : [context objectAtIndex:0];
294 }
295
296 - (id) yieldToSelector:(SEL)selector {
297 return [self yieldToSelector:selector withObject:nil];
298 }
299
300 @end
301 /* }}} */
302
303 /* Cydia Action Sheet {{{ */
304 @interface CYActionSheet : UIAlertView {
305 unsigned button_;
306 }
307
308 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
309 @end
310
311 @implementation CYActionSheet
312
313 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
314 if ((self = [super init])) {
315 [self setTitle:title];
316 [self setDelegate:self];
317 for (NSString *button in buttons) [self addButtonWithTitle:button];
318 [self setCancelButtonIndex:index];
319 } return self;
320 }
321
322 - (void) _updateFrameForDisplay {
323 [super _updateFrameForDisplay];
324 if ([self cancelButtonIndex] == -1) {
325 NSArray *buttons = [self buttons];
326 if ([buttons count]) {
327 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
328 for (UIThreePartButton *button in buttons)
329 [button setBackground:background forState:0];
330 }
331 }
332 }
333
334 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
335 button_ = buttonIndex + 1;
336 }
337
338 - (void) dismiss {
339 [self dismissWithClickedButtonIndex:-1 animated:YES];
340 }
341
342 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
343 [self setRunsModal:YES];
344 button_ = 0;
345 [self show];
346 return button_;
347 }
348
349 @end
350 /* }}} */
351
352 /* NSForcedOrderingSearch doesn't work on the iPhone */
353 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
354 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
355 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
356
357 /* Information Dictionaries {{{ */
358 @interface NSMutableArray (Cydia)
359 - (void) addInfoDictionary:(NSDictionary *)info;
360 @end
361
362 @implementation NSMutableArray (Cydia)
363
364 - (void) addInfoDictionary:(NSDictionary *)info {
365 [self addObject:info];
366 }
367
368 @end
369
370 @interface NSMutableDictionary (Cydia)
371 - (void) addInfoDictionary:(NSDictionary *)info;
372 @end
373
374 @implementation NSMutableDictionary (Cydia)
375
376 - (void) addInfoDictionary:(NSDictionary *)info {
377 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
378 }
379
380 @end
381 /* }}} */
382
383 #define lprintf(args...) fprintf(stderr, args)
384
385 #define ForRelease 1
386 #define TraceLogging (1 && !ForRelease)
387 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
388 #define ProfileTimes (0 && !ForRelease)
389 #define ForSaurik (0 && !ForRelease)
390 #define LogBrowser (0 && !ForRelease)
391 #define TrackResize (0 && !ForRelease)
392 #define ManualRefresh (1 && !ForRelease)
393 #define ShowInternals (0 && !ForRelease)
394 #define IgnoreInstall (0 && !ForRelease)
395 #define AlwaysReload (0 && !ForRelease)
396
397 #if !TraceLogging
398 #undef _trace
399 #define _trace(args...)
400 #endif
401
402 #if !ProfileTimes
403 #undef _profile
404 #define _profile(name) {
405 #undef _end
406 #define _end }
407 #define PrintTimes() do {} while (false)
408 #endif
409
410 /* Radix Sort {{{ */
411 typedef uint32_t (*SKRadixFunction)(id, void *);
412
413 @interface NSMutableArray (Radix)
414 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
415 @end
416
417 struct RadixItem_ {
418 size_t index;
419 uint32_t key;
420 };
421
422 @implementation NSMutableArray (Radix)
423
424 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
425 size_t count([self count]);
426 struct RadixItem_ *swap(new RadixItem_[count * 2]);
427
428 for (size_t i(0); i != count; ++i) {
429 RadixItem_ &item(swap[i]);
430 item.index = i;
431
432 id object([self objectAtIndex:i]);
433 item.key = function(object, argument);
434 }
435
436 struct RadixItem_ *lhs(swap), *rhs(swap + count);
437
438 static const size_t width = 32;
439 static const size_t bits = 11;
440 static const size_t slots = 1 << bits;
441 static const size_t passes = (width + (bits - 1)) / bits;
442
443 size_t *hist(new size_t[slots]);
444
445 for (size_t pass(0); pass != passes; ++pass) {
446 memset(hist, 0, sizeof(size_t) * slots);
447
448 for (size_t i(0); i != count; ++i) {
449 uint32_t key(lhs[i].key);
450 key >>= pass * bits;
451 key &= _not(uint32_t) >> width - bits;
452 ++hist[key];
453 }
454
455 size_t offset(0);
456 for (size_t i(0); i != slots; ++i) {
457 size_t local(offset);
458 offset += hist[i];
459 hist[i] = local;
460 }
461
462 for (size_t i(0); i != count; ++i) {
463 uint32_t key(lhs[i].key);
464 key >>= pass * bits;
465 key &= _not(uint32_t) >> width - bits;
466 rhs[hist[key]++] = lhs[i];
467 }
468
469 RadixItem_ *tmp(lhs);
470 lhs = rhs;
471 rhs = tmp;
472 }
473
474 delete [] hist;
475
476 const void **values(new const void *[count]);
477 for (size_t i(0); i != count; ++i)
478 values[i] = [self objectAtIndex:lhs[i].index];
479 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
480 delete [] values;
481
482 delete [] swap;
483 }
484
485 @end
486 /* }}} */
487 /* Insertion Sort {{{ */
488
489 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
490 const char *ptr = (const char *)list;
491 while (0 < count) {
492 CFIndex half = count / 2;
493 const char *probe = ptr + elementSize * half;
494 CFComparisonResult cr = comparator(element, probe, context);
495 if (0 == cr) return (probe - (const char *)list) / elementSize;
496 ptr = (cr < 0) ? ptr : probe + elementSize;
497 count = (cr < 0) ? half : (half + (count & 1) - 1);
498 }
499 return (ptr - (const char *)list) / elementSize;
500 }
501
502 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
503 const char *ptr = (const char *)list;
504 while (0 < count) {
505 CFIndex half = count / 2;
506 const char *probe = ptr + elementSize * half;
507 CFComparisonResult cr = comparator(element, probe, context);
508 if (0 == cr) return (probe - (const char *)list) / elementSize;
509 ptr = (cr < 0) ? ptr : probe + elementSize;
510 count = (cr < 0) ? half : (half + (count & 1) - 1);
511 }
512 return (ptr - (const char *)list) / elementSize;
513 }
514
515 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
516 if (range.length == 0)
517 return;
518 const void **values(new const void *[range.length]);
519 CFArrayGetValues(array, range, values);
520
521 #if HistogramInsertionSort > 0
522 uint32_t total(0), *offsets(new uint32_t[range.length]);
523 #endif
524
525 for (CFIndex index(1); index != range.length; ++index) {
526 const void *value(values[index]);
527 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
528 CFIndex correct(index);
529 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
530 #if HistogramInsertionSort > 1
531 NSLog(@"%@ < %@", value, values[correct - 1]);
532 #endif
533 if (--correct == 0)
534 break;
535 }
536 if (correct != index) {
537 size_t offset(index - correct);
538 #if HistogramInsertionSort
539 total += offset;
540 ++offsets[offset];
541 if (offset > 10)
542 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
543 #endif
544 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
545 values[correct] = value;
546 }
547 }
548
549 CFArrayReplaceValues(array, range, values, range.length);
550 delete [] values;
551
552 #if HistogramInsertionSort > 0
553 for (CFIndex index(0); index != range.length; ++index)
554 if (offsets[index] != 0)
555 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
556 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
557 delete [] offsets;
558 #endif
559 }
560
561 /* }}} */
562
563 /* Apple Bug Fixes {{{ */
564 @implementation UIWebDocumentView (Cydia)
565
566 - (void) _setScrollerOffset:(CGPoint)offset {
567 UIScroller *scroller([self _scroller]);
568
569 CGSize size([scroller contentSize]);
570 CGSize bounds([scroller bounds].size);
571
572 CGPoint max;
573 max.x = size.width - bounds.width;
574 max.y = size.height - bounds.height;
575
576 // wtf Apple?!
577 if (max.x < 0)
578 max.x = 0;
579 if (max.y < 0)
580 max.y = 0;
581
582 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
583 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
584
585 [scroller setOffset:offset];
586 }
587
588 @end
589 /* }}} */
590
591 @implementation WebScriptObject (NSFastEnumeration)
592
593 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
594 size_t length([self count] - state->state);
595 if (length <= 0)
596 return 0;
597 else if (length > count)
598 length = count;
599 for (size_t i(0); i != length; ++i)
600 objects[i] = [self objectAtIndex:state->state++];
601 state->itemsPtr = objects;
602 state->mutationsPtr = (unsigned long *) self;
603 return length;
604 }
605
606 @end
607
608 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
609 size_t length([self length] - state->state);
610 if (length <= 0)
611 return 0;
612 else if (length > count)
613 length = count;
614 for (size_t i(0); i != length; ++i)
615 objects[i] = [self item:state->state++];
616 state->itemsPtr = objects;
617 state->mutationsPtr = (unsigned long *) self;
618 return length;
619 }
620
621 /* Cydia NSString Additions {{{ */
622 @interface NSString (Cydia)
623 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
624 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
625 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
626 - (NSComparisonResult) compareByPath:(NSString *)other;
627 - (NSString *) stringByCachingURLWithCurrentCDN;
628 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
629 @end
630
631 @implementation NSString (Cydia)
632
633 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
634 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
635 }
636
637 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
638 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
639 memcpy(data, bytes, length);
640 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
641 }
642
643 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
644 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
645 }
646
647 - (NSComparisonResult) compareByPath:(NSString *)other {
648 NSString *prefix = [self commonPrefixWithString:other options:0];
649 size_t length = [prefix length];
650
651 NSRange lrange = NSMakeRange(length, [self length] - length);
652 NSRange rrange = NSMakeRange(length, [other length] - length);
653
654 lrange = [self rangeOfString:@"/" options:0 range:lrange];
655 rrange = [other rangeOfString:@"/" options:0 range:rrange];
656
657 NSComparisonResult value;
658
659 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
660 value = NSOrderedSame;
661 else if (lrange.location == NSNotFound)
662 value = NSOrderedAscending;
663 else if (rrange.location == NSNotFound)
664 value = NSOrderedDescending;
665 else
666 value = NSOrderedSame;
667
668 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
669 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
670 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
671 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
672
673 NSComparisonResult result = [lpath compare:rpath];
674 return result == NSOrderedSame ? value : result;
675 }
676
677 - (NSString *) stringByCachingURLWithCurrentCDN {
678 return [self
679 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
680 withString:@"://cache.cydia.saurik.com/"
681 ];
682 }
683
684 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
685 return [(id)CFURLCreateStringByAddingPercentEscapes(
686 kCFAllocatorDefault,
687 (CFStringRef) self,
688 NULL,
689 CFSTR(";/?:@&=+$,"),
690 kCFStringEncodingUTF8
691 ) autorelease];
692 }
693
694 @end
695 /* }}} */
696
697 /* C++ NSString Wrapper Cache {{{ */
698 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
699 return size == 0 ? NULL :
700 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
701 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
702 }
703
704 static _finline CFStringRef CYStringCreate(const char *data) {
705 return CYStringCreate(data, strlen(data));
706 }
707
708 class CYString {
709 private:
710 char *data_;
711 size_t size_;
712 CFStringRef cache_;
713
714 _finline void clear_() {
715 if (cache_ != NULL) {
716 CFRelease(cache_);
717 cache_ = NULL;
718 }
719 }
720
721 public:
722 _finline bool empty() const {
723 return size_ == 0;
724 }
725
726 _finline size_t size() const {
727 return size_;
728 }
729
730 _finline char *data() const {
731 return data_;
732 }
733
734 _finline void clear() {
735 size_ = 0;
736 clear_();
737 }
738
739 _finline CYString() :
740 data_(0),
741 size_(0),
742 cache_(NULL)
743 {
744 }
745
746 _finline ~CYString() {
747 clear_();
748 }
749
750 void operator =(const CYString &rhs) {
751 data_ = rhs.data_;
752 size_ = rhs.size_;
753
754 if (rhs.cache_ == nil)
755 cache_ = NULL;
756 else
757 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
758 }
759
760 void set(apr_pool_t *pool, const char *data, size_t size) {
761 if (size == 0)
762 clear();
763 else {
764 clear_();
765
766 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
767 memcpy(temp, data, size);
768 temp[size] = '\0';
769 data_ = temp;
770 size_ = size;
771 }
772 }
773
774 _finline void set(apr_pool_t *pool, const char *data) {
775 set(pool, data, data == NULL ? 0 : strlen(data));
776 }
777
778 _finline void set(apr_pool_t *pool, const std::string &rhs) {
779 set(pool, rhs.data(), rhs.size());
780 }
781
782 bool operator ==(const CYString &rhs) const {
783 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
784 }
785
786 _finline operator CFStringRef() {
787 if (cache_ == NULL)
788 cache_ = CYStringCreate(data_, size_);
789 return cache_;
790 }
791
792 _finline operator id() {
793 return (NSString *) static_cast<CFStringRef>(*this);
794 }
795 };
796 /* }}} */
797 /* C++ NSString Algorithm Adapters {{{ */
798 extern "C" {
799 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
800 }
801
802 struct NSStringMapHash :
803 std::unary_function<NSString *, size_t>
804 {
805 _finline size_t operator ()(NSString *value) const {
806 return CFStringHashNSString((CFStringRef) value);
807 }
808 };
809
810 struct NSStringMapLess :
811 std::binary_function<NSString *, NSString *, bool>
812 {
813 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
814 return [lhs compare:rhs] == NSOrderedAscending;
815 }
816 };
817
818 struct NSStringMapEqual :
819 std::binary_function<NSString *, NSString *, bool>
820 {
821 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
822 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
823 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
824 //[lhs isEqualToString:rhs];
825 }
826 };
827 /* }}} */
828
829 /* Perl-Compatible RegEx {{{ */
830 class Pcre {
831 private:
832 pcre *code_;
833 pcre_extra *study_;
834 int capture_;
835 int *matches_;
836 const char *data_;
837
838 public:
839 Pcre(const char *regex) :
840 study_(NULL)
841 {
842 const char *error;
843 int offset;
844 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
845
846 if (code_ == NULL) {
847 lprintf("%d:%s\n", offset, error);
848 _assert(false);
849 }
850
851 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
852 matches_ = new int[(capture_ + 1) * 3];
853 }
854
855 ~Pcre() {
856 pcre_free(code_);
857 delete matches_;
858 }
859
860 NSString *operator [](size_t match) {
861 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
862 }
863
864 bool operator ()(NSString *data) {
865 // XXX: length is for characters, not for bytes
866 return operator ()([data UTF8String], [data length]);
867 }
868
869 bool operator ()(const char *data, size_t size) {
870 data_ = data;
871 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
872 }
873 };
874 /* }}} */
875 /* Mime Addresses {{{ */
876 @interface Address : NSObject {
877 NSString *name_;
878 NSString *address_;
879 }
880
881 - (NSString *) name;
882 - (NSString *) address;
883
884 - (void) setAddress:(NSString *)address;
885
886 + (Address *) addressWithString:(NSString *)string;
887 - (Address *) initWithString:(NSString *)string;
888 @end
889
890 @implementation Address
891
892 - (void) dealloc {
893 [name_ release];
894 if (address_ != nil)
895 [address_ release];
896 [super dealloc];
897 }
898
899 - (NSString *) name {
900 return name_;
901 }
902
903 - (NSString *) address {
904 return address_;
905 }
906
907 - (void) setAddress:(NSString *)address {
908 if (address_ != nil)
909 [address_ autorelease];
910 if (address == nil)
911 address_ = nil;
912 else
913 address_ = [address retain];
914 }
915
916 + (Address *) addressWithString:(NSString *)string {
917 return [[[Address alloc] initWithString:string] autorelease];
918 }
919
920 + (NSArray *) _attributeKeys {
921 return [NSArray arrayWithObjects:@"address", @"name", nil];
922 }
923
924 - (NSArray *) attributeKeys {
925 return [[self class] _attributeKeys];
926 }
927
928 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
929 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
930 }
931
932 - (Address *) initWithString:(NSString *)string {
933 if ((self = [super init]) != nil) {
934 const char *data = [string UTF8String];
935 size_t size = [string length];
936
937 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
938
939 if (address_r(data, size)) {
940 name_ = [address_r[1] retain];
941 address_ = [address_r[2] retain];
942 } else {
943 name_ = [string retain];
944 address_ = nil;
945 }
946 } return self;
947 }
948
949 @end
950 /* }}} */
951 /* CoreGraphics Primitives {{{ */
952 class CYColor {
953 private:
954 CGColorRef color_;
955
956 public:
957 CYColor() :
958 color_(NULL)
959 {
960 }
961
962 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
963 color_(NULL)
964 {
965 Set(space, red, green, blue, alpha);
966 }
967
968 void Clear() {
969 if (color_ != NULL)
970 CGColorRelease(color_);
971 }
972
973 ~CYColor() {
974 Clear();
975 }
976
977 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
978 Clear();
979 float color[] = {red, green, blue, alpha};
980 color_ = CGColorCreate(space, (CGFloat *) color);
981 }
982
983 operator CGColorRef() {
984 return color_;
985 }
986 };
987 /* }}} */
988
989 /* Random Global Variables {{{ */
990 static const int PulseInterval_ = 50000;
991 static const int ButtonBarWidth_ = 60;
992 static const int ButtonBarHeight_ = 48;
993 static const float KeyboardTime_ = 0.3f;
994
995 static int Finish_;
996 static NSArray *Finishes_;
997
998 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
999 #define NotifyConfig_ "/etc/notify.conf"
1000
1001 static bool Queuing_;
1002
1003 static CYColor Blue_;
1004 static CYColor Blueish_;
1005 static CYColor Black_;
1006 static CYColor Off_;
1007 static CYColor White_;
1008 static CYColor Gray_;
1009 static CYColor Green_;
1010 static CYColor Purple_;
1011 static CYColor Purplish_;
1012
1013 static UIColor *InstallingColor_;
1014 static UIColor *RemovingColor_;
1015
1016 static NSString *App_;
1017 static NSString *Home_;
1018
1019 static BOOL Advanced_;
1020 static BOOL Ignored_;
1021
1022 static UIFont *Font12_;
1023 static UIFont *Font12Bold_;
1024 static UIFont *Font14_;
1025 static UIFont *Font18Bold_;
1026 static UIFont *Font22Bold_;
1027
1028 static const char *Machine_ = NULL;
1029 static NSString *System_ = nil;
1030 static NSString *SerialNumber_ = nil;
1031 static NSString *ChipID_ = nil;
1032 static NSString *Token_ = nil;
1033 static NSString *UniqueID_ = nil;
1034 static NSString *PLMN_ = nil;
1035 static NSString *Build_ = nil;
1036 static NSString *Product_ = nil;
1037 static NSString *Safari_ = nil;
1038
1039 static CFLocaleRef Locale_;
1040 static NSArray *Languages_;
1041 static CGColorSpaceRef space_;
1042
1043 static NSDictionary *SectionMap_;
1044 static NSMutableDictionary *Metadata_;
1045 static _transient NSMutableDictionary *Settings_;
1046 static _transient NSString *Role_;
1047 static _transient NSMutableDictionary *Packages_;
1048 static _transient NSMutableDictionary *Sections_;
1049 static _transient NSMutableDictionary *Sources_;
1050 static bool Changed_;
1051 static NSDate *now_;
1052
1053 static bool IsWildcat_;
1054 /* }}} */
1055
1056 /* Display Helpers {{{ */
1057 inline float Interpolate(float begin, float end, float fraction) {
1058 return (end - begin) * fraction + begin;
1059 }
1060
1061 /* XXX: localize this! */
1062 NSString *SizeString(double size) {
1063 bool negative = size < 0;
1064 if (negative)
1065 size = -size;
1066
1067 unsigned power = 0;
1068 while (size > 1024) {
1069 size /= 1024;
1070 ++power;
1071 }
1072
1073 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1074
1075 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1076 }
1077
1078 static _finline const char *StripVersion_(const char *version) {
1079 const char *colon(strchr(version, ':'));
1080 if (colon != NULL)
1081 version = colon + 1;
1082 return version;
1083 }
1084
1085 NSString *LocalizeSection(NSString *section) {
1086 static Pcre title_r("^(.*?) \\((.*)\\)$");
1087 if (title_r(section)) {
1088 NSString *parent(title_r[1]);
1089 NSString *child(title_r[2]);
1090
1091 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1092 LocalizeSection(parent),
1093 LocalizeSection(child)
1094 ];
1095 }
1096
1097 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1098 }
1099
1100 NSString *Simplify(NSString *title) {
1101 const char *data = [title UTF8String];
1102 size_t size = [title length];
1103
1104 static Pcre square_r("^\\[(.*)\\]$");
1105 if (square_r(data, size))
1106 return Simplify(square_r[1]);
1107
1108 static Pcre paren_r("^\\((.*)\\)$");
1109 if (paren_r(data, size))
1110 return Simplify(paren_r[1]);
1111
1112 static Pcre title_r("^(.*?) \\((.*)\\)$");
1113 if (title_r(data, size))
1114 return Simplify(title_r[1]);
1115
1116 return title;
1117 }
1118 /* }}} */
1119
1120 NSString *GetLastUpdate() {
1121 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1122
1123 if (update == nil)
1124 return UCLocalize("NEVER_OR_UNKNOWN");
1125
1126 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1127 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1128
1129 CFRelease(formatter);
1130
1131 return [(NSString *) formatted autorelease];
1132 }
1133
1134 bool isSectionVisible(NSString *section) {
1135 NSDictionary *metadata([Sections_ objectForKey:section]);
1136 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1137 return hidden == nil || ![hidden boolValue];
1138 }
1139
1140 @class Cydia;
1141
1142 /* Delegate Prototypes {{{ */
1143 @class Package;
1144 @class Source;
1145
1146 @interface NSObject (ProgressDelegate)
1147 @end
1148
1149 @protocol ProgressDelegate
1150 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1151 - (void) setProgressTitle:(NSString *)title;
1152 - (void) setProgressPercent:(float)percent;
1153 - (void) startProgress;
1154 - (void) addProgressOutput:(NSString *)output;
1155 - (bool) isCancelling:(size_t)received;
1156 @end
1157
1158 @protocol ConfigurationDelegate
1159 - (void) repairWithSelector:(SEL)selector;
1160 - (void) setConfigurationData:(NSString *)data;
1161 @end
1162
1163 @class PackageController;
1164
1165 @protocol CydiaDelegate
1166 - (void) setPackageController:(PackageController *)view;
1167 - (void) clearPackage:(Package *)package;
1168 - (void) installPackage:(Package *)package;
1169 - (void) installPackages:(NSArray *)packages;
1170 - (void) removePackage:(Package *)package;
1171 - (void) beginUpdate;
1172 - (BOOL) updating;
1173 - (void) distUpgrade;
1174 - (void) loadData;
1175 - (void) updateData;
1176 - (void) syncData;
1177 - (void) showSettings;
1178 - (UIProgressHUD *) addProgressHUD;
1179 - (BOOL) hudIsShowing;
1180 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1181 - (CYViewController *) pageForPackage:(NSString *)name;
1182 - (PackageController *) packageController;
1183 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1184 @end
1185 /* }}} */
1186
1187 /* Status Delegation {{{ */
1188 class Status :
1189 public pkgAcquireStatus
1190 {
1191 private:
1192 _transient NSObject<ProgressDelegate> *delegate_;
1193
1194 public:
1195 Status() :
1196 delegate_(nil)
1197 {
1198 }
1199
1200 void setDelegate(id delegate) {
1201 delegate_ = delegate;
1202 }
1203
1204 NSObject<ProgressDelegate> *getDelegate() const {
1205 return delegate_;
1206 }
1207
1208 virtual bool MediaChange(std::string media, std::string drive) {
1209 return false;
1210 }
1211
1212 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1213 }
1214
1215 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1216 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1217 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1218 }
1219
1220 virtual void Done(pkgAcquire::ItemDesc &item) {
1221 }
1222
1223 virtual void Fail(pkgAcquire::ItemDesc &item) {
1224 if (
1225 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1226 item.Owner->Status == pkgAcquire::Item::StatDone
1227 )
1228 return;
1229
1230 std::string &error(item.Owner->ErrorText);
1231 if (error.empty())
1232 return;
1233
1234 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1235 NSArray *fields([description componentsSeparatedByString:@" "]);
1236 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1237
1238 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1239 withObject:[NSArray arrayWithObjects:
1240 [NSString stringWithUTF8String:error.c_str()],
1241 source,
1242 nil]
1243 waitUntilDone:YES
1244 ];
1245 }
1246
1247 virtual bool Pulse(pkgAcquire *Owner) {
1248 bool value = pkgAcquireStatus::Pulse(Owner);
1249
1250 float percent(
1251 double(CurrentBytes + CurrentItems) /
1252 double(TotalBytes + TotalItems)
1253 );
1254
1255 [delegate_ setProgressPercent:percent];
1256 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1257 }
1258
1259 virtual void Start() {
1260 [delegate_ startProgress];
1261 }
1262
1263 virtual void Stop() {
1264 }
1265 };
1266 /* }}} */
1267 /* Progress Delegation {{{ */
1268 class Progress :
1269 public OpProgress
1270 {
1271 private:
1272 _transient id<ProgressDelegate> delegate_;
1273 float percent_;
1274
1275 protected:
1276 virtual void Update() {
1277 /*if (abs(Percent - percent_) > 2)
1278 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1279 percent_ = Percent;
1280 }*/
1281
1282 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1283 [delegate_ setProgressPercent:(Percent / 100)];*/
1284 }
1285
1286 public:
1287 Progress() :
1288 delegate_(nil),
1289 percent_(0)
1290 {
1291 }
1292
1293 void setDelegate(id delegate) {
1294 delegate_ = delegate;
1295 }
1296
1297 id getDelegate() const {
1298 return delegate_;
1299 }
1300
1301 virtual void Done() {
1302 //NSLog(@"DONE");
1303 //[delegate_ setProgressPercent:1];
1304 }
1305 };
1306 /* }}} */
1307
1308 /* Database Interface {{{ */
1309 typedef std::map< unsigned long, _H<Source> > SourceMap;
1310
1311 @interface Database : NSObject {
1312 NSZone *zone_;
1313 apr_pool_t *pool_;
1314
1315 unsigned era_;
1316
1317 pkgCacheFile cache_;
1318 pkgDepCache::Policy *policy_;
1319 pkgRecords *records_;
1320 pkgProblemResolver *resolver_;
1321 pkgAcquire *fetcher_;
1322 FileFd *lock_;
1323 SPtr<pkgPackageManager> manager_;
1324 pkgSourceList *list_;
1325
1326 SourceMap sources_;
1327 CFMutableArrayRef packages_;
1328
1329 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1330 Status status_;
1331 Progress progress_;
1332
1333 int cydiafd_;
1334 int statusfd_;
1335 FILE *input_;
1336 }
1337
1338 + (Database *) sharedInstance;
1339 - (unsigned) era;
1340
1341 - (void) _readCydia:(NSNumber *)fd;
1342 - (void) _readStatus:(NSNumber *)fd;
1343 - (void) _readOutput:(NSNumber *)fd;
1344
1345 - (FILE *) input;
1346
1347 - (Package *) packageWithName:(NSString *)name;
1348
1349 - (pkgCacheFile &) cache;
1350 - (pkgDepCache::Policy *) policy;
1351 - (pkgRecords *) records;
1352 - (pkgProblemResolver *) resolver;
1353 - (pkgAcquire &) fetcher;
1354 - (pkgSourceList &) list;
1355 - (NSArray *) packages;
1356 - (NSArray *) sources;
1357 - (void) reloadData;
1358
1359 - (void) configure;
1360 - (bool) prepare;
1361 - (void) perform;
1362 - (bool) upgrade;
1363 - (void) update;
1364
1365 - (void) setVisible;
1366
1367 - (void) updateWithStatus:(Status &)status;
1368
1369 - (void) setDelegate:(id)delegate;
1370 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1371 @end
1372 /* }}} */
1373 /* Delegate Helpers {{{ */
1374 @implementation NSObject (ProgressDelegate)
1375
1376 - (void) _setProgressErrorPackage:(NSArray *)args {
1377 [self performSelector:@selector(setProgressError:forPackage:)
1378 withObject:[args objectAtIndex:0]
1379 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1380 ];
1381 }
1382
1383 - (void) _setProgressErrorTitle:(NSArray *)args {
1384 [self performSelector:@selector(setProgressError:withTitle:)
1385 withObject:[args objectAtIndex:0]
1386 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1387 ];
1388 }
1389
1390 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1391 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1392 withObject:[NSArray arrayWithObjects:error, title, nil]
1393 waitUntilDone:YES
1394 ];
1395 }
1396
1397 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1398 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1399
1400 [self performSelector:@selector(setProgressError:withTitle:)
1401 withObject:error
1402 withObject:(package == nil ? id : [package name])
1403 ];
1404 }
1405
1406 @end
1407 /* }}} */
1408
1409 /* Source Class {{{ */
1410 @interface Source : NSObject {
1411 CYString depiction_;
1412 CYString description_;
1413 CYString label_;
1414 CYString origin_;
1415 CYString support_;
1416
1417 CYString uri_;
1418 CYString distribution_;
1419 CYString type_;
1420 CYString version_;
1421
1422 NSString *host_;
1423 NSString *authority_;
1424
1425 CYString defaultIcon_;
1426
1427 NSDictionary *record_;
1428 BOOL trusted_;
1429 }
1430
1431 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1432
1433 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1434
1435 - (NSString *) depictionForPackage:(NSString *)package;
1436 - (NSString *) supportForPackage:(NSString *)package;
1437
1438 - (NSDictionary *) record;
1439 - (BOOL) trusted;
1440
1441 - (NSString *) uri;
1442 - (NSString *) distribution;
1443 - (NSString *) type;
1444 - (NSString *) key;
1445 - (NSString *) host;
1446
1447 - (NSString *) name;
1448 - (NSString *) description;
1449 - (NSString *) label;
1450 - (NSString *) origin;
1451 - (NSString *) version;
1452
1453 - (NSString *) defaultIcon;
1454
1455 @end
1456
1457 @implementation Source
1458
1459 - (void) _clear {
1460 uri_.clear();
1461 distribution_.clear();
1462 type_.clear();
1463
1464 description_.clear();
1465 label_.clear();
1466 origin_.clear();
1467 depiction_.clear();
1468 support_.clear();
1469 version_.clear();
1470 defaultIcon_.clear();
1471
1472 if (record_ != nil) {
1473 [record_ release];
1474 record_ = nil;
1475 }
1476
1477 if (host_ != nil) {
1478 [host_ release];
1479 host_ = nil;
1480 }
1481
1482 if (authority_ != nil) {
1483 [authority_ release];
1484 authority_ = nil;
1485 }
1486 }
1487
1488 - (void) dealloc {
1489 // XXX: this is a very inefficient way to call these deconstructors
1490 [self _clear];
1491 [super dealloc];
1492 }
1493
1494 + (NSArray *) _attributeKeys {
1495 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1496 }
1497
1498 - (NSArray *) attributeKeys {
1499 return [[self class] _attributeKeys];
1500 }
1501
1502 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1503 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1504 }
1505
1506 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1507 [self _clear];
1508
1509 trusted_ = index->IsTrusted();
1510
1511 uri_.set(pool, index->GetURI());
1512 distribution_.set(pool, index->GetDist());
1513 type_.set(pool, index->GetType());
1514
1515 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1516 if (dindex != NULL) {
1517 FileFd fd;
1518 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1519 _error->Discard();
1520 else {
1521 pkgTagFile tags(&fd);
1522
1523 pkgTagSection section;
1524 tags.Step(section);
1525
1526 struct {
1527 const char *name_;
1528 CYString *value_;
1529 } names[] = {
1530 {"default-icon", &defaultIcon_},
1531 {"depiction", &depiction_},
1532 {"description", &description_},
1533 {"label", &label_},
1534 {"origin", &origin_},
1535 {"support", &support_},
1536 {"version", &version_},
1537 };
1538
1539 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1540 const char *start, *end;
1541
1542 if (section.Find(names[i].name_, start, end)) {
1543 CYString &value(*names[i].value_);
1544 value.set(pool, start, end - start);
1545 }
1546 }
1547 }
1548 }
1549
1550 record_ = [Sources_ objectForKey:[self key]];
1551 if (record_ != nil)
1552 record_ = [record_ retain];
1553
1554 NSURL *url([NSURL URLWithString:uri_]);
1555
1556 host_ = [url host];
1557 if (host_ != nil)
1558 host_ = [[host_ lowercaseString] retain];
1559
1560 if (host_ != nil)
1561 authority_ = host_;
1562 else
1563 authority_ = [url path];
1564
1565 if (authority_ != nil)
1566 authority_ = [authority_ retain];
1567 }
1568
1569 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1570 if ((self = [super init]) != nil) {
1571 [self setMetaIndex:index inPool:pool];
1572 } return self;
1573 }
1574
1575 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1576 NSDictionary *lhr = [self record];
1577 NSDictionary *rhr = [source record];
1578
1579 if (lhr != rhr)
1580 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1581
1582 NSString *lhs = [self name];
1583 NSString *rhs = [source name];
1584
1585 if ([lhs length] != 0 && [rhs length] != 0) {
1586 unichar lhc = [lhs characterAtIndex:0];
1587 unichar rhc = [rhs characterAtIndex:0];
1588
1589 if (isalpha(lhc) && !isalpha(rhc))
1590 return NSOrderedAscending;
1591 else if (!isalpha(lhc) && isalpha(rhc))
1592 return NSOrderedDescending;
1593 }
1594
1595 return [lhs compare:rhs options:LaxCompareOptions_];
1596 }
1597
1598 - (NSString *) depictionForPackage:(NSString *)package {
1599 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1600 }
1601
1602 - (NSString *) supportForPackage:(NSString *)package {
1603 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1604 }
1605
1606 - (NSDictionary *) record {
1607 return record_;
1608 }
1609
1610 - (BOOL) trusted {
1611 return trusted_;
1612 }
1613
1614 - (NSString *) uri {
1615 return uri_;
1616 }
1617
1618 - (NSString *) distribution {
1619 return distribution_;
1620 }
1621
1622 - (NSString *) type {
1623 return type_;
1624 }
1625
1626 - (NSString *) key {
1627 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1628 }
1629
1630 - (NSString *) host {
1631 return host_;
1632 }
1633
1634 - (NSString *) name {
1635 return origin_.empty() ? authority_ : origin_;
1636 }
1637
1638 - (NSString *) description {
1639 return description_;
1640 }
1641
1642 - (NSString *) label {
1643 return label_.empty() ? authority_ : label_;
1644 }
1645
1646 - (NSString *) origin {
1647 return origin_;
1648 }
1649
1650 - (NSString *) version {
1651 return version_;
1652 }
1653
1654 - (NSString *) defaultIcon {
1655 return defaultIcon_;
1656 }
1657
1658 @end
1659 /* }}} */
1660 /* Relationship Class {{{ */
1661 @interface Relationship : NSObject {
1662 NSString *type_;
1663 NSString *id_;
1664 }
1665
1666 - (NSString *) type;
1667 - (NSString *) id;
1668 - (NSString *) name;
1669
1670 @end
1671
1672 @implementation Relationship
1673
1674 - (void) dealloc {
1675 [type_ release];
1676 [id_ release];
1677 [super dealloc];
1678 }
1679
1680 - (NSString *) type {
1681 return type_;
1682 }
1683
1684 - (NSString *) id {
1685 return id_;
1686 }
1687
1688 - (NSString *) name {
1689 _assert(false);
1690 return nil;
1691 }
1692
1693 @end
1694 /* }}} */
1695 /* Package Class {{{ */
1696 @interface Package : NSObject {
1697 unsigned era_;
1698 apr_pool_t *pool_;
1699
1700 pkgCache::VerIterator version_;
1701 pkgCache::PkgIterator iterator_;
1702 _transient Database *database_;
1703 pkgCache::VerFileIterator file_;
1704
1705 Source *source_;
1706 bool parsed_;
1707
1708 CYString section_;
1709 _transient NSString *section$_;
1710 bool essential_;
1711 bool required_;
1712 bool visible_;
1713 bool obsolete_;
1714
1715 NSString *latest_;
1716 CYString installed_;
1717
1718 CYString id_;
1719 CYString name_;
1720 CYString tagline_;
1721 CYString icon_;
1722 CYString depiction_;
1723 CYString homepage_;
1724
1725 CYString sponsor_;
1726 Address *sponsor$_;
1727
1728 CYString author_;
1729 Address *author$_;
1730
1731 CYString bugs_;
1732 CYString support_;
1733 NSMutableArray *tags_;
1734 NSString *role_;
1735
1736 NSArray *relationships_;
1737
1738 NSMutableDictionary *metadata_;
1739 _transient NSDate *firstSeen_;
1740 _transient NSDate *lastSeen_;
1741 bool subscribed_;
1742 }
1743
1744 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1745 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1746
1747 - (pkgCache::PkgIterator) iterator;
1748 - (void) parse;
1749
1750 - (NSString *) section;
1751 - (NSString *) simpleSection;
1752
1753 - (NSString *) longSection;
1754 - (NSString *) shortSection;
1755
1756 - (NSString *) uri;
1757
1758 - (Address *) maintainer;
1759 - (size_t) size;
1760 - (NSString *) longDescription;
1761 - (NSString *) shortDescription;
1762 - (unichar) index;
1763
1764 - (NSMutableDictionary *) metadata;
1765 - (NSDate *) seen;
1766 - (BOOL) subscribed;
1767 - (BOOL) ignored;
1768
1769 - (NSString *) latest;
1770 - (NSString *) installed;
1771 - (BOOL) uninstalled;
1772
1773 - (BOOL) valid;
1774 - (BOOL) upgradableAndEssential:(BOOL)essential;
1775 - (BOOL) essential;
1776 - (BOOL) broken;
1777 - (BOOL) unfiltered;
1778 - (BOOL) visible;
1779
1780 - (BOOL) half;
1781 - (BOOL) halfConfigured;
1782 - (BOOL) halfInstalled;
1783 - (BOOL) hasMode;
1784 - (NSString *) mode;
1785
1786 - (void) setVisible;
1787
1788 - (NSString *) id;
1789 - (NSString *) name;
1790 - (UIImage *) icon;
1791 - (NSString *) homepage;
1792 - (NSString *) depiction;
1793 - (Address *) author;
1794
1795 - (NSString *) support;
1796
1797 - (NSArray *) files;
1798 - (NSArray *) relationships;
1799 - (NSArray *) warnings;
1800 - (NSArray *) applications;
1801
1802 - (Source *) source;
1803 - (NSString *) role;
1804
1805 - (BOOL) matches:(NSString *)text;
1806
1807 - (bool) hasSupportingRole;
1808 - (BOOL) hasTag:(NSString *)tag;
1809 - (NSString *) primaryPurpose;
1810 - (NSArray *) purposes;
1811 - (bool) isCommercial;
1812
1813 - (CYString &) cyname;
1814
1815 - (uint32_t) compareBySection:(NSArray *)sections;
1816
1817 - (uint32_t) compareForChanges;
1818
1819 - (void) install;
1820 - (void) remove;
1821
1822 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1823 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1824 - (bool) isInstalledAndVisible:(NSNumber *)number;
1825 - (bool) isVisibleInSection:(NSString *)section;
1826 - (bool) isVisibleInSource:(Source *)source;
1827
1828 @end
1829
1830 uint32_t PackageChangesRadix(Package *self, void *) {
1831 union {
1832 uint32_t key;
1833
1834 struct {
1835 uint32_t timestamp : 30;
1836 uint32_t ignored : 1;
1837 uint32_t upgradable : 1;
1838 } bits;
1839 } value;
1840
1841 bool upgradable([self upgradableAndEssential:YES]);
1842 value.bits.upgradable = upgradable ? 1 : 0;
1843
1844 if (upgradable) {
1845 value.bits.timestamp = 0;
1846 value.bits.ignored = [self ignored] ? 0 : 1;
1847 value.bits.upgradable = 1;
1848 } else {
1849 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1850 value.bits.ignored = 0;
1851 value.bits.upgradable = 0;
1852 }
1853
1854 return _not(uint32_t) - value.key;
1855 }
1856
1857 _finline static void Stifle(uint8_t &value) {
1858 }
1859
1860 uint32_t PackagePrefixRadix(Package *self, void *context) {
1861 size_t offset(reinterpret_cast<size_t>(context));
1862 CYString &name([self cyname]);
1863
1864 size_t size(name.size());
1865 if (size == 0)
1866 return 0;
1867 char *text(name.data());
1868
1869 size_t zeros;
1870 if (!isdigit(text[0]))
1871 zeros = 0;
1872 else {
1873 size_t digits(1);
1874 while (size != digits && isdigit(text[digits]))
1875 if (++digits == 4)
1876 break;
1877 zeros = 4 - digits;
1878 }
1879
1880 uint8_t data[4];
1881
1882 // 0.607997
1883
1884 if (offset == 0 && zeros != 0) {
1885 memset(data, '0', zeros);
1886 memcpy(data + zeros, text, 4 - zeros);
1887 } else {
1888 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1889 if (size <= offset - zeros)
1890 return 0;
1891
1892 text += offset - zeros;
1893 size -= offset - zeros;
1894
1895 if (size >= 4)
1896 memcpy(data, text, 4);
1897 else {
1898 memcpy(data, text, size);
1899 memset(data + size, 0, 4 - size);
1900 }
1901
1902 for (size_t i(0); i != 4; ++i)
1903 if (isalpha(data[i]))
1904 data[i] |= 0x20;
1905 }
1906
1907 if (offset == 0)
1908 if (data[0] == '@')
1909 data[0] = 0x7f;
1910 else
1911 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1912
1913 /* XXX: ntohl may be more honest */
1914 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1915 }
1916
1917 CYString &(*PackageName)(Package *self, SEL sel);
1918
1919 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1920 _profile(PackageNameCompare)
1921 CYString &lhi(PackageName(lhs, @selector(cyname)));
1922 CYString &rhi(PackageName(rhs, @selector(cyname)));
1923 CFStringRef lhn(lhi), rhn(rhi);
1924
1925 if (lhn == NULL)
1926 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1927 else if (rhn == NULL)
1928 return NSOrderedDescending;
1929
1930 _profile(PackageNameCompare$NumbersLast)
1931 if (!lhi.empty() && !rhi.empty()) {
1932 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1933 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1934 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1935 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1936 return lha ? NSOrderedAscending : NSOrderedDescending;
1937 }
1938 _end
1939
1940 CFIndex length = CFStringGetLength(lhn);
1941
1942 _profile(PackageNameCompare$Compare)
1943 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1944 _end
1945 _end
1946 }
1947
1948 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1949 return PackageNameCompare(*lhs, *rhs, context);
1950 }
1951
1952 struct PackageNameOrdering :
1953 std::binary_function<Package *, Package *, bool>
1954 {
1955 _finline bool operator ()(Package *lhs, Package *rhs) const {
1956 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1957 }
1958 };
1959
1960 @implementation Package
1961
1962 - (NSString *) description {
1963 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1964 }
1965
1966 - (void) dealloc {
1967 if (source_ != nil)
1968 [source_ release];
1969
1970 if (latest_ != nil)
1971 [latest_ release];
1972
1973 if (sponsor$_ != nil)
1974 [sponsor$_ release];
1975 if (author$_ != nil)
1976 [author$_ release];
1977 if (tags_ != nil)
1978 [tags_ release];
1979 if (role_ != nil)
1980 [role_ release];
1981
1982 if (relationships_ != nil)
1983 [relationships_ release];
1984 if (metadata_ != nil)
1985 [metadata_ release];
1986
1987 [super dealloc];
1988 }
1989
1990 + (NSString *) webScriptNameForSelector:(SEL)selector {
1991 if (selector == @selector(hasTag:))
1992 return @"hasTag";
1993 else
1994 return nil;
1995 }
1996
1997 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1998 return [self webScriptNameForSelector:selector] == nil;
1999 }
2000
2001 + (NSArray *) _attributeKeys {
2002 return [NSArray arrayWithObjects:@"applications", @"author", @"depiction", @"longDescription", @"essential", @"homepage", @"icon", @"id", @"installed", @"latest", @"longSection", @"maintainer", @"mode", @"name", @"purposes", @"section", @"shortDescription", @"shortSection", @"simpleSection", @"size", @"source", @"sponsor", @"support", @"warnings", nil];
2003 }
2004
2005 - (NSArray *) attributeKeys {
2006 return [[self class] _attributeKeys];
2007 }
2008
2009 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2010 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2011 }
2012
2013 - (void) parse {
2014 if (parsed_)
2015 return;
2016 parsed_ = true;
2017 if (file_.end())
2018 return;
2019
2020 _profile(Package$parse)
2021 pkgRecords::Parser *parser;
2022
2023 _profile(Package$parse$Lookup)
2024 parser = &[database_ records]->Lookup(file_);
2025 _end
2026
2027 CYString website;
2028
2029 _profile(Package$parse$Find)
2030 struct {
2031 const char *name_;
2032 CYString *value_;
2033 } names[] = {
2034 {"icon", &icon_},
2035 {"depiction", &depiction_},
2036 {"homepage", &homepage_},
2037 {"website", &website},
2038 {"bugs", &bugs_},
2039 {"support", &support_},
2040 {"sponsor", &sponsor_},
2041 {"author", &author_},
2042 };
2043
2044 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2045 const char *start, *end;
2046
2047 if (parser->Find(names[i].name_, start, end)) {
2048 CYString &value(*names[i].value_);
2049 _profile(Package$parse$Value)
2050 value.set(pool_, start, end - start);
2051 _end
2052 }
2053 }
2054 _end
2055
2056 _profile(Package$parse$Tagline)
2057 const char *start, *end;
2058 if (parser->ShortDesc(start, end)) {
2059 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2060 if (stop == NULL)
2061 stop = end;
2062 while (stop != start && stop[-1] == '\r')
2063 --stop;
2064 tagline_.set(pool_, start, stop - start);
2065 }
2066 _end
2067
2068 _profile(Package$parse$Retain)
2069 if (homepage_.empty())
2070 homepage_ = website;
2071 if (homepage_ == depiction_)
2072 homepage_.clear();
2073 _end
2074 _end
2075 }
2076
2077 - (void) setVisible {
2078 visible_ = required_ && [self unfiltered];
2079 }
2080
2081 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2082 if ((self = [super init]) != nil) {
2083 _profile(Package$initWithVersion)
2084 era_ = [database era];
2085 pool_ = pool;
2086
2087 version_ = version;
2088
2089 _profile(Package$initWithVersion$ParentPkg)
2090 iterator_ = version.ParentPkg();
2091 _end
2092
2093 database_ = database;
2094
2095 _profile(Package$initWithVersion$Latest)
2096 const char *latest(StripVersion_(version_.VerStr()));
2097 latest_ = (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(latest), strlen(latest), kCFStringEncodingASCII, NO);
2098 _end
2099
2100 pkgCache::VerIterator current;
2101 _profile(Package$initWithVersion$Versions)
2102 current = iterator_.CurrentVer();
2103 if (!current.end())
2104 installed_.set(pool_, StripVersion_(current.VerStr()));
2105
2106 if (!version_.end())
2107 file_ = version_.FileList();
2108 else {
2109 pkgCache &cache([database_ cache]);
2110 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2111 }
2112 _end
2113
2114 _profile(Package$initWithVersion$Name)
2115 id_.set(pool_, iterator_.Name());
2116 name_.set(pool, iterator_.Display());
2117 _end
2118
2119 _profile(Package$initWithVersion$lowercaseString)
2120 char *data(id_.data());
2121 for (size_t i(0), e(id_.size()); i != e; ++i)
2122 // XXX: do not use tolower() as this is not locale-specific? :(
2123 data[i] |= 0x20;
2124 _end
2125
2126 if (!file_.end()) {
2127 _profile(Package$initWithVersion$Source)
2128 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2129 _end
2130 }
2131
2132 required_ = true;
2133
2134 _profile(Package$initWithVersion$Tags)
2135 pkgCache::TagIterator tag(iterator_.TagList());
2136 if (!tag.end()) {
2137 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2138 do {
2139 const char *name(tag.Name());
2140 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2141 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2142 role_ = (NSString *) CYStringCreate(name + 6);
2143 if (required_ && strncmp(name, "require::", 9) == 0 && (
2144 true
2145 ))
2146 required_ = false;
2147 ++tag;
2148 } while (!tag.end());
2149 }
2150 _end
2151
2152 bool changed(false);
2153
2154 _profile(Package$initWithVersion$Metadata)
2155 metadata_ = [Packages_ objectForKey:id_];
2156
2157 if (metadata_ == nil) {
2158 firstSeen_ = now_;
2159
2160 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2161 firstSeen_, @"FirstSeen",
2162 latest_, @"LastVersion",
2163 nil] mutableCopy];
2164
2165 changed = true;
2166 } else {
2167 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2168 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2169
2170 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2171 subscribed_ = [subscribed boolValue];
2172
2173 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2174
2175 if (firstSeen_ == nil) {
2176 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2177 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2178 changed = true;
2179 }
2180
2181 if (version == nil) {
2182 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2183 changed = true;
2184 } else if (![version isEqualToString:latest_]) {
2185 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2186 lastSeen_ = now_;
2187 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2188 changed = true;
2189 }
2190 }
2191
2192 metadata_ = [metadata_ retain];
2193
2194 if (changed) {
2195 [Packages_ setObject:metadata_ forKey:id_];
2196 Changed_ = true;
2197 }
2198 _end
2199
2200 _profile(Package$initWithVersion$Section)
2201 section_.set(pool_, iterator_.Section());
2202 _end
2203
2204 _profile(Package$initWithVersion$hasTag)
2205 obsolete_ = [self hasTag:@"cydia::obsolete"];
2206 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2207 _end
2208
2209 _profile(Package$initWithVersion$setVisible)
2210 [self setVisible];
2211 _end
2212 _end } return self;
2213 }
2214
2215 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2216 pkgCache::VerIterator version;
2217
2218 _profile(Package$packageWithIterator$GetCandidateVer)
2219 version = [database policy]->GetCandidateVer(iterator);
2220 _end
2221
2222 if (version.end())
2223 return nil;
2224
2225 return [[[Package alloc]
2226 initWithVersion:version
2227 withZone:zone
2228 inPool:pool
2229 database:database
2230 ] autorelease];
2231 }
2232
2233 - (pkgCache::PkgIterator) iterator {
2234 return iterator_;
2235 }
2236
2237 - (NSString *) section {
2238 if (section$_ == nil) {
2239 if (section_.empty())
2240 return nil;
2241
2242 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2243 NSString *name(section_);
2244
2245 lookup:
2246 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2247 if (NSString *rename = [value objectForKey:@"Rename"]) {
2248 name = rename;
2249 goto lookup;
2250 }
2251
2252 section$_ = name;
2253 } return section$_;
2254 }
2255
2256 - (NSString *) simpleSection {
2257 if (NSString *section = [self section])
2258 return Simplify(section);
2259 else
2260 return nil;
2261 }
2262
2263 - (NSString *) longSection {
2264 return LocalizeSection([self section]);
2265 }
2266
2267 - (NSString *) shortSection {
2268 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2269 }
2270
2271 - (NSString *) uri {
2272 return nil;
2273 #if 0
2274 pkgIndexFile *index;
2275 pkgCache::PkgFileIterator file(file_.File());
2276 if (![database_ list].FindIndex(file, index))
2277 return nil;
2278 return [NSString stringWithUTF8String:iterator_->Path];
2279 //return [NSString stringWithUTF8String:file.Site()];
2280 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2281 #endif
2282 }
2283
2284 - (Address *) maintainer {
2285 if (file_.end())
2286 return nil;
2287 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2288 const std::string &maintainer(parser->Maintainer());
2289 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2290 }
2291
2292 - (size_t) size {
2293 return version_.end() ? 0 : version_->InstalledSize;
2294 }
2295
2296 - (NSString *) longDescription {
2297 @synchronized (database_) {
2298 if ([database_ era] != era_ || file_.end())
2299 return nil;
2300
2301 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2302 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2303
2304 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2305 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2306 if ([lines count] < 2)
2307 return nil;
2308
2309 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2310 for (size_t i(1), e([lines count]); i != e; ++i) {
2311 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2312 [trimmed addObject:trim];
2313 }
2314
2315 return [trimmed componentsJoinedByString:@"\n"];
2316 } }
2317
2318 - (NSString *) shortDescription {
2319 return tagline_;
2320 }
2321
2322 - (unichar) index {
2323 _profile(Package$index)
2324 CFStringRef name((CFStringRef) [self name]);
2325 if (CFStringGetLength(name) == 0)
2326 return '#';
2327 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2328 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2329 return '#';
2330 return toupper(character);
2331 _end
2332 }
2333
2334 - (NSMutableDictionary *) metadata {
2335 return metadata_;
2336 }
2337
2338 - (NSDate *) seen {
2339 if (subscribed_ && lastSeen_ != nil)
2340 return lastSeen_;
2341 return firstSeen_;
2342 }
2343
2344 - (BOOL) subscribed {
2345 return subscribed_;
2346 }
2347
2348 - (BOOL) ignored {
2349 NSDictionary *metadata([self metadata]);
2350 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2351 return [ignored boolValue];
2352 else
2353 return false;
2354 }
2355
2356 - (NSString *) latest {
2357 return latest_;
2358 }
2359
2360 - (NSString *) installed {
2361 return installed_;
2362 }
2363
2364 - (BOOL) uninstalled {
2365 return installed_.empty();
2366 }
2367
2368 - (BOOL) valid {
2369 return !version_.end();
2370 }
2371
2372 - (BOOL) upgradableAndEssential:(BOOL)essential {
2373 _profile(Package$upgradableAndEssential)
2374 pkgCache::VerIterator current(iterator_.CurrentVer());
2375 if (current.end())
2376 return essential && essential_ && visible_;
2377 else
2378 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2379 _end
2380 }
2381
2382 - (BOOL) essential {
2383 return essential_;
2384 }
2385
2386 - (BOOL) broken {
2387 return [database_ cache][iterator_].InstBroken();
2388 }
2389
2390 - (BOOL) unfiltered {
2391 _profile(Package$unfiltered$obsolete)
2392 if (obsolete_)
2393 return false;
2394 _end
2395
2396 _profile(Package$unfiltered$hasSupportingRole)
2397 if (![self hasSupportingRole])
2398 return false;
2399 _end
2400
2401 NSString *section;
2402
2403 _profile(Package$unfiltered$section)
2404 section = [self section];
2405 _end
2406
2407 _profile(Package$unfiltered$isSectionVisible)
2408 if (section != nil && !isSectionVisible(section))
2409 return false;
2410 _end
2411
2412 return true;
2413 }
2414
2415 - (BOOL) visible {
2416 return visible_;
2417 }
2418
2419 - (BOOL) half {
2420 unsigned char current(iterator_->CurrentState);
2421 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2422 }
2423
2424 - (BOOL) halfConfigured {
2425 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2426 }
2427
2428 - (BOOL) halfInstalled {
2429 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2430 }
2431
2432 - (BOOL) hasMode {
2433 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2434 return state.Mode != pkgDepCache::ModeKeep;
2435 }
2436
2437 - (NSString *) mode {
2438 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2439
2440 switch (state.Mode) {
2441 case pkgDepCache::ModeDelete:
2442 if ((state.iFlags & pkgDepCache::Purge) != 0)
2443 return @"PURGE";
2444 else
2445 return @"REMOVE";
2446 case pkgDepCache::ModeKeep:
2447 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2448 return @"REINSTALL";
2449 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2450 return nil;*/
2451 else
2452 return nil;
2453 case pkgDepCache::ModeInstall:
2454 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2455 return @"REINSTALL";
2456 else*/ switch (state.Status) {
2457 case -1:
2458 return @"DOWNGRADE";
2459 case 0:
2460 return @"INSTALL";
2461 case 1:
2462 return @"UPGRADE";
2463 case 2:
2464 return @"NEW_INSTALL";
2465 _nodefault
2466 }
2467 _nodefault
2468 }
2469 }
2470
2471 - (NSString *) id {
2472 return id_;
2473 }
2474
2475 - (NSString *) name {
2476 return name_.empty() ? id_ : name_;
2477 }
2478
2479 - (UIImage *) icon {
2480 NSString *section = [self simpleSection];
2481
2482 UIImage *icon(nil);
2483 if (!icon_.empty())
2484 if ([static_cast<id>(icon_) hasPrefix:@"file:///"])
2485 // XXX: correct escaping
2486 icon = [UIImage imageAtPath:[static_cast<id>(icon_) substringFromIndex:7]];
2487 if (icon == nil) if (section != nil)
2488 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2489 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2490 if ([dicon hasPrefix:@"file:///"])
2491 // XXX: correct escaping
2492 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2493 if (icon == nil)
2494 icon = [UIImage applicationImageNamed:@"unknown.png"];
2495 return icon;
2496 }
2497
2498 - (NSString *) homepage {
2499 return homepage_;
2500 }
2501
2502 - (NSString *) depiction {
2503 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2504 }
2505
2506 - (Address *) sponsor {
2507 if (sponsor$_ == nil) {
2508 if (sponsor_.empty())
2509 return nil;
2510 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2511 } return sponsor$_;
2512 }
2513
2514 - (Address *) author {
2515 if (author$_ == nil) {
2516 if (author_.empty())
2517 return nil;
2518 author$_ = [[Address addressWithString:author_] retain];
2519 } return author$_;
2520 }
2521
2522 - (NSString *) support {
2523 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2524 }
2525
2526 - (NSArray *) files {
2527 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2528 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2529
2530 std::ifstream fin;
2531 fin.open([path UTF8String]);
2532 if (!fin.is_open())
2533 return nil;
2534
2535 std::string line;
2536 while (std::getline(fin, line))
2537 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2538
2539 return files;
2540 }
2541
2542 - (NSArray *) relationships {
2543 return relationships_;
2544 }
2545
2546 - (NSArray *) warnings {
2547 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2548 const char *name(iterator_.Name());
2549
2550 size_t length(strlen(name));
2551 if (length < 2) invalid:
2552 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2553 else for (size_t i(0); i != length; ++i)
2554 if (
2555 /* XXX: technically this is not allowed */
2556 (name[i] < 'A' || name[i] > 'Z') &&
2557 (name[i] < 'a' || name[i] > 'z') &&
2558 (name[i] < '0' || name[i] > '9') &&
2559 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2560 ) goto invalid;
2561
2562 if (strcmp(name, "cydia") != 0) {
2563 bool cydia = false;
2564 bool user = false;
2565 bool _private = false;
2566 bool stash = false;
2567
2568 bool repository = [[self section] isEqualToString:@"Repositories"];
2569
2570 if (NSArray *files = [self files])
2571 for (NSString *file in files)
2572 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2573 cydia = true;
2574 else if (!user && [file isEqualToString:@"/User"])
2575 user = true;
2576 else if (!_private && [file isEqualToString:@"/private"])
2577 _private = true;
2578 else if (!stash && [file isEqualToString:@"/var/stash"])
2579 stash = true;
2580
2581 /* XXX: this is not sensitive enough. only some folders are valid. */
2582 if (cydia && !repository)
2583 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2584 if (user)
2585 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2586 if (_private)
2587 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2588 if (stash)
2589 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2590 }
2591
2592 return [warnings count] == 0 ? nil : warnings;
2593 }
2594
2595 - (NSArray *) applications {
2596 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2597
2598 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2599
2600 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2601 if (NSArray *files = [self files])
2602 for (NSString *file in files)
2603 if (application_r(file)) {
2604 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2605 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2606 if ([id isEqualToString:me])
2607 continue;
2608
2609 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2610 if (display == nil)
2611 display = application_r[1];
2612
2613 NSString *bundle([file stringByDeletingLastPathComponent]);
2614 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2615 if (icon == nil || [icon length] == 0)
2616 icon = @"icon.png";
2617 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2618
2619 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2620 [applications addObject:application];
2621
2622 [application addObject:id];
2623 [application addObject:display];
2624 [application addObject:url];
2625 }
2626
2627 return [applications count] == 0 ? nil : applications;
2628 }
2629
2630 - (Source *) source {
2631 if (source_ == nil) {
2632 @synchronized (database_) {
2633 if ([database_ era] != era_ || file_.end())
2634 source_ = (Source *) [NSNull null];
2635 else
2636 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2637 }
2638 }
2639
2640 return source_ == (Source *) [NSNull null] ? nil : source_;
2641 }
2642
2643 - (NSString *) role {
2644 return role_;
2645 }
2646
2647 - (BOOL) matches:(NSString *)text {
2648 if (text == nil)
2649 return NO;
2650
2651 NSRange range;
2652
2653 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2654 if (range.location != NSNotFound)
2655 return YES;
2656
2657 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2658 if (range.location != NSNotFound)
2659 return YES;
2660
2661 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2662 if (range.location != NSNotFound)
2663 return YES;
2664
2665 return NO;
2666 }
2667
2668 - (bool) hasSupportingRole {
2669 if (role_ == nil)
2670 return true;
2671 if ([role_ isEqualToString:@"enduser"])
2672 return true;
2673 if ([Role_ isEqualToString:@"User"])
2674 return false;
2675 if ([role_ isEqualToString:@"hacker"])
2676 return true;
2677 if ([Role_ isEqualToString:@"Hacker"])
2678 return false;
2679 if ([role_ isEqualToString:@"developer"])
2680 return true;
2681 if ([Role_ isEqualToString:@"Developer"])
2682 return false;
2683 _assert(false);
2684 }
2685
2686 - (BOOL) hasTag:(NSString *)tag {
2687 return tags_ == nil ? NO : [tags_ containsObject:tag];
2688 }
2689
2690 - (NSString *) primaryPurpose {
2691 for (NSString *tag in tags_)
2692 if ([tag hasPrefix:@"purpose::"])
2693 return [tag substringFromIndex:9];
2694 return nil;
2695 }
2696
2697 - (NSArray *) purposes {
2698 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2699 for (NSString *tag in tags_)
2700 if ([tag hasPrefix:@"purpose::"])
2701 [purposes addObject:[tag substringFromIndex:9]];
2702 return [purposes count] == 0 ? nil : purposes;
2703 }
2704
2705 - (bool) isCommercial {
2706 return [self hasTag:@"cydia::commercial"];
2707 }
2708
2709 - (CYString &) cyname {
2710 return name_.empty() ? id_ : name_;
2711 }
2712
2713 - (uint32_t) compareBySection:(NSArray *)sections {
2714 NSString *section([self section]);
2715 for (size_t i(0), e([sections count]); i != e; ++i) {
2716 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2717 return i;
2718 }
2719
2720 return _not(uint32_t);
2721 }
2722
2723 - (uint32_t) compareForChanges {
2724 union {
2725 uint32_t key;
2726
2727 struct {
2728 uint32_t timestamp : 30;
2729 uint32_t ignored : 1;
2730 uint32_t upgradable : 1;
2731 } bits;
2732 } value;
2733
2734 bool upgradable([self upgradableAndEssential:YES]);
2735 value.bits.upgradable = upgradable ? 1 : 0;
2736
2737 if (upgradable) {
2738 value.bits.timestamp = 0;
2739 value.bits.ignored = [self ignored] ? 0 : 1;
2740 value.bits.upgradable = 1;
2741 } else {
2742 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2743 value.bits.ignored = 0;
2744 value.bits.upgradable = 0;
2745 }
2746
2747 return _not(uint32_t) - value.key;
2748 }
2749
2750 - (void) clear {
2751 @synchronized (database_) {
2752 pkgProblemResolver *resolver = [database_ resolver];
2753 resolver->Clear(iterator_);
2754
2755 pkgCacheFile &cache([database_ cache]);
2756 cache->SetReInstall(iterator_, false);
2757 cache->MarkKeep(iterator_, false);
2758 } }
2759
2760 - (void) install {
2761 @synchronized (database_) {
2762 pkgProblemResolver *resolver = [database_ resolver];
2763 resolver->Clear(iterator_);
2764 resolver->Protect(iterator_);
2765
2766 pkgCacheFile &cache([database_ cache]);
2767 cache->SetReInstall(iterator_, false);
2768 cache->MarkInstall(iterator_, false);
2769
2770 pkgDepCache::StateCache &state((*cache)[iterator_]);
2771 if (!state.Install())
2772 cache->SetReInstall(iterator_, true);
2773 } }
2774
2775 - (void) remove {
2776 @synchronized (database_) {
2777 pkgProblemResolver *resolver = [database_ resolver];
2778 resolver->Clear(iterator_);
2779 resolver->Remove(iterator_);
2780 resolver->Protect(iterator_);
2781
2782 pkgCacheFile &cache([database_ cache]);
2783 cache->SetReInstall(iterator_, false);
2784 cache->MarkDelete(iterator_, true);
2785 } }
2786
2787 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2788 _profile(Package$isUnfilteredAndSearchedForBy)
2789 bool value(true);
2790
2791 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2792 value &= [self unfiltered];
2793 _end
2794
2795 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2796 value &= [self matches:search];
2797 _end
2798
2799 return value;
2800 _end
2801 }
2802
2803 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2804 if ([search length] == 0)
2805 return false;
2806
2807 _profile(Package$isUnfilteredAndSelectedForBy)
2808 bool value(true);
2809
2810 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2811 value &= [self unfiltered];
2812 _end
2813
2814 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2815 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2816 _end
2817
2818 return value;
2819 _end
2820 }
2821
2822 - (bool) isInstalledAndVisible:(NSNumber *)number {
2823 return ((![number boolValue] && ![role_ isEqualToString:@"cydia"]) || [self visible]) && ![self uninstalled];
2824 }
2825
2826 - (bool) isVisibleInSection:(NSString *)name {
2827 NSString *section = [self section];
2828
2829 return
2830 [self visible] && (
2831 name == nil ||
2832 section == nil && [name length] == 0 ||
2833 [name isEqualToString:section]
2834 );
2835 }
2836
2837 - (bool) isVisibleInSource:(Source *)source {
2838 return [self source] == source && [self visible];
2839 }
2840
2841 @end
2842 /* }}} */
2843 /* Section Class {{{ */
2844 @interface Section : NSObject {
2845 NSString *name_;
2846 unichar index_;
2847 size_t row_;
2848 size_t count_;
2849 NSString *localized_;
2850 }
2851
2852 - (NSComparisonResult) compareByLocalized:(Section *)section;
2853 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2854 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2855 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2856 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2857 - (NSString *) name;
2858 - (unichar) index;
2859
2860 - (size_t) row;
2861 - (size_t) count;
2862
2863 - (void) addToRow;
2864 - (void) addToCount;
2865
2866 - (void) setCount:(size_t)count;
2867 - (NSString *) localized;
2868
2869 @end
2870
2871 @implementation Section
2872
2873 - (void) dealloc {
2874 [name_ release];
2875 if (localized_ != nil)
2876 [localized_ release];
2877 [super dealloc];
2878 }
2879
2880 - (NSComparisonResult) compareByLocalized:(Section *)section {
2881 NSString *lhs(localized_);
2882 NSString *rhs([section localized]);
2883
2884 /*if ([lhs length] != 0 && [rhs length] != 0) {
2885 unichar lhc = [lhs characterAtIndex:0];
2886 unichar rhc = [rhs characterAtIndex:0];
2887
2888 if (isalpha(lhc) && !isalpha(rhc))
2889 return NSOrderedAscending;
2890 else if (!isalpha(lhc) && isalpha(rhc))
2891 return NSOrderedDescending;
2892 }*/
2893
2894 return [lhs compare:rhs options:LaxCompareOptions_];
2895 }
2896
2897 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2898 if ((self = [self initWithName:name localize:NO]) != nil) {
2899 if (localized != nil)
2900 localized_ = [localized retain];
2901 } return self;
2902 }
2903
2904 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2905 return [self initWithName:name row:0 localize:localize];
2906 }
2907
2908 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2909 if ((self = [super init]) != nil) {
2910 name_ = [name retain];
2911 index_ = '\0';
2912 row_ = row;
2913 if (localize)
2914 localized_ = [LocalizeSection(name_) retain];
2915 } return self;
2916 }
2917
2918 /* XXX: localize the index thingees */
2919 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2920 if ((self = [super init]) != nil) {
2921 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2922 index_ = index;
2923 row_ = row;
2924 } return self;
2925 }
2926
2927 - (NSString *) name {
2928 return name_;
2929 }
2930
2931 - (unichar) index {
2932 return index_;
2933 }
2934
2935 - (size_t) row {
2936 return row_;
2937 }
2938
2939 - (size_t) count {
2940 return count_;
2941 }
2942
2943 - (void) addToRow {
2944 ++row_;
2945 }
2946
2947 - (void) addToCount {
2948 ++count_;
2949 }
2950
2951 - (void) setCount:(size_t)count {
2952 count_ = count;
2953 }
2954
2955 - (NSString *) localized {
2956 return localized_;
2957 }
2958
2959 @end
2960 /* }}} */
2961
2962 static NSString *Colon_;
2963 static NSString *Error_;
2964 static NSString *Warning_;
2965
2966 /* Database Implementation {{{ */
2967 @implementation Database
2968
2969 + (Database *) sharedInstance {
2970 static Database *instance;
2971 if (instance == nil)
2972 instance = [[Database alloc] init];
2973 return instance;
2974 }
2975
2976 - (unsigned) era {
2977 return era_;
2978 }
2979
2980 - (void) dealloc {
2981 // XXX: actually implement this thing
2982 _assert(false);
2983 NSRecycleZone(zone_);
2984 // XXX: malloc_destroy_zone(zone_);
2985 apr_pool_destroy(pool_);
2986 [super dealloc];
2987 }
2988
2989 - (void) _readCydia:(NSNumber *)fd { _pooled
2990 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2991 std::istream is(&ib);
2992 std::string line;
2993
2994 static Pcre finish_r("^finish:([^:]*)$");
2995
2996 while (std::getline(is, line)) {
2997 const char *data(line.c_str());
2998 size_t size = line.size();
2999 lprintf("C:%s\n", data);
3000
3001 if (finish_r(data, size)) {
3002 NSString *finish = finish_r[1];
3003 int index = [Finishes_ indexOfObject:finish];
3004 if (index != INT_MAX && index > Finish_)
3005 Finish_ = index;
3006 }
3007 }
3008
3009 _assume(false);
3010 }
3011
3012 - (void) _readStatus:(NSNumber *)fd { _pooled
3013 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3014 std::istream is(&ib);
3015 std::string line;
3016
3017 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3018 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3019
3020 while (std::getline(is, line)) {
3021 const char *data(line.c_str());
3022 size_t size(line.size());
3023 lprintf("S:%s\n", data);
3024
3025 if (conffile_r(data, size)) {
3026 [delegate_ setConfigurationData:conffile_r[1]];
3027 } else if (strncmp(data, "status: ", 8) == 0) {
3028 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3029 [delegate_ setProgressTitle:string];
3030 } else if (pmstatus_r(data, size)) {
3031 std::string type([pmstatus_r[1] UTF8String]);
3032 NSString *id = pmstatus_r[2];
3033
3034 float percent([pmstatus_r[3] floatValue]);
3035 [delegate_ setProgressPercent:(percent / 100)];
3036
3037 NSString *string = pmstatus_r[4];
3038
3039 if (type == "pmerror")
3040 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3041 withObject:[NSArray arrayWithObjects:string, id, nil]
3042 waitUntilDone:YES
3043 ];
3044 else if (type == "pmstatus") {
3045 [delegate_ setProgressTitle:string];
3046 } else if (type == "pmconffile")
3047 [delegate_ setConfigurationData:string];
3048 else
3049 lprintf("E:unknown pmstatus\n");
3050 } else
3051 lprintf("E:unknown status\n");
3052 }
3053
3054 _assume(false);
3055 }
3056
3057 - (void) _readOutput:(NSNumber *)fd { _pooled
3058 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3059 std::istream is(&ib);
3060 std::string line;
3061
3062 while (std::getline(is, line)) {
3063 lprintf("O:%s\n", line.c_str());
3064 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3065 }
3066
3067 _assume(false);
3068 }
3069
3070 - (FILE *) input {
3071 return input_;
3072 }
3073
3074 - (Package *) packageWithName:(NSString *)name {
3075 @synchronized (self) {
3076 if (static_cast<pkgDepCache *>(cache_) == NULL)
3077 return nil;
3078 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3079 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3080 } }
3081
3082 - (id) init {
3083 if ((self = [super init]) != nil) {
3084 policy_ = NULL;
3085 records_ = NULL;
3086 resolver_ = NULL;
3087 fetcher_ = NULL;
3088 lock_ = NULL;
3089
3090 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3091 apr_pool_create(&pool_, NULL);
3092
3093 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
3094
3095 int fds[2];
3096
3097 _assert(pipe(fds) != -1);
3098 cydiafd_ = fds[1];
3099
3100 _config->Set("APT::Keep-Fds::", cydiafd_);
3101 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3102
3103 [NSThread
3104 detachNewThreadSelector:@selector(_readCydia:)
3105 toTarget:self
3106 withObject:[NSNumber numberWithInt:fds[0]]
3107 ];
3108
3109 _assert(pipe(fds) != -1);
3110 statusfd_ = fds[1];
3111
3112 [NSThread
3113 detachNewThreadSelector:@selector(_readStatus:)
3114 toTarget:self
3115 withObject:[NSNumber numberWithInt:fds[0]]
3116 ];
3117
3118 _assert(pipe(fds) != -1);
3119 _assert(dup2(fds[0], 0) != -1);
3120 _assert(close(fds[0]) != -1);
3121
3122 input_ = fdopen(fds[1], "a");
3123
3124 _assert(pipe(fds) != -1);
3125 _assert(dup2(fds[1], 1) != -1);
3126 _assert(close(fds[1]) != -1);
3127
3128 [NSThread
3129 detachNewThreadSelector:@selector(_readOutput:)
3130 toTarget:self
3131 withObject:[NSNumber numberWithInt:fds[0]]
3132 ];
3133 } return self;
3134 }
3135
3136 - (pkgCacheFile &) cache {
3137 return cache_;
3138 }
3139
3140 - (pkgDepCache::Policy *) policy {
3141 return policy_;
3142 }
3143
3144 - (pkgRecords *) records {
3145 return records_;
3146 }
3147
3148 - (pkgProblemResolver *) resolver {
3149 return resolver_;
3150 }
3151
3152 - (pkgAcquire &) fetcher {
3153 return *fetcher_;
3154 }
3155
3156 - (pkgSourceList &) list {
3157 return *list_;
3158 }
3159
3160 - (NSArray *) packages {
3161 return (NSArray *) packages_;
3162 }
3163
3164 - (NSArray *) sources {
3165 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3166 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3167 [sources addObject:i->second];
3168 return sources;
3169 }
3170
3171 - (NSArray *) issues {
3172 if (cache_->BrokenCount() == 0)
3173 return nil;
3174
3175 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3176
3177 for (Package *package in [self packages]) {
3178 if (![package broken])
3179 continue;
3180 pkgCache::PkgIterator pkg([package iterator]);
3181
3182 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3183 [entry addObject:[package name]];
3184 [issues addObject:entry];
3185
3186 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3187 if (ver.end())
3188 continue;
3189
3190 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3191 pkgCache::DepIterator start;
3192 pkgCache::DepIterator end;
3193 dep.GlobOr(start, end); // ++dep
3194
3195 if (!cache_->IsImportantDep(end))
3196 continue;
3197 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3198 continue;
3199
3200 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3201 [entry addObject:failure];
3202 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3203
3204 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3205 if (Package *package = [self packageWithName:name])
3206 name = [package name];
3207 [failure addObject:name];
3208
3209 pkgCache::PkgIterator target(start.TargetPkg());
3210 if (target->ProvidesList != 0)
3211 [failure addObject:@"?"];
3212 else {
3213 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3214 if (!ver.end())
3215 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3216 else if (!cache_[target].CandidateVerIter(cache_).end())
3217 [failure addObject:@"-"];
3218 else if (target->ProvidesList == 0)
3219 [failure addObject:@"!"];
3220 else
3221 [failure addObject:@"%"];
3222 }
3223
3224 _forever {
3225 if (start.TargetVer() != 0)
3226 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3227 if (start == end)
3228 break;
3229 ++start;
3230 }
3231 }
3232 }
3233
3234 return issues;
3235 }
3236
3237 - (bool) popErrorWithTitle:(NSString *)title {
3238 bool fatal(false);
3239 std::string message;
3240
3241 while (!_error->empty()) {
3242 std::string error;
3243 bool warning(!_error->PopMessage(error));
3244 if (!warning)
3245 fatal = true;
3246 for (;;) {
3247 size_t size(error.size());
3248 if (size == 0 || error[size - 1] != '\n')
3249 break;
3250 error.resize(size - 1);
3251 }
3252 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3253
3254 if (!message.empty())
3255 message += "\n\n";
3256 message += error;
3257 }
3258
3259 if (fatal && !message.empty())
3260 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3261
3262 return fatal;
3263 }
3264
3265 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3266 return [self popErrorWithTitle:title] || !success;
3267 }
3268
3269 - (void) reloadData { CYPoolStart() {
3270 @synchronized (self) {
3271 ++era_;
3272
3273 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3274 CFArrayRemoveAllValues(packages_);
3275
3276 sources_.clear();
3277
3278 _error->Discard();
3279
3280 delete list_;
3281 list_ = NULL;
3282 manager_ = NULL;
3283 delete lock_;
3284 lock_ = NULL;
3285 delete fetcher_;
3286 fetcher_ = NULL;
3287 delete resolver_;
3288 resolver_ = NULL;
3289 delete records_;
3290 records_ = NULL;
3291 delete policy_;
3292 policy_ = NULL;
3293
3294 if (now_ != nil) {
3295 [now_ release];
3296 now_ = nil;
3297 }
3298
3299 cache_.Close();
3300
3301 apr_pool_clear(pool_);
3302 NSRecycleZone(zone_);
3303
3304 int chk(creat("/tmp/cydia.chk", 0644));
3305 if (chk != -1)
3306 close(chk);
3307
3308 NSString *title(UCLocalize("DATABASE"));
3309
3310 _trace();
3311 if (!cache_.Open(progress_, true)) { pop:
3312 std::string error;
3313 bool warning(!_error->PopMessage(error));
3314 lprintf("cache_.Open():[%s]\n", error.c_str());
3315
3316 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3317 [delegate_ repairWithSelector:@selector(configure)];
3318 else if (error == "The package lists or status file could not be parsed or opened.")
3319 [delegate_ repairWithSelector:@selector(update)];
3320 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3321 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3322 // else if (error == "The list of sources could not be read.")
3323 else
3324 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3325
3326 if (warning)
3327 goto pop;
3328 _error->Discard();
3329 return;
3330 }
3331 _trace();
3332
3333 unlink("/tmp/cydia.chk");
3334
3335 now_ = [[NSDate date] retain];
3336
3337 policy_ = new pkgDepCache::Policy();
3338 records_ = new pkgRecords(cache_);
3339 resolver_ = new pkgProblemResolver(cache_);
3340 fetcher_ = new pkgAcquire(&status_);
3341 lock_ = NULL;
3342
3343 list_ = new pkgSourceList();
3344 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3345 return;
3346
3347 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3348 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3349 return;
3350 }
3351
3352 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3353 return;
3354
3355 if (cache_->BrokenCount() != 0) {
3356 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3357 return;
3358
3359 if (cache_->BrokenCount() != 0) {
3360 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3361 return;
3362 }
3363
3364 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3365 return;
3366 }
3367
3368 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3369 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3370 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3371 // XXX: this could be more intelligent
3372 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3373 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3374 if (!cached.end())
3375 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3376 }
3377 }
3378
3379 {
3380 /*std::vector<Package *> packages;
3381 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3382 [packages_ release];
3383 packages_ = nil;*/
3384
3385 _trace();
3386
3387 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3388 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3389 //packages.push_back(package);
3390 CFArrayAppendValue(packages_, [package retain]);
3391
3392 _trace();
3393
3394 /*if (packages.empty())
3395 packages_ = [[NSArray alloc] init];
3396 else
3397 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3398 _trace();*/
3399
3400 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3401 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3402 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3403
3404 /*_trace();
3405 PrintTimes();
3406 _trace();*/
3407
3408 _trace();
3409
3410 /*if (!packages.empty())
3411 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3412 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3413
3414 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3415
3416 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3417
3418 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3419
3420 _trace();
3421 }
3422 } } CYPoolEnd() _trace(); }
3423
3424 - (void) clear {
3425 @synchronized (self) {
3426 delete resolver_;
3427 resolver_ = new pkgProblemResolver(cache_);
3428
3429 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3430 if (!cache_[iterator].Keep()) {
3431 cache_->MarkKeep(iterator, false);
3432 cache_->SetReInstall(iterator, false);
3433 }
3434 }
3435 } }
3436
3437 - (void) configure {
3438 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3439 system([dpkg UTF8String]);
3440 }
3441
3442 - (bool) clean {
3443 // XXX: I don't remember this condition
3444 if (lock_ != NULL)
3445 return false;
3446
3447 FileFd Lock;
3448 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3449
3450 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3451
3452 if ([self popErrorWithTitle:title])
3453 return false;
3454
3455 pkgAcquire fetcher;
3456 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3457
3458 class LogCleaner :
3459 public pkgArchiveCleaner
3460 {
3461 protected:
3462 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3463 unlink(File);
3464 }
3465 } cleaner;
3466
3467 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3468 return false;
3469
3470 return true;
3471 }
3472
3473 - (bool) prepare {
3474 fetcher_->Shutdown();
3475
3476 pkgRecords records(cache_);
3477
3478 lock_ = new FileFd();
3479 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3480
3481 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3482
3483 if ([self popErrorWithTitle:title])
3484 return false;
3485
3486 pkgSourceList list;
3487 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3488 return false;
3489
3490 manager_ = (_system->CreatePM(cache_));
3491 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3492 return false;
3493
3494 return true;
3495 }
3496
3497 - (void) perform {
3498 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3499
3500 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3501 pkgSourceList list;
3502 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3503 return;
3504 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3505 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3506 }
3507
3508 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3509 _trace();
3510 return;
3511 }
3512
3513 bool failed = false;
3514 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3515 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3516 continue;
3517 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3518 continue;
3519
3520 std::string uri = (*item)->DescURI();
3521 std::string error = (*item)->ErrorText;
3522
3523 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3524 failed = true;
3525
3526 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3527 withObject:[NSArray arrayWithObjects:
3528 [NSString stringWithUTF8String:error.c_str()],
3529 nil]
3530 waitUntilDone:YES
3531 ];
3532 }
3533
3534 if (failed) {
3535 _trace();
3536 return;
3537 }
3538
3539 _system->UnLock();
3540 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3541
3542 if (_error->PendingError()) {
3543 _trace();
3544 return;
3545 }
3546
3547 if (result == pkgPackageManager::Failed) {
3548 _trace();
3549 return;
3550 }
3551
3552 if (result != pkgPackageManager::Completed) {
3553 _trace();
3554 return;
3555 }
3556
3557 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3558 pkgSourceList list;
3559 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3560 return;
3561 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3562 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3563 }
3564
3565 if (![before isEqualToArray:after])
3566 [self update];
3567 }
3568
3569 - (bool) upgrade {
3570 NSString *title(UCLocalize("UPGRADE"));
3571 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3572 return false;
3573 return true;
3574 }
3575
3576 - (void) update {
3577 [self updateWithStatus:status_];
3578 }
3579
3580 - (void) setVisible {
3581 for (Package *package in [self packages])
3582 [package setVisible];
3583 }
3584
3585 - (void) updateWithStatus:(Status &)status {
3586 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3587 NSString *title(UCLocalize("REFRESHING_DATA"));
3588
3589 pkgSourceList list;
3590 if (!list.ReadMainList())
3591 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3592
3593 FileFd lock;
3594 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3595 if ([self popErrorWithTitle:title])
3596 return;
3597
3598 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3599 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3600 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3601
3602 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3603 Changed_ = true;
3604 }
3605
3606 - (void) setDelegate:(id)delegate {
3607 delegate_ = delegate;
3608 status_.setDelegate(delegate);
3609 progress_.setDelegate(delegate);
3610 }
3611
3612 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3613 SourceMap::const_iterator i(sources_.find(file->ID));
3614 return i == sources_.end() ? nil : i->second;
3615 }
3616
3617 @end
3618 /* }}} */
3619
3620 /* Confirmation Controller {{{ */
3621 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3622 if (!iterator.end())
3623 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3624 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3625 continue;
3626 pkgCache::PkgIterator package(dep.TargetPkg());
3627 if (package.end())
3628 continue;
3629 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3630 return true;
3631 }
3632
3633 return false;
3634 }
3635 /* }}} */
3636
3637 /* Web Scripting {{{ */
3638 @interface CydiaObject : NSObject {
3639 id indirect_;
3640 _transient id delegate_;
3641 }
3642
3643 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3644 @end
3645
3646 @implementation CydiaObject
3647
3648 - (void) dealloc {
3649 [indirect_ release];
3650 [super dealloc];
3651 }
3652
3653 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3654 if ((self = [super init]) != nil) {
3655 indirect_ = [indirect retain];
3656 } return self;
3657 }
3658
3659 - (void) setDelegate:(id)delegate {
3660 delegate_ = delegate;
3661 }
3662
3663 + (NSArray *) _attributeKeys {
3664 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3665 }
3666
3667 - (NSArray *) attributeKeys {
3668 return [[self class] _attributeKeys];
3669 }
3670
3671 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3672 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3673 }
3674
3675 - (NSString *) device {
3676 return [[UIDevice currentDevice] uniqueIdentifier];
3677 }
3678
3679 #if 0 // XXX: implement!
3680 - (NSString *) mac {
3681 if (![indirect_ promptForSensitive:@"Mac Address"])
3682 return nil;
3683 }
3684
3685 - (NSString *) serial {
3686 if (![indirect_ promptForSensitive:@"Serial #"])
3687 return nil;
3688 }
3689
3690 - (NSString *) firewire {
3691 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3692 return nil;
3693 }
3694
3695 - (NSString *) imei {
3696 if (![indirect_ promptForSensitive:@"IMEI"])
3697 return nil;
3698 }
3699 #endif
3700
3701 + (NSString *) webScriptNameForSelector:(SEL)selector {
3702 if (selector == @selector(close))
3703 return @"close";
3704 else if (selector == @selector(getInstalledPackages))
3705 return @"getInstalledPackages";
3706 else if (selector == @selector(getPackageById:))
3707 return @"getPackageById";
3708 else if (selector == @selector(installPackages:))
3709 return @"installPackages";
3710 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3711 return @"setButtonImage";
3712 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3713 return @"setButtonTitle";
3714 else if (selector == @selector(setPopupHook:))
3715 return @"setPopupHook";
3716 else if (selector == @selector(setSpecial:))
3717 return @"setSpecial";
3718 else if (selector == @selector(setToken:))
3719 return @"setToken";
3720 else if (selector == @selector(setViewportWidth:))
3721 return @"setViewportWidth";
3722 else if (selector == @selector(supports:))
3723 return @"supports";
3724 else if (selector == @selector(stringWithFormat:arguments:))
3725 return @"format";
3726 else if (selector == @selector(localizedStringForKey:value:table:))
3727 return @"localize";
3728 else if (selector == @selector(du:))
3729 return @"du";
3730 else if (selector == @selector(statfs:))
3731 return @"statfs";
3732 else
3733 return nil;
3734 }
3735
3736 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3737 return [self webScriptNameForSelector:selector] == nil;
3738 }
3739
3740 - (BOOL) supports:(NSString *)feature {
3741 return [feature isEqualToString:@"window.open"];
3742 }
3743
3744 - (NSArray *) getInstalledPackages {
3745 NSArray *packages([[Database sharedInstance] packages]);
3746 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3747 for (Package *package in packages)
3748 if ([package installed] != nil)
3749 [installed addObject:package];
3750 return installed;
3751 }
3752
3753 - (Package *) getPackageById:(NSString *)id {
3754 Package *package([[Database sharedInstance] packageWithName:id]);
3755 [package parse];
3756 return package;
3757 }
3758
3759 - (NSArray *) statfs:(NSString *)path {
3760 struct statfs stat;
3761
3762 if (path == nil || statfs([path UTF8String], &stat) == -1)
3763 return nil;
3764
3765 return [NSArray arrayWithObjects:
3766 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3767 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3768 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3769 nil];
3770 }
3771
3772 - (NSNumber *) du:(NSString *)path {
3773 NSNumber *value(nil);
3774
3775 int fds[2];
3776 _assert(pipe(fds) != -1);
3777
3778 pid_t pid(ExecFork());
3779 if (pid == 0) {
3780 _assert(dup2(fds[1], 1) != -1);
3781 _assert(close(fds[0]) != -1);
3782 _assert(close(fds[1]) != -1);
3783 /* XXX: this should probably not use du */
3784 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3785 exit(1);
3786 _assert(false);
3787 }
3788
3789 _assert(close(fds[1]) != -1);
3790
3791 if (FILE *du = fdopen(fds[0], "r")) {
3792 char line[1024];
3793 while (fgets(line, sizeof(line), du) != NULL) {
3794 size_t length(strlen(line));
3795 while (length != 0 && line[length - 1] == '\n')
3796 line[--length] = '\0';
3797 if (char *tab = strchr(line, '\t')) {
3798 *tab = '\0';
3799 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3800 }
3801 }
3802
3803 fclose(du);
3804 } else _assert(close(fds[0]));
3805
3806 int status;
3807 wait:
3808 if (waitpid(pid, &status, 0) == -1)
3809 if (errno == EINTR)
3810 goto wait;
3811 else _assert(false);
3812
3813 return value;
3814 }
3815
3816 - (void) close {
3817 [indirect_ close];
3818 }
3819
3820 - (void) installPackages:(NSArray *)packages {
3821 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3822 }
3823
3824 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3825 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3826 }
3827
3828 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3829 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3830 }
3831
3832 - (void) setSpecial:(id)function {
3833 [indirect_ setSpecial:function];
3834 }
3835
3836 - (void) setToken:(NSString *)token {
3837 if (Token_ != nil)
3838 [Token_ release];
3839 Token_ = [token retain];
3840
3841 [Metadata_ setObject:Token_ forKey:@"Token"];
3842 Changed_ = true;
3843 }
3844
3845 - (void) setPopupHook:(id)function {
3846 [indirect_ setPopupHook:function];
3847 }
3848
3849 - (void) setViewportWidth:(float)width {
3850 [indirect_ setViewportWidth:width];
3851 }
3852
3853 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3854 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3855 unsigned count([arguments count]);
3856 id values[count];
3857 for (unsigned i(0); i != count; ++i)
3858 values[i] = [arguments objectAtIndex:i];
3859 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3860 }
3861
3862 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3863 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3864 value = nil;
3865 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3866 table = nil;
3867 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3868 }
3869
3870 @end
3871 /* }}} */
3872
3873 /* Cydia Browser Controller {{{ */
3874 @interface CYBrowserController : BrowserController {
3875 CydiaObject *cydia_;
3876 }
3877
3878 @end
3879
3880 @implementation CYBrowserController
3881
3882 - (void) dealloc {
3883 [cydia_ release];
3884 [super dealloc];
3885 }
3886
3887 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3888 }
3889
3890 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3891 [super webView:view didClearWindowObject:window forFrame:frame];
3892
3893 WebDataSource *source([frame dataSource]);
3894 NSURLResponse *response([source response]);
3895 NSURL *url([response URL]);
3896 NSString *scheme([url scheme]);
3897
3898 NSHTTPURLResponse *http;
3899 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3900 http = (NSHTTPURLResponse *) response;
3901 else
3902 http = nil;
3903
3904 NSDictionary *headers([http allHeaderFields]);
3905 NSString *host([url host]);
3906 [self setHeaders:headers forHost:host];
3907
3908 if (
3909 [host isEqualToString:@"cydia.saurik.com"] ||
3910 [host hasSuffix:@".cydia.saurik.com"] ||
3911 [scheme isEqualToString:@"file"]
3912 )
3913 [window setValue:cydia_ forKey:@"cydia"];
3914 }
3915
3916 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3917 if (System_ != NULL)
3918 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3919 if (Machine_ != NULL)
3920 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3921 if (Token_ != nil)
3922 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3923 if (Role_ != nil)
3924 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3925 }
3926
3927 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3928 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3929 [self _setMoreHeaders:copy];
3930 return copy;
3931 }
3932
3933 - (void) setDelegate:(id)delegate {
3934 [super setDelegate:delegate];
3935 [cydia_ setDelegate:delegate];
3936 }
3937
3938 - (id) init {
3939 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3940 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3941
3942 WebView *webview([[webview_ _documentView] webView]);
3943
3944 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3945
3946 NSString *application = package == nil ? @"Cydia" : [NSString
3947 stringWithFormat:@"Cydia/%@",
3948 [package installed]
3949 ];
3950
3951 if (Safari_ != nil)
3952 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3953 if (Build_ != nil)
3954 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3955 if (Product_ != nil)
3956 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3957
3958 [webview setApplicationNameForUserAgent:application];
3959 } return self;
3960 }
3961
3962 @end
3963 /* }}} */
3964
3965 /* Confirmation {{{ */
3966 @protocol ConfirmationControllerDelegate
3967 - (void) cancelAndClear:(bool)clear;
3968 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3969 - (void) queue;
3970 @end
3971
3972 @interface ConfirmationController : CYBrowserController {
3973 _transient Database *database_;
3974 UIAlertView *essential_;
3975 NSArray *changes_;
3976 NSArray *issues_;
3977 NSArray *sizes_;
3978 BOOL substrate_;
3979 }
3980
3981 - (id) initWithDatabase:(Database *)database;
3982
3983 @end
3984
3985 @implementation ConfirmationController
3986
3987 - (void) dealloc {
3988 [changes_ release];
3989 if (issues_ != nil)
3990 [issues_ release];
3991 [sizes_ release];
3992 if (essential_ != nil)
3993 [essential_ release];
3994 [super dealloc];
3995 }
3996
3997 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3998 NSString *context([alert context]);
3999
4000 if ([context isEqualToString:@"remove"]) {
4001 if (button == [alert cancelButtonIndex]) {
4002 [self dismissModalViewControllerAnimated:YES];
4003 } else if (button == [alert firstOtherButtonIndex]) {
4004 if (substrate_)
4005 Finish_ = 2;
4006 [delegate_ confirmWithNavigationController:[self navigationController]];
4007 }
4008
4009 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4010 } else if ([context isEqualToString:@"unable"]) {
4011 [self dismissModalViewControllerAnimated:YES];
4012 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4013 } else {
4014 [super alertView:alert clickedButtonAtIndex:button];
4015 }
4016 }
4017
4018 - (void) _doContinue {
4019 [self dismissModalViewControllerAnimated:YES];
4020 [delegate_ cancelAndClear:NO];
4021 }
4022
4023 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4024 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4025 return nil;
4026 }
4027
4028 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4029 [super webView:view didClearWindowObject:window forFrame:frame];
4030 [window setValue:changes_ forKey:@"changes"];
4031 [window setValue:issues_ forKey:@"issues"];
4032 [window setValue:sizes_ forKey:@"sizes"];
4033 [window setValue:self forKey:@"queue"];
4034 }
4035
4036 - (id) initWithDatabase:(Database *)database {
4037 if ((self = [super init]) != nil) {
4038 database_ = database;
4039
4040 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4041
4042 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4043 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4044 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4045 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4046 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4047
4048 bool remove(false);
4049
4050 pkgDepCache::Policy *policy([database_ policy]);
4051
4052 pkgCacheFile &cache([database_ cache]);
4053 NSArray *packages = [database_ packages];
4054 for (Package *package in packages) {
4055 pkgCache::PkgIterator iterator = [package iterator];
4056 pkgDepCache::StateCache &state(cache[iterator]);
4057
4058 NSString *name([package name]);
4059
4060 if (state.NewInstall())
4061 [installing addObject:name];
4062 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4063 [reinstalling addObject:name];
4064 else if (state.Upgrade())
4065 [upgrading addObject:name];
4066 else if (state.Downgrade())
4067 [downgrading addObject:name];
4068 else if (state.Delete()) {
4069 if ([package essential])
4070 remove = true;
4071 [removing addObject:name];
4072 } else continue;
4073
4074 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4075 substrate_ |= DepSubstrate(iterator.CurrentVer());
4076 }
4077
4078 if (!remove)
4079 essential_ = nil;
4080 else if (Advanced_) {
4081 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4082
4083 essential_ = [[UIAlertView alloc]
4084 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4085 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4086 delegate:self
4087 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4088 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4089 ];
4090
4091 [essential_ setContext:@"remove"];
4092 } else {
4093 essential_ = [[UIAlertView alloc]
4094 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4095 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4096 delegate:self
4097 cancelButtonTitle:UCLocalize("OKAY")
4098 otherButtonTitles:nil
4099 ];
4100
4101 [essential_ setContext:@"unable"];
4102 }
4103
4104 changes_ = [[NSArray alloc] initWithObjects:
4105 installing,
4106 reinstalling,
4107 upgrading,
4108 downgrading,
4109 removing,
4110 nil];
4111
4112 issues_ = [database_ issues];
4113 if (issues_ != nil)
4114 issues_ = [issues_ retain];
4115
4116 sizes_ = [[NSArray alloc] initWithObjects:
4117 SizeString([database_ fetcher].FetchNeeded()),
4118 SizeString([database_ fetcher].PartialPresent()),
4119 nil];
4120
4121 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4122
4123 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4124 initWithTitle:UCLocalize("CANCEL")
4125 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4126 style:UIBarButtonItemStylePlain
4127 target:self
4128 action:@selector(cancelButtonClicked)
4129 ] autorelease]];
4130 } return self;
4131 }
4132
4133 - (void) applyRightButton {
4134 #if !AlwaysReload && !IgnoreInstall
4135 if (issues_ == nil && ![self isLoading])
4136 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4137 initWithTitle:UCLocalize("CONFIRM")
4138 style:UIBarButtonItemStylePlain
4139 target:self
4140 action:@selector(confirmButtonClicked)
4141 ] autorelease]];
4142 else
4143 [super applyRightButton];
4144 #else
4145 [[self navigationItem] setRightBarButtonItem:nil];
4146 #endif
4147 }
4148
4149 - (void) cancelButtonClicked {
4150 [self dismissModalViewControllerAnimated:YES];
4151 [delegate_ cancelAndClear:YES];
4152 }
4153
4154 #if !AlwaysReload
4155 - (void) confirmButtonClicked {
4156 #if IgnoreInstall
4157 return;
4158 #endif
4159 if (essential_ != nil)
4160 [essential_ show];
4161 else {
4162 if (substrate_)
4163 Finish_ = 2;
4164 [delegate_ confirmWithNavigationController:[self navigationController]];
4165 }
4166 }
4167 #endif
4168
4169 @end
4170 /* }}} */
4171
4172 /* Progress Data {{{ */
4173 @interface ProgressData : NSObject {
4174 SEL selector_;
4175 // XXX: should these really both be _transient?
4176 _transient id target_;
4177 _transient id object_;
4178 }
4179
4180 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4181
4182 - (SEL) selector;
4183 - (id) target;
4184 - (id) object;
4185 @end
4186
4187 @implementation ProgressData
4188
4189 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4190 if ((self = [super init]) != nil) {
4191 selector_ = selector;
4192 target_ = target;
4193 object_ = object;
4194 } return self;
4195 }
4196
4197 - (SEL) selector {
4198 return selector_;
4199 }
4200
4201 - (id) target {
4202 return target_;
4203 }
4204
4205 - (id) object {
4206 return object_;
4207 }
4208
4209 @end
4210 /* }}} */
4211 /* Progress Controller {{{ */
4212 @interface ProgressController : CYViewController <
4213 ConfigurationDelegate,
4214 ProgressDelegate
4215 > {
4216 _transient Database *database_;
4217 UIProgressBar *progress_;
4218 UITextView *output_;
4219 UITextLabel *status_;
4220 UIPushButton *close_;
4221 BOOL running_;
4222 SHA1SumValue springlist_;
4223 SHA1SumValue notifyconf_;
4224 NSString *title_;
4225 }
4226
4227 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4228
4229 - (void) _retachThread;
4230 - (void) _detachNewThreadData:(ProgressData *)data;
4231 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4232
4233 - (BOOL) isRunning;
4234
4235 @end
4236
4237 @protocol ProgressControllerDelegate
4238 - (void) progressControllerIsComplete:(ProgressController *)sender;
4239 @end
4240
4241 @implementation ProgressController
4242
4243 - (void) dealloc {
4244 [database_ setDelegate:nil];
4245 [progress_ release];
4246 [output_ release];
4247 [status_ release];
4248 [close_ release];
4249 if (title_ != nil)
4250 [title_ release];
4251 [super dealloc];
4252 }
4253
4254 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4255 if ((self = [super init]) != nil) {
4256 database_ = database;
4257 [database_ setDelegate:self];
4258 delegate_ = delegate;
4259
4260 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4261
4262 progress_ = [[UIProgressBar alloc] init];
4263 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4264 [progress_ setStyle:0];
4265
4266 status_ = [[UITextLabel alloc] init];
4267 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4268 [status_ setColor:[UIColor whiteColor]];
4269 [status_ setBackgroundColor:[UIColor clearColor]];
4270 [status_ setCentersHorizontally:YES];
4271 //[status_ setFont:font];
4272
4273 output_ = [[UITextView alloc] init];
4274
4275 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4276 //[output_ setTextFont:@"Courier New"];
4277 [output_ setFont:[[output_ font] fontWithSize:12]];
4278 [output_ setTextColor:[UIColor whiteColor]];
4279 [output_ setBackgroundColor:[UIColor clearColor]];
4280 [output_ setMarginTop:0];
4281 [output_ setAllowsRubberBanding:YES];
4282 [output_ setEditable:NO];
4283 [[self view] addSubview:output_];
4284
4285 close_ = [[UIPushButton alloc] init];
4286 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4287 [close_ setAutosizesToFit:NO];
4288 [close_ setDrawsShadow:YES];
4289 [close_ setStretchBackground:YES];
4290 [close_ setEnabled:YES];
4291 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4292 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4293 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4294 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4295 } return self;
4296 }
4297
4298 - (void) positionViews {
4299 CGRect bounds = [[self view] bounds];
4300 CGSize prgsize = [UIProgressBar defaultSize];
4301
4302 CGRect prgrect = {{
4303 (bounds.size.width - prgsize.width) / 2,
4304 bounds.size.height - prgsize.height - 20
4305 }, prgsize};
4306
4307 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4308
4309 [progress_ setFrame:prgrect];
4310 [status_ setFrame:CGRectMake(
4311 10,
4312 bounds.size.height - prgsize.height - 50,
4313 bounds.size.width - 20,
4314 24
4315 )];
4316 [output_ setFrame:CGRectMake(
4317 10,
4318 20,
4319 bounds.size.width - 20,
4320 bounds.size.height - 62
4321 )];
4322 [close_ setFrame:CGRectMake(
4323 (bounds.size.width - closewidth) / 2,
4324 bounds.size.height - prgsize.height - 50,
4325 closewidth,
4326 32 + prgsize.height
4327 )];
4328 }
4329
4330 - (void) viewWillAppear:(BOOL)animated {
4331 [super viewDidAppear:animated];
4332 [[self navigationItem] setHidesBackButton:YES];
4333 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4334
4335 [self positionViews];
4336 }
4337
4338 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4339 [self positionViews];
4340 }
4341
4342 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4343 NSString *context([alert context]);
4344
4345 if ([context isEqualToString:@"conffile"]) {
4346 FILE *input = [database_ input];
4347 if (button == [alert cancelButtonIndex])
4348 fprintf(input, "N\n");
4349 else if (button == [alert firstOtherButtonIndex])
4350 fprintf(input, "Y\n");
4351 fflush(input);
4352 }
4353 }
4354
4355 - (void) closeButtonPushed {
4356 running_ = NO;
4357
4358 UpdateExternalStatus(0);
4359
4360 switch (Finish_) {
4361 case 0:
4362 [self dismissModalViewControllerAnimated:YES];
4363 break;
4364
4365 case 1:
4366 [delegate_ terminateWithSuccess];
4367 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4368 [delegate_ suspendWithAnimation:YES];
4369 else
4370 [delegate_ suspend];*/
4371 break;
4372
4373 case 2:
4374 system("launchctl stop com.apple.SpringBoard");
4375 break;
4376
4377 case 3:
4378 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4379 break;
4380
4381 case 4:
4382 system("reboot");
4383 break;
4384 }
4385 }
4386
4387 - (void) _retachThread {
4388 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4389
4390 [[self view] addSubview:close_];
4391 [progress_ removeFromSuperview];
4392 [status_ removeFromSuperview];
4393
4394 [database_ popErrorWithTitle:title_];
4395 [delegate_ progressControllerIsComplete:self];
4396
4397 if (Finish_ < 4) {
4398 FileFd file;
4399 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4400 _error->Discard();
4401 else {
4402 MMap mmap(file, MMap::ReadOnly);
4403 SHA1Summation sha1;
4404 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4405 if (!(notifyconf_ == sha1.Result()))
4406 Finish_ = 4;
4407 }
4408 }
4409
4410 if (Finish_ < 3) {
4411 FileFd file;
4412 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4413 _error->Discard();
4414 else {
4415 MMap mmap(file, MMap::ReadOnly);
4416 SHA1Summation sha1;
4417 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4418 if (!(springlist_ == sha1.Result()))
4419 Finish_ = 3;
4420 }
4421 }
4422
4423 switch (Finish_) {
4424 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4425 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4426 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4427 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4428 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4429 }
4430
4431 system("su -c /usr/bin/uicache mobile");
4432
4433 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4434
4435 [delegate_ setStatusBarShowsProgress:NO];
4436 }
4437
4438 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4439 [[data target] performSelector:[data selector] withObject:[data object]];
4440 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4441 }
4442
4443 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4444 UpdateExternalStatus(1);
4445
4446 if (title_ != nil)
4447 [title_ release];
4448 if (title == nil)
4449 title_ = nil;
4450 else
4451 title_ = [title retain];
4452
4453 [[self navigationItem] setTitle:title_];
4454
4455 [status_ setText:nil];
4456 [output_ setText:@""];
4457 [progress_ setProgress:0];
4458
4459 [close_ removeFromSuperview];
4460 [[self view] addSubview:progress_];
4461 [[self view] addSubview:status_];
4462
4463 [delegate_ setStatusBarShowsProgress:YES];
4464 running_ = YES;
4465
4466 {
4467 FileFd file;
4468 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4469 _error->Discard();
4470 else {
4471 MMap mmap(file, MMap::ReadOnly);
4472 SHA1Summation sha1;
4473 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4474 notifyconf_ = sha1.Result();
4475 }
4476 }
4477
4478 {
4479 FileFd file;
4480 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4481 _error->Discard();
4482 else {
4483 MMap mmap(file, MMap::ReadOnly);
4484 SHA1Summation sha1;
4485 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4486 springlist_ = sha1.Result();
4487 }
4488 }
4489
4490 [NSThread
4491 detachNewThreadSelector:@selector(_detachNewThreadData:)
4492 toTarget:self
4493 withObject:[[[ProgressData alloc]
4494 initWithSelector:selector
4495 target:target
4496 object:object
4497 ] autorelease]
4498 ];
4499 }
4500
4501 - (void) repairWithSelector:(SEL)selector {
4502 [self
4503 detachNewThreadSelector:selector
4504 toTarget:database_
4505 withObject:nil
4506 title:UCLocalize("REPAIRING")
4507 ];
4508 }
4509
4510 - (void) setConfigurationData:(NSString *)data {
4511 [self
4512 performSelectorOnMainThread:@selector(_setConfigurationData:)
4513 withObject:data
4514 waitUntilDone:YES
4515 ];
4516 }
4517
4518 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4519 CYActionSheet *sheet([[[CYActionSheet alloc]
4520 initWithTitle:title
4521 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4522 defaultButtonIndex:0
4523 ] autorelease]);
4524
4525 [sheet setMessage:error];
4526 [sheet yieldToPopupAlertAnimated:YES];
4527 [sheet dismiss];
4528 }
4529
4530 - (void) setProgressTitle:(NSString *)title {
4531 [self
4532 performSelectorOnMainThread:@selector(_setProgressTitle:)
4533 withObject:title
4534 waitUntilDone:YES
4535 ];
4536 }
4537
4538 - (void) setProgressPercent:(float)percent {
4539 [self
4540 performSelectorOnMainThread:@selector(_setProgressPercent:)
4541 withObject:[NSNumber numberWithFloat:percent]
4542 waitUntilDone:YES
4543 ];
4544 }
4545
4546 - (void) startProgress {
4547 }
4548
4549 - (void) addProgressOutput:(NSString *)output {
4550 [self
4551 performSelectorOnMainThread:@selector(_addProgressOutput:)
4552 withObject:output
4553 waitUntilDone:YES
4554 ];
4555 }
4556
4557 - (bool) isCancelling:(size_t)received {
4558 return false;
4559 }
4560
4561 - (void) _setConfigurationData:(NSString *)data {
4562 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4563
4564 if (!conffile_r(data)) {
4565 lprintf("E:invalid conffile\n");
4566 return;
4567 }
4568
4569 NSString *ofile = conffile_r[1];
4570 //NSString *nfile = conffile_r[2];
4571
4572 UIAlertView *alert = [[[UIAlertView alloc]
4573 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4574 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4575 delegate:self
4576 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4577 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4578 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4579 nil
4580 ] autorelease];
4581
4582 [alert setContext:@"conffile"];
4583 [alert show];
4584 }
4585
4586 - (void) _setProgressTitle:(NSString *)title {
4587 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4588 for (size_t i(0), e([words count]); i != e; ++i) {
4589 NSString *word([words objectAtIndex:i]);
4590 if (Package *package = [database_ packageWithName:word])
4591 [words replaceObjectAtIndex:i withObject:[package name]];
4592 }
4593
4594 [status_ setText:[words componentsJoinedByString:@" "]];
4595 }
4596
4597 - (void) _setProgressPercent:(NSNumber *)percent {
4598 [progress_ setProgress:[percent floatValue]];
4599 }
4600
4601 - (void) _addProgressOutput:(NSString *)output {
4602 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4603 CGSize size = [output_ contentSize];
4604 CGRect rect = {{0, size.height}, {size.width, 0}};
4605 [output_ scrollRectToVisible:rect animated:YES];
4606 }
4607
4608 - (BOOL) isRunning {
4609 return running_;
4610 }
4611
4612 @end
4613 /* }}} */
4614
4615 /* Cell Content View {{{ */
4616 @protocol ContentDelegate
4617 - (void) drawContentRect:(CGRect)rect;
4618 @end
4619
4620 @interface ContentView : UIView {
4621 _transient id<ContentDelegate> delegate_;
4622 }
4623
4624 @end
4625
4626 @implementation ContentView
4627 - (id) initWithFrame:(CGRect)frame {
4628 if ((self = [super initWithFrame:frame]) != nil) {
4629 /* Fix landscape stretching. */
4630 [self setNeedsDisplayOnBoundsChange:YES];
4631 } return self;
4632 }
4633
4634 - (void) setDelegate:(id<ContentDelegate>)delegate {
4635 delegate_ = delegate;
4636 }
4637
4638 - (void) drawRect:(CGRect)rect {
4639 [super drawRect:rect];
4640 [delegate_ drawContentRect:rect];
4641 }
4642 @end
4643 /* }}} */
4644 /* Package Cell {{{ */
4645 @interface PackageCell : UITableViewCell <
4646 ContentDelegate
4647 > {
4648 UIImage *icon_;
4649 NSString *name_;
4650 NSString *description_;
4651 bool commercial_;
4652 NSString *source_;
4653 UIImage *badge_;
4654 Package *package_;
4655 UIColor *color_;
4656 ContentView *content_;
4657 BOOL faded_;
4658 float fade_;
4659 UIImage *placard_;
4660 }
4661
4662 - (PackageCell *) init;
4663 - (void) setPackage:(Package *)package;
4664
4665 + (int) heightForPackage:(Package *)package;
4666 - (void) drawContentRect:(CGRect)rect;
4667
4668 @end
4669
4670 @implementation PackageCell
4671
4672 - (void) clearPackage {
4673 if (icon_ != nil) {
4674 [icon_ release];
4675 icon_ = nil;
4676 }
4677
4678 if (name_ != nil) {
4679 [name_ release];
4680 name_ = nil;
4681 }
4682
4683 if (description_ != nil) {
4684 [description_ release];
4685 description_ = nil;
4686 }
4687
4688 if (source_ != nil) {
4689 [source_ release];
4690 source_ = nil;
4691 }
4692
4693 if (badge_ != nil) {
4694 [badge_ release];
4695 badge_ = nil;
4696 }
4697
4698 if (placard_ != nil) {
4699 [placard_ release];
4700 placard_ = nil;
4701 }
4702
4703 [package_ release];
4704 package_ = nil;
4705 }
4706
4707 - (void) dealloc {
4708 [self clearPackage];
4709 [content_ release];
4710 [color_ release];
4711 [super dealloc];
4712 }
4713
4714 - (float) fade {
4715 return faded_ ? [self selectionPercent] : fade_;
4716 }
4717
4718 - (PackageCell *) init {
4719 CGRect frame(CGRectMake(0, 0, 320, 74));
4720 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4721 UIView *content([self contentView]);
4722 CGRect bounds([content bounds]);
4723
4724 content_ = [[ContentView alloc] initWithFrame:bounds];
4725 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4726 [content addSubview:content_];
4727
4728 [content_ setDelegate:self];
4729 [content_ setOpaque:YES];
4730 if ([self respondsToSelector:@selector(selectionPercent)])
4731 faded_ = YES;
4732 } return self;
4733 }
4734
4735 - (void) _setBackgroundColor {
4736 UIColor *color;
4737 if (NSString *mode = [package_ mode]) {
4738 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4739 color = remove ? RemovingColor_ : InstallingColor_;
4740 } else
4741 color = [UIColor whiteColor];
4742
4743 [content_ setBackgroundColor:color];
4744 [self setNeedsDisplay];
4745 }
4746
4747 - (void) setPackage:(Package *)package {
4748 [self clearPackage];
4749 [package parse];
4750
4751 Source *source = [package source];
4752
4753 icon_ = [[package icon] retain];
4754 name_ = [[package name] retain];
4755
4756 if (IsWildcat_)
4757 description_ = [package longDescription];
4758 if (description_ == nil)
4759 description_ = [package shortDescription];
4760 if (description_ != nil)
4761 description_ = [description_ retain];
4762
4763 commercial_ = [package isCommercial];
4764
4765 package_ = [package retain];
4766
4767 NSString *label = nil;
4768 bool trusted = false;
4769
4770 if (source != nil) {
4771 label = [source label];
4772 trusted = [source trusted];
4773 } else if ([[package id] isEqualToString:@"firmware"])
4774 label = UCLocalize("APPLE");
4775 else
4776 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4777
4778 NSString *from(label);
4779
4780 NSString *section = [package simpleSection];
4781 if (section != nil && ![section isEqualToString:label]) {
4782 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4783 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4784 }
4785
4786 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4787 source_ = [from retain];
4788
4789 if (NSString *purpose = [package primaryPurpose])
4790 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4791 badge_ = [badge_ retain];
4792
4793 if ([package installed] != nil)
4794 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4795 placard_ = [placard_ retain];
4796
4797 [self _setBackgroundColor];
4798 [content_ setNeedsDisplay];
4799 }
4800
4801 - (void) drawContentRect:(CGRect)rect {
4802 bool selected([self isSelected]);
4803 float width([self bounds].size.width);
4804
4805 #if 0
4806 CGContextRef context(UIGraphicsGetCurrentContext());
4807 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4808 CGContextFillRect(context, rect);
4809 #endif
4810
4811 if (icon_ != nil) {
4812 CGRect rect;
4813 rect.size = [icon_ size];
4814
4815 rect.size.width /= 2;
4816 rect.size.height /= 2;
4817
4818 rect.origin.x = 25 - rect.size.width / 2;
4819 rect.origin.y = 25 - rect.size.height / 2;
4820
4821 [icon_ drawInRect:rect];
4822 }
4823
4824 if (badge_ != nil) {
4825 CGSize size = [badge_ size];
4826
4827 [badge_ drawAtPoint:CGPointMake(
4828 36 - size.width / 2,
4829 36 - size.height / 2
4830 )];
4831 }
4832
4833 if (selected)
4834 UISetColor(White_);
4835
4836 if (!selected)
4837 UISetColor(commercial_ ? Purple_ : Black_);
4838 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4839 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4840
4841 if (!selected)
4842 UISetColor(commercial_ ? Purplish_ : Gray_);
4843 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4844
4845 if (placard_ != nil)
4846 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4847 }
4848
4849 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4850 //[self _setBackgroundColor];
4851 [super setSelected:selected animated:fade];
4852 [content_ setNeedsDisplay];
4853 }
4854
4855 + (int) heightForPackage:(Package *)package {
4856 return 73;
4857 }
4858
4859 @end
4860 /* }}} */
4861 /* Section Cell {{{ */
4862 @interface SectionCell : UITableViewCell <
4863 ContentDelegate
4864 > {
4865 NSString *basic_;
4866 NSString *section_;
4867 NSString *name_;
4868 NSString *count_;
4869 UIImage *icon_;
4870 ContentView *content_;
4871 UISwitch *switch_;
4872 BOOL editing_;
4873 }
4874
4875 - (void) setSection:(Section *)section editing:(BOOL)editing;
4876
4877 @end
4878
4879 @implementation SectionCell
4880
4881 - (void) clearSection {
4882 if (basic_ != nil) {
4883 [basic_ release];
4884 basic_ = nil;
4885 }
4886
4887 if (section_ != nil) {
4888 [section_ release];
4889 section_ = nil;
4890 }
4891
4892 if (name_ != nil) {
4893 [name_ release];
4894 name_ = nil;
4895 }
4896
4897 if (count_ != nil) {
4898 [count_ release];
4899 count_ = nil;
4900 }
4901 }
4902
4903 - (void) dealloc {
4904 [self clearSection];
4905 [icon_ release];
4906 [switch_ release];
4907 [content_ release];
4908
4909 [super dealloc];
4910 }
4911
4912 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4913 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4914 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4915 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4916 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4917
4918 UIView *content([self contentView]);
4919 CGRect bounds([content bounds]);
4920
4921 content_ = [[ContentView alloc] initWithFrame:bounds];
4922 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4923 [content addSubview:content_];
4924 [content_ setBackgroundColor:[UIColor whiteColor]];
4925
4926 [content_ setDelegate:self];
4927 } return self;
4928 }
4929
4930 - (void) onSwitch:(id)sender {
4931 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4932 if (metadata == nil) {
4933 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4934 [Sections_ setObject:metadata forKey:basic_];
4935 }
4936
4937 Changed_ = true;
4938 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4939 }
4940
4941 - (void) setSection:(Section *)section editing:(BOOL)editing {
4942 if (editing != editing_) {
4943 if (editing_)
4944 [switch_ removeFromSuperview];
4945 else
4946 [self addSubview:switch_];
4947 editing_ = editing;
4948 }
4949
4950 [self clearSection];
4951
4952 if (section == nil) {
4953 name_ = [UCLocalize("ALL_PACKAGES") retain];
4954 count_ = nil;
4955 } else {
4956 basic_ = [section name];
4957 if (basic_ != nil)
4958 basic_ = [basic_ retain];
4959
4960 section_ = [section localized];
4961 if (section_ != nil)
4962 section_ = [section_ retain];
4963
4964 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4965 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4966
4967 if (editing_)
4968 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4969 }
4970
4971 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4972 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
4973
4974 [content_ setNeedsDisplay];
4975 }
4976
4977 - (void) setFrame:(CGRect)frame {
4978 [super setFrame:frame];
4979
4980 CGRect rect([switch_ frame]);
4981 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4982 }
4983
4984 - (void) drawContentRect:(CGRect)rect {
4985 BOOL selected = [self isSelected];
4986
4987 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4988
4989 if (selected)
4990 UISetColor(White_);
4991
4992 if (!selected)
4993 UISetColor(Black_);
4994
4995 float width(rect.size.width);
4996 if (editing_)
4997 width -= 87;
4998
4999 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5000
5001 CGSize size = [count_ sizeWithFont:Font14_];
5002
5003 UISetColor(White_);
5004 if (count_ != nil)
5005 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5006 }
5007
5008 @end
5009 /* }}} */
5010
5011 /* File Table {{{ */
5012 @interface FileTable : CYViewController <
5013 UITableViewDataSource,
5014 UITableViewDelegate
5015 > {
5016 _transient Database *database_;
5017 Package *package_;
5018 NSString *name_;
5019 NSMutableArray *files_;
5020 UITableView *list_;
5021 }
5022
5023 - (id) initWithDatabase:(Database *)database;
5024 - (void) setPackage:(Package *)package;
5025
5026 @end
5027
5028 @implementation FileTable
5029
5030 - (void) dealloc {
5031 if (package_ != nil)
5032 [package_ release];
5033 if (name_ != nil)
5034 [name_ release];
5035 [files_ release];
5036 [list_ release];
5037 [super dealloc];
5038 }
5039
5040 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5041 return files_ == nil ? 0 : [files_ count];
5042 }
5043
5044 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5045 return 24.0f;
5046 }*/
5047
5048 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5049 static NSString *reuseIdentifier = @"Cell";
5050
5051 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5052 if (cell == nil) {
5053 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5054 [cell setFont:[UIFont systemFontOfSize:16]];
5055 }
5056 [cell setText:[files_ objectAtIndex:indexPath.row]];
5057 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5058
5059 return cell;
5060 }
5061
5062 - (id) initWithDatabase:(Database *)database {
5063 if ((self = [super init]) != nil) {
5064 database_ = database;
5065
5066 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5067
5068 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5069
5070 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5071 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5072 [list_ setRowHeight:24.0f];
5073 [[self view] addSubview:list_];
5074
5075 [list_ setDataSource:self];
5076 [list_ setDelegate:self];
5077 } return self;
5078 }
5079
5080 - (void) setPackage:(Package *)package {
5081 if (package_ != nil) {
5082 [package_ autorelease];
5083 package_ = nil;
5084 }
5085
5086 if (name_ != nil) {
5087 [name_ release];
5088 name_ = nil;
5089 }
5090
5091 [files_ removeAllObjects];
5092
5093 if (package != nil) {
5094 package_ = [package retain];
5095 name_ = [[package id] retain];
5096
5097 if (NSArray *files = [package files])
5098 [files_ addObjectsFromArray:files];
5099
5100 if ([files_ count] != 0) {
5101 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5102 [files_ removeObjectAtIndex:0];
5103 [files_ sortUsingSelector:@selector(compareByPath:)];
5104
5105 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5106 [stack addObject:@"/"];
5107
5108 for (int i(0), e([files_ count]); i != e; ++i) {
5109 NSString *file = [files_ objectAtIndex:i];
5110 while (![file hasPrefix:[stack lastObject]])
5111 [stack removeLastObject];
5112 NSString *directory = [stack lastObject];
5113 [stack addObject:[file stringByAppendingString:@"/"]];
5114 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5115 ([stack count] - 2) * 3, "",
5116 [file substringFromIndex:[directory length]]
5117 ]];
5118 }
5119 }
5120 }
5121
5122 [list_ reloadData];
5123 }
5124
5125 - (void) reloadData {
5126 [self setPackage:[database_ packageWithName:name_]];
5127 }
5128
5129 @end
5130 /* }}} */
5131 /* Package Controller {{{ */
5132 @interface PackageController : CYBrowserController <
5133 UIActionSheetDelegate
5134 > {
5135 _transient Database *database_;
5136 Package *package_;
5137 NSString *name_;
5138 bool commercial_;
5139 NSMutableArray *buttons_;
5140 UIBarButtonItem *button_;
5141 }
5142
5143 - (id) initWithDatabase:(Database *)database;
5144 - (void) setPackage:(Package *)package;
5145
5146 @end
5147
5148 @implementation PackageController
5149
5150 - (void) dealloc {
5151 if (package_ != nil)
5152 [package_ release];
5153 if (name_ != nil)
5154 [name_ release];
5155
5156 [buttons_ release];
5157
5158 if (button_ != nil)
5159 [button_ release];
5160
5161 [super dealloc];
5162 }
5163
5164 - (void) release {
5165 if ([self retainCount] == 1)
5166 [delegate_ setPackageController:self];
5167 [super release];
5168 }
5169
5170 /* XXX: this is not safe at all... localization of /fail/ */
5171 - (void) _clickButtonWithName:(NSString *)name {
5172 if ([name isEqualToString:UCLocalize("CLEAR")])
5173 [delegate_ clearPackage:package_];
5174 else if ([name isEqualToString:UCLocalize("INSTALL")])
5175 [delegate_ installPackage:package_];
5176 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5177 [delegate_ installPackage:package_];
5178 else if ([name isEqualToString:UCLocalize("REMOVE")])
5179 [delegate_ removePackage:package_];
5180 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5181 [delegate_ installPackage:package_];
5182 else _assert(false);
5183 }
5184
5185 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5186 NSString *context([sheet context]);
5187
5188 if ([context isEqualToString:@"modify"]) {
5189 if (button != [sheet cancelButtonIndex]) {
5190 NSString *buttonName = [buttons_ objectAtIndex:button];
5191 [self _clickButtonWithName:buttonName];
5192 }
5193
5194 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5195 }
5196 }
5197
5198 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5199 [super webView:view didClearWindowObject:window forFrame:frame];
5200 [window setValue:package_ forKey:@"package"];
5201 }
5202
5203 - (bool) _allowJavaScriptPanel {
5204 return commercial_;
5205 }
5206
5207 #if !AlwaysReload
5208 - (void) _customButtonClicked {
5209 int count([buttons_ count]);
5210 if (count == 0)
5211 return;
5212
5213 if (count == 1)
5214 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5215 else {
5216 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5217 [buttons addObjectsFromArray:buttons_];
5218
5219 UIActionSheet *sheet = [[[UIActionSheet alloc]
5220 initWithTitle:nil
5221 delegate:self
5222 cancelButtonTitle:nil
5223 destructiveButtonTitle:nil
5224 otherButtonTitles:nil
5225 ] autorelease];
5226
5227 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5228 if (!IsWildcat_) {
5229 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5230 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5231 }
5232 [sheet setContext:@"modify"];
5233
5234 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5235 }
5236 }
5237
5238 // We don't want to allow non-commercial packages to do custom things to the install button,
5239 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5240 - (void) customButtonClicked {
5241 if (commercial_)
5242 [super customButtonClicked];
5243 else
5244 [self _customButtonClicked];
5245 }
5246
5247 - (void) reloadButtonClicked {
5248 // Don't reload a package view by clicking the button.
5249 }
5250
5251 - (void) applyLoadingTitle {
5252 // Don't show "Loading" as the title. Ever.
5253 }
5254
5255 - (UIBarButtonItem *) rightButton {
5256 return button_;
5257 }
5258 #endif
5259
5260 - (id) initWithDatabase:(Database *)database {
5261 if ((self = [super init]) != nil) {
5262 database_ = database;
5263 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5264 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5265 } return self;
5266 }
5267
5268 - (void) setPackage:(Package *)package {
5269 if (package_ != nil) {
5270 [package_ autorelease];
5271 package_ = nil;
5272 }
5273
5274 if (name_ != nil) {
5275 [name_ release];
5276 name_ = nil;
5277 }
5278
5279 [buttons_ removeAllObjects];
5280
5281 if (package != nil) {
5282 [package parse];
5283
5284 package_ = [package retain];
5285 name_ = [[package id] retain];
5286 commercial_ = [package isCommercial];
5287
5288 if ([package_ mode] != nil)
5289 [buttons_ addObject:UCLocalize("CLEAR")];
5290 if ([package_ source] == nil);
5291 else if ([package_ upgradableAndEssential:NO])
5292 [buttons_ addObject:UCLocalize("UPGRADE")];
5293 else if ([package_ uninstalled])
5294 [buttons_ addObject:UCLocalize("INSTALL")];
5295 else
5296 [buttons_ addObject:UCLocalize("REINSTALL")];
5297 if (![package_ uninstalled])
5298 [buttons_ addObject:UCLocalize("REMOVE")];
5299 }
5300
5301 if (button_ != nil)
5302 [button_ release];
5303
5304 NSString *title;
5305 switch ([buttons_ count]) {
5306 case 0: title = nil; break;
5307 case 1: title = [buttons_ objectAtIndex:0]; break;
5308 default: title = UCLocalize("MODIFY"); break;
5309 }
5310
5311 button_ = [[UIBarButtonItem alloc]
5312 initWithTitle:title
5313 style:UIBarButtonItemStylePlain
5314 target:self
5315 action:@selector(customButtonClicked)
5316 ];
5317 }
5318
5319 - (bool) isLoading {
5320 return commercial_ ? [super isLoading] : false;
5321 }
5322
5323 - (void) reloadData {
5324 [self setPackage:[database_ packageWithName:name_]];
5325 }
5326
5327 @end
5328 /* }}} */
5329 /* Package Table {{{ */
5330 @interface PackageTable : UIView <
5331 UITableViewDataSource,
5332 UITableViewDelegate
5333 > {
5334 _transient Database *database_;
5335 NSMutableArray *packages_;
5336 NSMutableArray *sections_;
5337 UITableView *list_;
5338 NSMutableArray *index_;
5339 NSMutableDictionary *indices_;
5340 // XXX: this target_ seems to be delegate_. :(
5341 _transient id target_;
5342 SEL action_;
5343 // XXX: why do we even have this delegate_?
5344 _transient id delegate_;
5345 }
5346
5347 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5348
5349 - (void) setDelegate:(id)delegate;
5350
5351 - (void) reloadData;
5352 - (void) resetCursor;
5353
5354 - (UITableView *) list;
5355
5356 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5357
5358 - (void) deselectWithAnimation:(BOOL)animated;
5359
5360 @end
5361
5362 @implementation PackageTable
5363
5364 - (void) dealloc {
5365 [packages_ release];
5366 [sections_ release];
5367 [list_ release];
5368 [index_ release];
5369 [indices_ release];
5370
5371 [super dealloc];
5372 }
5373
5374 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5375 NSInteger count([sections_ count]);
5376 return count == 0 ? 1 : count;
5377 }
5378
5379 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5380 if ([sections_ count] == 0)
5381 return nil;
5382 return [[sections_ objectAtIndex:section] name];
5383 }
5384
5385 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5386 if ([sections_ count] == 0)
5387 return 0;
5388 return [[sections_ objectAtIndex:section] count];
5389 }
5390
5391 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5392 Section *section([sections_ objectAtIndex:[path section]]);
5393 NSInteger row([path row]);
5394 Package *package([packages_ objectAtIndex:([section row] + row)]);
5395 return package;
5396 }
5397
5398 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5399 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5400 if (cell == nil)
5401 cell = [[[PackageCell alloc] init] autorelease];
5402 [cell setPackage:[self packageAtIndexPath:path]];
5403 return cell;
5404 }
5405
5406 - (void) deselectWithAnimation:(BOOL)animated {
5407 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5408 }
5409
5410 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5411 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5412 }*/
5413
5414 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5415 Package *package([self packageAtIndexPath:path]);
5416 package = [database_ packageWithName:[package id]];
5417 [target_ performSelector:action_ withObject:package];
5418 return path;
5419 }
5420
5421 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5422 return [packages_ count] > 20 ? index_ : nil;
5423 }
5424
5425 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5426 return index;
5427 }
5428
5429 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5430 if ((self = [super initWithFrame:frame]) != nil) {
5431 database_ = database;
5432
5433 target_ = target;
5434 action_ = action;
5435
5436 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5437 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5438
5439 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5440 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5441
5442 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5443 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5444 [list_ setRowHeight:73.0f];
5445 [self addSubview:list_];
5446
5447 [list_ setDataSource:self];
5448 [list_ setDelegate:self];
5449 } return self;
5450 }
5451
5452 - (void) setDelegate:(id)delegate {
5453 delegate_ = delegate;
5454 }
5455
5456 - (bool) hasPackage:(Package *)package {
5457 return true;
5458 }
5459
5460 - (void) reloadData {
5461 NSArray *packages = [database_ packages];
5462
5463 [packages_ removeAllObjects];
5464 [sections_ removeAllObjects];
5465
5466 _profile(PackageTable$reloadData$Filter)
5467 for (Package *package in packages)
5468 if ([self hasPackage:package])
5469 [packages_ addObject:package];
5470 _end
5471
5472 [index_ removeAllObjects];
5473 [indices_ removeAllObjects];
5474
5475 Section *section = nil;
5476
5477 _profile(PackageTable$reloadData$Section)
5478 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5479 Package *package;
5480 unichar index;
5481
5482 _profile(PackageTable$reloadData$Section$Package)
5483 package = [packages_ objectAtIndex:offset];
5484 index = [package index];
5485 _end
5486
5487 if (section == nil || [section index] != index) {
5488 _profile(PackageTable$reloadData$Section$Allocate)
5489 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5490 _end
5491
5492 [index_ addObject:[section name]];
5493 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5494
5495 _profile(PackageTable$reloadData$Section$Add)
5496 [sections_ addObject:section];
5497 _end
5498 }
5499
5500 [section addToCount];
5501 }
5502 _end
5503
5504 _profile(PackageTable$reloadData$List)
5505 [list_ reloadData];
5506 _end
5507 }
5508
5509 - (void) resetCursor {
5510 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5511 }
5512
5513 - (UITableView *) list {
5514 return list_;
5515 }
5516
5517 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5518 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5519 }
5520
5521 @end
5522 /* }}} */
5523 /* Filtered Package Table {{{ */
5524 @interface FilteredPackageTable : PackageTable {
5525 SEL filter_;
5526 IMP imp_;
5527 id object_;
5528 }
5529
5530 - (void) setObject:(id)object;
5531 - (void) setObject:(id)object forFilter:(SEL)filter;
5532
5533 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5534
5535 @end
5536
5537 @implementation FilteredPackageTable
5538
5539 - (void) dealloc {
5540 if (object_ != nil)
5541 [object_ release];
5542 [super dealloc];
5543 }
5544
5545 - (void) setFilter:(SEL)filter {
5546 filter_ = filter;
5547
5548 /* XXX: this is an unsafe optimization of doomy hell */
5549 Method method(class_getInstanceMethod([Package class], filter));
5550 _assert(method != NULL);
5551 imp_ = method_getImplementation(method);
5552 _assert(imp_ != NULL);
5553 }
5554
5555 - (void) setObject:(id)object {
5556 if (object_ != nil)
5557 [object_ release];
5558 if (object == nil)
5559 object_ = nil;
5560 else
5561 object_ = [object retain];
5562 }
5563
5564 - (void) setObject:(id)object forFilter:(SEL)filter {
5565 [self setFilter:filter];
5566 [self setObject:object];
5567 }
5568
5569 - (bool) hasPackage:(Package *)package {
5570 _profile(FilteredPackageTable$hasPackage)
5571 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5572 _end
5573 }
5574
5575 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5576 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5577 [self setFilter:filter];
5578 object_ = [object retain];
5579 [self reloadData];
5580 } return self;
5581 }
5582
5583 @end
5584 /* }}} */
5585
5586 /* Filtered Package Controller {{{ */
5587 @interface FilteredPackageController : CYViewController {
5588 _transient Database *database_;
5589 FilteredPackageTable *packages_;
5590 NSString *title_;
5591 }
5592
5593 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5594
5595 @end
5596
5597 @implementation FilteredPackageController
5598
5599 - (void) dealloc {
5600 [packages_ release];
5601 [title_ release];
5602
5603 [super dealloc];
5604 }
5605
5606 - (void) viewDidAppear:(BOOL)animated {
5607 [super viewDidAppear:animated];
5608 [packages_ deselectWithAnimation:animated];
5609 }
5610
5611 - (void) didSelectPackage:(Package *)package {
5612 PackageController *view([delegate_ packageController]);
5613 [view setPackage:package];
5614 [view setDelegate:delegate_];
5615 [[self navigationController] pushViewController:view animated:YES];
5616 }
5617
5618 - (NSString *) title { return title_; }
5619
5620 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5621 if ((self = [super init]) != nil) {
5622 database_ = database;
5623 title_ = [title copy];
5624 [[self navigationItem] setTitle:title_];
5625
5626 packages_ = [[FilteredPackageTable alloc]
5627 initWithFrame:[[self view] bounds]
5628 database:database
5629 target:self
5630 action:@selector(didSelectPackage:)
5631 filter:filter
5632 with:object
5633 ];
5634
5635 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5636 [[self view] addSubview:packages_];
5637 } return self;
5638 }
5639
5640 - (void) reloadData {
5641 [packages_ reloadData];
5642 }
5643
5644 - (void) setDelegate:(id)delegate {
5645 [super setDelegate:delegate];
5646 [packages_ setDelegate:delegate];
5647 }
5648
5649 @end
5650
5651 /* }}} */
5652
5653 /* Add Source Controller {{{ */
5654 @interface AddSourceController : CYViewController {
5655 _transient Database *database_;
5656 }
5657
5658 - (id) initWithDatabase:(Database *)database;
5659
5660 @end
5661
5662 @implementation AddSourceController
5663
5664 - (id) initWithDatabase:(Database *)database {
5665 if ((self = [super init]) != nil) {
5666 database_ = database;
5667 } return self;
5668 }
5669
5670 @end
5671 /* }}} */
5672 /* Source Cell {{{ */
5673 @interface SourceCell : UITableViewCell <
5674 ContentDelegate
5675 > {
5676 UIImage *icon_;
5677 NSString *origin_;
5678 NSString *description_;
5679 NSString *label_;
5680 ContentView *content_;
5681 }
5682
5683 - (void) setSource:(Source *)source;
5684
5685 @end
5686
5687 @implementation SourceCell
5688
5689 - (void) clearSource {
5690 [icon_ release];
5691 [origin_ release];
5692 [description_ release];
5693 [label_ release];
5694
5695 icon_ = nil;
5696 origin_ = nil;
5697 description_ = nil;
5698 label_ = nil;
5699 }
5700
5701 - (void) setSource:(Source *)source {
5702 [self clearSource];
5703
5704 if (icon_ == nil)
5705 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5706 if (icon_ == nil)
5707 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5708 icon_ = [icon_ retain];
5709
5710 origin_ = [[source name] retain];
5711 label_ = [[source uri] retain];
5712 description_ = [[source description] retain];
5713
5714 [content_ setNeedsDisplay];
5715 }
5716
5717 - (void) dealloc {
5718 [self clearSource];
5719 [content_ release];
5720 [super dealloc];
5721 }
5722
5723 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5724 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5725 UIView *content([self contentView]);
5726 CGRect bounds([content bounds]);
5727
5728 content_ = [[ContentView alloc] initWithFrame:bounds];
5729 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5730 [content_ setBackgroundColor:[UIColor whiteColor]];
5731 [content addSubview:content_];
5732
5733 [content_ setDelegate:self];
5734 [content_ setOpaque:YES];
5735 } return self;
5736 }
5737
5738 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5739 [super setSelected:selected animated:animated];
5740 [content_ setNeedsDisplay];
5741 }
5742
5743 - (void) drawContentRect:(CGRect)rect {
5744 bool selected([self isSelected]);
5745 float width(rect.size.width);
5746
5747 if (icon_ != nil)
5748 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5749
5750 if (selected)
5751 UISetColor(White_);
5752
5753 if (!selected)
5754 UISetColor(Black_);
5755 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5756
5757 if (!selected)
5758 UISetColor(Blue_);
5759 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5760
5761 if (!selected)
5762 UISetColor(Gray_);
5763 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5764 }
5765
5766 @end
5767 /* }}} */
5768 /* Source Table {{{ */
5769 @interface SourceTable : CYViewController <
5770 UITableViewDataSource,
5771 UITableViewDelegate
5772 > {
5773 _transient Database *database_;
5774 UITableView *list_;
5775 NSMutableArray *sources_;
5776 int offset_;
5777
5778 NSString *href_;
5779 UIProgressHUD *hud_;
5780 NSError *error_;
5781
5782 //NSURLConnection *installer_;
5783 NSURLConnection *trivial_;
5784 NSURLConnection *trivial_bz2_;
5785 NSURLConnection *trivial_gz_;
5786 //NSURLConnection *automatic_;
5787
5788 BOOL cydia_;
5789 }
5790
5791 - (id) initWithDatabase:(Database *)database;
5792
5793 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5794
5795 @end
5796
5797 @implementation SourceTable
5798
5799 - (void) _releaseConnection:(NSURLConnection *)connection {
5800 if (connection != nil) {
5801 [connection cancel];
5802 //[connection setDelegate:nil];
5803 [connection release];
5804 }
5805 }
5806
5807 - (void) dealloc {
5808 if (href_ != nil)
5809 [href_ release];
5810 if (hud_ != nil)
5811 [hud_ release];
5812 if (error_ != nil)
5813 [error_ release];
5814
5815 //[self _releaseConnection:installer_];
5816 [self _releaseConnection:trivial_];
5817 [self _releaseConnection:trivial_gz_];
5818 [self _releaseConnection:trivial_bz2_];
5819 //[self _releaseConnection:automatic_];
5820
5821 [sources_ release];
5822 [list_ release];
5823 [super dealloc];
5824 }
5825
5826 - (void) viewDidAppear:(BOOL)animated {
5827 [super viewDidAppear:animated];
5828 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5829 }
5830
5831 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5832 return offset_ == 0 ? 1 : 2;
5833 }
5834
5835 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5836 switch (section + (offset_ == 0 ? 1 : 0)) {
5837 case 0: return UCLocalize("ENTERED_BY_USER");
5838 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5839
5840 _nodefault
5841 }
5842 }
5843
5844 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5845 int count = [sources_ count];
5846 switch (section) {
5847 case 0: return (offset_ == 0 ? count : offset_);
5848 case 1: return count - offset_;
5849
5850 _nodefault
5851 }
5852 }
5853
5854 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5855 unsigned idx = 0;
5856 switch (indexPath.section) {
5857 case 0: idx = indexPath.row; break;
5858 case 1: idx = indexPath.row + offset_; break;
5859
5860 _nodefault
5861 }
5862 return [sources_ objectAtIndex:idx];
5863 }
5864
5865 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5866 Source *source = [self sourceAtIndexPath:indexPath];
5867 return [source description] == nil ? 56 : 73;
5868 }
5869
5870 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5871 static NSString *cellIdentifier = @"SourceCell";
5872
5873 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5874 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5875 [cell setSource:[self sourceAtIndexPath:indexPath]];
5876
5877 return cell;
5878 }
5879
5880 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5881 return UITableViewCellAccessoryDisclosureIndicator;
5882 }
5883
5884 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5885 Source *source = [self sourceAtIndexPath:indexPath];
5886
5887 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5888 initWithDatabase:database_
5889 title:[source label]
5890 filter:@selector(isVisibleInSource:)
5891 with:source
5892 ] autorelease];
5893
5894 [packages setDelegate:delegate_];
5895
5896 [[self navigationController] pushViewController:packages animated:YES];
5897 }
5898
5899 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5900 Source *source = [self sourceAtIndexPath:indexPath];
5901 return [source record] != nil;
5902 }
5903
5904 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5905 Source *source = [self sourceAtIndexPath:indexPath];
5906 [Sources_ removeObjectForKey:[source key]];
5907 [delegate_ syncData];
5908 }
5909
5910 - (void) complete {
5911 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5912 @"deb", @"Type",
5913 href_, @"URI",
5914 @"./", @"Distribution",
5915 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5916
5917 [delegate_ syncData];
5918 }
5919
5920 - (NSString *) getWarning {
5921 NSString *href(href_);
5922 NSRange colon([href rangeOfString:@"://"]);
5923 if (colon.location != NSNotFound)
5924 href = [href substringFromIndex:(colon.location + 3)];
5925 href = [href stringByAddingPercentEscapes];
5926 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5927 href = [href stringByCachingURLWithCurrentCDN];
5928
5929 NSURL *url([NSURL URLWithString:href]);
5930
5931 NSStringEncoding encoding;
5932 NSError *error(nil);
5933
5934 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5935 return [warning length] == 0 ? nil : warning;
5936 return nil;
5937 }
5938
5939 - (void) _endConnection:(NSURLConnection *)connection {
5940 // XXX: the memory management in this method is horribly awkward
5941
5942 NSURLConnection **field = NULL;
5943 if (connection == trivial_)
5944 field = &trivial_;
5945 else if (connection == trivial_bz2_)
5946 field = &trivial_bz2_;
5947 else if (connection == trivial_gz_)
5948 field = &trivial_gz_;
5949 _assert(field != NULL);
5950 [connection release];
5951 *field = nil;
5952
5953 if (
5954 trivial_ == nil &&
5955 trivial_bz2_ == nil &&
5956 trivial_gz_ == nil
5957 ) {
5958 bool defer(false);
5959
5960 if (cydia_) {
5961 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5962 defer = true;
5963
5964 UIAlertView *alert = [[[UIAlertView alloc]
5965 initWithTitle:UCLocalize("SOURCE_WARNING")
5966 message:warning
5967 delegate:self
5968 cancelButtonTitle:UCLocalize("CANCEL")
5969 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5970 ] autorelease];
5971
5972 [alert setContext:@"warning"];
5973 [alert setNumberOfRows:1];
5974 [alert show];
5975 } else
5976 [self complete];
5977 } else if (error_ != nil) {
5978 UIAlertView *alert = [[[UIAlertView alloc]
5979 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5980 message:[error_ localizedDescription]
5981 delegate:self
5982 cancelButtonTitle:UCLocalize("OK")
5983 otherButtonTitles:nil
5984 ] autorelease];
5985
5986 [alert setContext:@"urlerror"];
5987 [alert show];
5988 } else {
5989 UIAlertView *alert = [[[UIAlertView alloc]
5990 initWithTitle:UCLocalize("NOT_REPOSITORY")
5991 message:UCLocalize("NOT_REPOSITORY_EX")
5992 delegate:self
5993 cancelButtonTitle:UCLocalize("OK")
5994 otherButtonTitles:nil
5995 ] autorelease];
5996
5997 [alert setContext:@"trivial"];
5998 [alert show];
5999 }
6000
6001 [delegate_ setStatusBarShowsProgress:NO];
6002 [delegate_ removeProgressHUD:hud_];
6003
6004 [hud_ autorelease];
6005 hud_ = nil;
6006
6007 if (!defer) {
6008 [href_ release];
6009 href_ = nil;
6010 }
6011
6012 if (error_ != nil) {
6013 [error_ release];
6014 error_ = nil;
6015 }
6016 }
6017 }
6018
6019 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6020 switch ([response statusCode]) {
6021 case 200:
6022 cydia_ = YES;
6023 }
6024 }
6025
6026 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6027 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6028 if (error_ != nil)
6029 error_ = [error retain];
6030 [self _endConnection:connection];
6031 }
6032
6033 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6034 [self _endConnection:connection];
6035 }
6036
6037 - (NSString *) title { return UCLocalize("SOURCES"); }
6038
6039 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6040 NSMutableURLRequest *request = [NSMutableURLRequest
6041 requestWithURL:[NSURL URLWithString:href]
6042 cachePolicy:NSURLRequestUseProtocolCachePolicy
6043 timeoutInterval:120.0
6044 ];
6045
6046 [request setHTTPMethod:method];
6047
6048 if (Machine_ != NULL)
6049 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6050 if (UniqueID_ != nil)
6051 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6052 if (Role_ != nil)
6053 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6054
6055 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6056 }
6057
6058 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6059 NSString *context([alert context]);
6060
6061 if ([context isEqualToString:@"source"]) {
6062 switch (button) {
6063 case 1: {
6064 NSString *href = [[alert textField] text];
6065
6066 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6067
6068 if (![href hasSuffix:@"/"])
6069 href_ = [href stringByAppendingString:@"/"];
6070 else
6071 href_ = href;
6072 href_ = [href_ retain];
6073
6074 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6075 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6076 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6077 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6078
6079 cydia_ = false;
6080
6081 // XXX: this is stupid
6082 hud_ = [[delegate_ addProgressHUD] retain];
6083 [hud_ setText:UCLocalize("VERIFYING_URL")];
6084 } break;
6085
6086 case 0:
6087 break;
6088
6089 _nodefault
6090 }
6091
6092 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6093 } else if ([context isEqualToString:@"trivial"])
6094 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6095 else if ([context isEqualToString:@"urlerror"])
6096 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6097 else if ([context isEqualToString:@"warning"]) {
6098 switch (button) {
6099 case 1:
6100 [self complete];
6101 break;
6102
6103 case 0:
6104 break;
6105
6106 _nodefault
6107 }
6108
6109 [href_ release];
6110 href_ = nil;
6111
6112 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6113 }
6114 }
6115
6116 - (id) initWithDatabase:(Database *)database {
6117 if ((self = [super init]) != nil) {
6118 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6119 [self updateButtonsForEditingStatus:NO animated:NO];
6120
6121 database_ = database;
6122 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6123
6124 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6125 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6126 [[self view] addSubview:list_];
6127
6128 [list_ setDataSource:self];
6129 [list_ setDelegate:self];
6130
6131 [self reloadData];
6132 } return self;
6133 }
6134
6135 - (void) reloadData {
6136 pkgSourceList list;
6137 if (!list.ReadMainList())
6138 return;
6139
6140 [sources_ removeAllObjects];
6141 [sources_ addObjectsFromArray:[database_ sources]];
6142 _trace();
6143 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6144 _trace();
6145
6146 int count([sources_ count]);
6147 offset_ = 0;
6148 for (int i = 0; i != count; i++) {
6149 if ([[sources_ objectAtIndex:i] record] == nil)
6150 break;
6151 offset_++;
6152 }
6153
6154 [list_ setEditing:NO];
6155 [self updateButtonsForEditingStatus:NO animated:NO];
6156 [list_ reloadData];
6157 }
6158
6159 - (void) addButtonClicked {
6160 /*[book_ pushPage:[[[AddSourceController alloc]
6161 initWithBook:book_
6162 database:database_
6163 ] autorelease]];*/
6164
6165 UIAlertView *alert = [[[UIAlertView alloc]
6166 initWithTitle:UCLocalize("ENTER_APT_URL")
6167 message:nil
6168 delegate:self
6169 cancelButtonTitle:UCLocalize("CANCEL")
6170 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6171 ] autorelease];
6172
6173 [alert setContext:@"source"];
6174 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6175
6176 [alert setNumberOfRows:1];
6177 [alert addTextFieldWithValue:@"http://" label:@""];
6178
6179 UITextInputTraits *traits = [[alert textField] textInputTraits];
6180 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6181 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6182 [traits setKeyboardType:UIKeyboardTypeURL];
6183 // XXX: UIReturnKeyDone
6184 [traits setReturnKeyType:UIReturnKeyNext];
6185
6186 [alert show];
6187 }
6188
6189 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6190 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6191 initWithTitle:UCLocalize("ADD")
6192 style:UIBarButtonItemStylePlain
6193 target:self
6194 action:@selector(addButtonClicked)
6195 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6196
6197 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6198 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6199 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6200 target:self
6201 action:@selector(editButtonClicked)
6202 ] autorelease] animated:animated];
6203
6204 if (IsWildcat_ && !editing)
6205 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6206 initWithTitle:UCLocalize("SETTINGS")
6207 style:UIBarButtonItemStylePlain
6208 target:self
6209 action:@selector(settingsButtonClicked)
6210 ] autorelease]];
6211 }
6212
6213 - (void) settingsButtonClicked {
6214 [delegate_ showSettings];
6215 }
6216
6217 - (void) editButtonClicked {
6218 [list_ setEditing:![list_ isEditing] animated:YES];
6219
6220 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6221 }
6222
6223 @end
6224 /* }}} */
6225
6226 /* Installed Controller {{{ */
6227 @interface InstalledController : FilteredPackageController {
6228 BOOL expert_;
6229 }
6230
6231 - (id) initWithDatabase:(Database *)database;
6232
6233 - (void) updateRoleButton;
6234 - (void) queueStatusDidChange;
6235
6236 @end
6237
6238 @implementation InstalledController
6239
6240 - (void) dealloc {
6241 [super dealloc];
6242 }
6243
6244 - (NSString *) title { return UCLocalize("INSTALLED"); }
6245
6246 - (id) initWithDatabase:(Database *)database {
6247 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6248 [self updateRoleButton];
6249 [self queueStatusDidChange];
6250 } return self;
6251 }
6252
6253 #if !AlwaysReload
6254 - (void) queueButtonClicked {
6255 [delegate_ queue];
6256 }
6257 #endif
6258
6259 - (void) queueStatusDidChange {
6260 #if !AlwaysReload
6261 if (IsWildcat_) {
6262 if (Queuing_) {
6263 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6264 initWithTitle:UCLocalize("QUEUE")
6265 style:UIBarButtonItemStyleDone
6266 target:self
6267 action:@selector(queueButtonClicked)
6268 ] autorelease]];
6269 } else {
6270 [[self navigationItem] setLeftBarButtonItem:nil];
6271 }
6272 }
6273 #endif
6274 }
6275
6276 - (void) reloadData {
6277 [packages_ reloadData];
6278 }
6279
6280 - (void) updateRoleButton {
6281 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6282 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6283 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6284 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6285 target:self
6286 action:@selector(roleButtonClicked)
6287 ] autorelease]];
6288 }
6289
6290 - (void) roleButtonClicked {
6291 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6292 [packages_ reloadData];
6293 expert_ = !expert_;
6294
6295 [self updateRoleButton];
6296 }
6297
6298 - (void) setDelegate:(id)delegate {
6299 [super setDelegate:delegate];
6300 [packages_ setDelegate:delegate];
6301 }
6302
6303 @end
6304 /* }}} */
6305
6306 /* Home Controller {{{ */
6307 @interface HomeController : CYBrowserController {
6308 }
6309
6310 @end
6311
6312 @implementation HomeController
6313
6314 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6315 [super _setMoreHeaders:request];
6316
6317 if (ChipID_ != nil)
6318 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6319 if (UniqueID_ != nil)
6320 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6321 if (PLMN_ != nil)
6322 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6323 }
6324
6325 - (void) aboutButtonClicked {
6326 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6327
6328 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6329 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6330 [alert setCancelButtonIndex:0];
6331
6332 [alert setMessage:
6333 @"Copyright (C) 2008-2010\n"
6334 "Jay Freeman (saurik)\n"
6335 "saurik@saurik.com\n"
6336 "http://www.saurik.com/"
6337 ];
6338
6339 [alert show];
6340 }
6341
6342 - (void) viewWillAppear:(BOOL)animated {
6343 [super viewWillAppear:animated];
6344 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6345 }
6346
6347 - (void) viewWillDisappear:(BOOL)animated {
6348 [super viewWillDisappear:animated];
6349 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6350 }
6351
6352 - (id) init {
6353 if ((self = [super init]) != nil) {
6354 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6355 initWithTitle:UCLocalize("ABOUT")
6356 style:UIBarButtonItemStylePlain
6357 target:self
6358 action:@selector(aboutButtonClicked)
6359 ] autorelease]];
6360 } return self;
6361 }
6362
6363 @end
6364 /* }}} */
6365 /* Manage Controller {{{ */
6366 @interface ManageController : CYBrowserController {
6367 }
6368
6369 - (void) queueStatusDidChange;
6370 @end
6371
6372 @implementation ManageController
6373
6374 - (id) init {
6375 if ((self = [super init]) != nil) {
6376 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6377
6378 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6379 initWithTitle:UCLocalize("SETTINGS")
6380 style:UIBarButtonItemStylePlain
6381 target:self
6382 action:@selector(settingsButtonClicked)
6383 ] autorelease]];
6384
6385 [self queueStatusDidChange];
6386 } return self;
6387 }
6388
6389 - (void) settingsButtonClicked {
6390 [delegate_ showSettings];
6391 }
6392
6393 #if !AlwaysReload
6394 - (void) queueButtonClicked {
6395 [delegate_ queue];
6396 }
6397
6398 - (void) applyLoadingTitle {
6399 // No "Loading" title.
6400 }
6401
6402 - (void) applyRightButton {
6403 // No right button.
6404 }
6405 #endif
6406
6407 - (void) queueStatusDidChange {
6408 #if !AlwaysReload
6409 if (!IsWildcat_ && Queuing_) {
6410 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6411 initWithTitle:UCLocalize("QUEUE")
6412 style:UIBarButtonItemStyleDone
6413 target:self
6414 action:@selector(queueButtonClicked)
6415 ] autorelease]];
6416 } else {
6417 [[self navigationItem] setRightBarButtonItem:nil];
6418 }
6419 #endif
6420 }
6421
6422 - (bool) isLoading {
6423 return false;
6424 }
6425
6426 @end
6427 /* }}} */
6428
6429 /* Refresh Bar {{{ */
6430 @interface RefreshBar : UINavigationBar {
6431 UIProgressIndicator *indicator_;
6432 UITextLabel *prompt_;
6433 UIProgressBar *progress_;
6434 UINavigationButton *cancel_;
6435 }
6436
6437 @end
6438
6439 @implementation RefreshBar
6440
6441 - (void) dealloc {
6442 [indicator_ release];
6443 [prompt_ release];
6444 [progress_ release];
6445 [cancel_ release];
6446 [super dealloc];
6447 }
6448
6449 - (void) positionViews {
6450 CGRect frame = [cancel_ frame];
6451 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6452 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6453 [cancel_ setFrame:frame];
6454
6455 CGSize prgsize = {75, 100};
6456 CGRect prgrect = {{
6457 [self frame].size.width - prgsize.width - 10,
6458 ([self frame].size.height - prgsize.height) / 2
6459 } , prgsize};
6460 [progress_ setFrame:prgrect];
6461
6462 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6463 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6464 CGRect indrect = {{indoffset, indoffset}, indsize};
6465 [indicator_ setFrame:indrect];
6466
6467 CGSize prmsize = {215, indsize.height + 4};
6468 CGRect prmrect = {{
6469 indoffset * 2 + indsize.width,
6470 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6471 }, prmsize};
6472 [prompt_ setFrame:prmrect];
6473 }
6474
6475 - (void)setFrame:(CGRect)frame {
6476 [super setFrame:frame];
6477
6478 [self positionViews];
6479 }
6480
6481 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6482 if ((self = [super initWithFrame:frame])) {
6483 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6484
6485 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6486 [self setBarStyle:UIBarStyleBlack];
6487
6488 UIBarStyle barstyle([self _barStyle:NO]);
6489 bool ugly(barstyle == UIBarStyleDefault);
6490
6491 UIProgressIndicatorStyle style = ugly ?
6492 UIProgressIndicatorStyleMediumBrown :
6493 UIProgressIndicatorStyleMediumWhite;
6494
6495 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6496 [indicator_ setStyle:style];
6497 [indicator_ startAnimation];
6498 [self addSubview:indicator_];
6499
6500 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6501 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6502 [prompt_ setBackgroundColor:[UIColor clearColor]];
6503 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6504 [self addSubview:prompt_];
6505
6506 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6507 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6508 [progress_ setStyle:0];
6509 [self addSubview:progress_];
6510
6511 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6512 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6513 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6514 [cancel_ setBarStyle:barstyle];
6515
6516 [self positionViews];
6517 } return self;
6518 }
6519
6520 - (void) cancel {
6521 [cancel_ removeFromSuperview];
6522 }
6523
6524 - (void) start {
6525 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6526 [progress_ setProgress:0];
6527 [self addSubview:cancel_];
6528 }
6529
6530 - (void) stop {
6531 [cancel_ removeFromSuperview];
6532 }
6533
6534 - (void) setPrompt:(NSString *)prompt {
6535 [prompt_ setText:prompt];
6536 }
6537
6538 - (void) setProgress:(float)progress {
6539 [progress_ setProgress:progress];
6540 }
6541
6542 @end
6543 /* }}} */
6544
6545 @class CYNavigationController;
6546
6547 /* Cydia Tab Bar Controller {{{ */
6548 @interface CYTabBarController : UITabBarController {
6549 _transient Database *database_;
6550 }
6551
6552 @end
6553
6554 @implementation CYTabBarController
6555
6556 /* XXX: some logic should probably go here related to
6557 freeing the view controllers on tab change */
6558
6559 - (void) reloadData {
6560 size_t count([[self viewControllers] count]);
6561 for (size_t i(0); i != count; ++i) {
6562 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6563 [page reloadData];
6564 }
6565 }
6566
6567 - (id) initWithDatabase:(Database *)database {
6568 if ((self = [super init]) != nil) {
6569 database_ = database;
6570 } return self;
6571 }
6572
6573 @end
6574 /* }}} */
6575
6576 /* Cydia Navigation Controller {{{ */
6577 @interface CYNavigationController : UINavigationController {
6578 _transient Database *database_;
6579 _transient id<UINavigationControllerDelegate> delegate_;
6580 }
6581
6582 - (id) initWithDatabase:(Database *)database;
6583 - (void) reloadData;
6584
6585 @end
6586
6587
6588 @implementation CYNavigationController
6589
6590 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6591 // Inherit autorotation settings for modal parents.
6592 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6593 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6594 } else {
6595 return [super shouldAutorotateToInterfaceOrientation:orientation];
6596 }
6597 }
6598
6599 - (void) dealloc {
6600 [super dealloc];
6601 }
6602
6603 - (void) reloadData {
6604 size_t count([[self viewControllers] count]);
6605 for (size_t i(0); i != count; ++i) {
6606 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6607 [page reloadData];
6608 }
6609 }
6610
6611 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6612 delegate_ = delegate;
6613 }
6614
6615 - (id) initWithDatabase:(Database *)database {
6616 if ((self = [super init]) != nil) {
6617 database_ = database;
6618 } return self;
6619 }
6620
6621 @end
6622 /* }}} */
6623 /* Cydia:// Protocol {{{ */
6624 @interface CydiaURLProtocol : NSURLProtocol {
6625 }
6626
6627 @end
6628
6629 @implementation CydiaURLProtocol
6630
6631 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6632 NSURL *url([request URL]);
6633 if (url == nil)
6634 return NO;
6635 NSString *scheme([[url scheme] lowercaseString]);
6636 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6637 return NO;
6638 return YES;
6639 }
6640
6641 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6642 return request;
6643 }
6644
6645 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6646 id<NSURLProtocolClient> client([self client]);
6647 if (icon == nil)
6648 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6649 else {
6650 NSData *data(UIImagePNGRepresentation(icon));
6651
6652 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6653 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6654 [client URLProtocol:self didLoadData:data];
6655 [client URLProtocolDidFinishLoading:self];
6656 }
6657 }
6658
6659 - (void) startLoading {
6660 id<NSURLProtocolClient> client([self client]);
6661 NSURLRequest *request([self request]);
6662
6663 NSURL *url([request URL]);
6664 NSString *href([url absoluteString]);
6665
6666 NSString *path([href substringFromIndex:8]);
6667 NSRange slash([path rangeOfString:@"/"]);
6668
6669 NSString *command;
6670 if (slash.location == NSNotFound) {
6671 command = path;
6672 path = nil;
6673 } else {
6674 command = [path substringToIndex:slash.location];
6675 path = [path substringFromIndex:(slash.location + 1)];
6676 }
6677
6678 Database *database([Database sharedInstance]);
6679
6680 if ([command isEqualToString:@"package-icon"]) {
6681 if (path == nil)
6682 goto fail;
6683 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6684 Package *package([database packageWithName:path]);
6685 if (package == nil)
6686 goto fail;
6687 UIImage *icon([package icon]);
6688 [self _returnPNGWithImage:icon forRequest:request];
6689 } else if ([command isEqualToString:@"source-icon"]) {
6690 if (path == nil)
6691 goto fail;
6692 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6693 NSString *source(Simplify(path));
6694 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6695 if (icon == nil)
6696 icon = [UIImage applicationImageNamed:@"unknown.png"];
6697 [self _returnPNGWithImage:icon forRequest:request];
6698 } else if ([command isEqualToString:@"uikit-image"]) {
6699 if (path == nil)
6700 goto fail;
6701 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6702 UIImage *icon(_UIImageWithName(path));
6703 [self _returnPNGWithImage:icon forRequest:request];
6704 } else if ([command isEqualToString:@"section-icon"]) {
6705 if (path == nil)
6706 goto fail;
6707 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6708 NSString *section(Simplify(path));
6709 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6710 if (icon == nil)
6711 icon = [UIImage applicationImageNamed:@"unknown.png"];
6712 [self _returnPNGWithImage:icon forRequest:request];
6713 } else fail: {
6714 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6715 }
6716 }
6717
6718 - (void) stopLoading {
6719 }
6720
6721 @end
6722 /* }}} */
6723
6724 /* Sections Controller {{{ */
6725 @interface SectionsController : CYViewController <
6726 UITableViewDataSource,
6727 UITableViewDelegate
6728 > {
6729 _transient Database *database_;
6730 NSMutableArray *sections_;
6731 NSMutableArray *filtered_;
6732 UITableView *list_;
6733 UIView *accessory_;
6734 BOOL editing_;
6735 }
6736
6737 - (id) initWithDatabase:(Database *)database;
6738 - (void) reloadData;
6739 - (void) resetView;
6740
6741 - (void) editButtonClicked;
6742
6743 @end
6744
6745 @implementation SectionsController
6746
6747 - (void) dealloc {
6748 [list_ setDataSource:nil];
6749 [list_ setDelegate:nil];
6750
6751 [sections_ release];
6752 [filtered_ release];
6753 [list_ release];
6754 [accessory_ release];
6755 [super dealloc];
6756 }
6757
6758 - (void) viewDidAppear:(BOOL)animated {
6759 [super viewDidAppear:animated];
6760 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6761 }
6762
6763 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6764 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6765 return section;
6766 }
6767
6768 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6769 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6770 }
6771
6772 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6773 return 45.0f;
6774 }*/
6775
6776 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6777 static NSString *reuseIdentifier = @"SectionCell";
6778
6779 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6780 if (cell == nil)
6781 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6782
6783 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6784
6785 return cell;
6786 }
6787
6788 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6789 if (editing_)
6790 return;
6791
6792 Section *section = [self sectionAtIndexPath:indexPath];
6793 NSString *name = [section name];
6794 NSString *title;
6795
6796 if ([indexPath row] == 0) {
6797 section = nil;
6798 name = nil;
6799 title = UCLocalize("ALL_PACKAGES");
6800 } else {
6801 if (name != nil) {
6802 name = [NSString stringWithString:name];
6803 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6804 } else {
6805 name = @"";
6806 title = UCLocalize("NO_SECTION");
6807 }
6808 }
6809
6810 FilteredPackageController *table = [[[FilteredPackageController alloc]
6811 initWithDatabase:database_
6812 title:title
6813 filter:@selector(isVisibleInSection:)
6814 with:name
6815 ] autorelease];
6816
6817 [table setDelegate:delegate_];
6818
6819 [[self navigationController] pushViewController:table animated:YES];
6820 }
6821
6822 - (NSString *) title { return UCLocalize("SECTIONS"); }
6823
6824 - (id) initWithDatabase:(Database *)database {
6825 if ((self = [super init]) != nil) {
6826 database_ = database;
6827
6828 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6829
6830 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6831 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6832
6833 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6834 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6835 [list_ setRowHeight:45.0f];
6836 [[self view] addSubview:list_];
6837
6838 [list_ setDataSource:self];
6839 [list_ setDelegate:self];
6840
6841 [self reloadData];
6842 } return self;
6843 }
6844
6845 - (void) reloadData {
6846 NSArray *packages = [database_ packages];
6847
6848 [sections_ removeAllObjects];
6849 [filtered_ removeAllObjects];
6850
6851 #if 0
6852 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6853 SectionMap sections;
6854 sections.resize(64);
6855 #else
6856 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6857 #endif
6858
6859 _trace();
6860 for (Package *package in packages) {
6861 NSString *name([package section]);
6862 NSString *key(name == nil ? @"" : name);
6863
6864 #if 0
6865 Section **section;
6866
6867 _profile(SectionsView$reloadData$Section)
6868 section = &sections[key];
6869 if (*section == nil) {
6870 _profile(SectionsView$reloadData$Section$Allocate)
6871 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6872 _end
6873 }
6874 _end
6875
6876 [*section addToCount];
6877
6878 _profile(SectionsView$reloadData$Filter)
6879 if (![package valid] || ![package visible])
6880 continue;
6881 _end
6882
6883 [*section addToRow];
6884 #else
6885 Section *section;
6886
6887 _profile(SectionsView$reloadData$Section)
6888 section = [sections objectForKey:key];
6889 if (section == nil) {
6890 _profile(SectionsView$reloadData$Section$Allocate)
6891 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6892 [sections setObject:section forKey:key];
6893 _end
6894 }
6895 _end
6896
6897 [section addToCount];
6898
6899 _profile(SectionsView$reloadData$Filter)
6900 if (![package valid] || ![package visible])
6901 continue;
6902 _end
6903
6904 [section addToRow];
6905 #endif
6906 }
6907 _trace();
6908
6909 #if 0
6910 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6911 [sections_ addObject:i->second];
6912 #else
6913 [sections_ addObjectsFromArray:[sections allValues]];
6914 #endif
6915
6916 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6917
6918 for (Section *section in sections_) {
6919 size_t count([section row]);
6920 if (count == 0)
6921 continue;
6922
6923 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6924 [section setCount:count];
6925 [filtered_ addObject:section];
6926 }
6927
6928 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6929 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
6930 style:UIBarButtonItemStylePlain
6931 target:self
6932 action:@selector(editButtonClicked)
6933 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6934
6935 [list_ reloadData];
6936 _trace();
6937 }
6938
6939 - (void) resetView {
6940 if (editing_)
6941 [self editButtonClicked];
6942 }
6943
6944 - (void) editButtonClicked {
6945 if ((editing_ = !editing_))
6946 [list_ reloadData];
6947 else
6948 [delegate_ updateData];
6949
6950 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6951 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6952 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6953 }
6954
6955 - (UIView *) accessoryView {
6956 return accessory_;
6957 }
6958
6959 @end
6960 /* }}} */
6961 /* Changes Controller {{{ */
6962 @interface ChangesController : CYViewController <
6963 UITableViewDataSource,
6964 UITableViewDelegate
6965 > {
6966 _transient Database *database_;
6967 CFMutableArrayRef packages_;
6968 NSMutableArray *sections_;
6969 UITableView *list_;
6970 unsigned upgrades_;
6971 BOOL hasSentFirstLoad_;
6972 }
6973
6974 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6975 - (void) reloadData;
6976
6977 @end
6978
6979 @implementation ChangesController
6980
6981 - (void) dealloc {
6982 [list_ setDelegate:nil];
6983 [list_ setDataSource:nil];
6984
6985 CFRelease(packages_);
6986
6987 [sections_ release];
6988 [list_ release];
6989 [super dealloc];
6990 }
6991
6992 - (void) viewDidAppear:(BOOL)animated {
6993 [super viewDidAppear:animated];
6994 if (!hasSentFirstLoad_) {
6995 hasSentFirstLoad_ = YES;
6996 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6997 } else {
6998 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6999 }
7000 }
7001
7002 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7003 NSInteger count([sections_ count]);
7004 return count == 0 ? 1 : count;
7005 }
7006
7007 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7008 if ([sections_ count] == 0)
7009 return nil;
7010 return [[sections_ objectAtIndex:section] name];
7011 }
7012
7013 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7014 if ([sections_ count] == 0)
7015 return 0;
7016 return [[sections_ objectAtIndex:section] count];
7017 }
7018
7019 - (Package *) packageAtIndex:(NSUInteger)index {
7020 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7021 }
7022
7023 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7024 Section *section([sections_ objectAtIndex:[path section]]);
7025 NSInteger row([path row]);
7026 return [self packageAtIndex:([section row] + row)];
7027 }
7028
7029 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7030 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7031 if (cell == nil)
7032 cell = [[[PackageCell alloc] init] autorelease];
7033 [cell setPackage:[self packageAtIndexPath:path]];
7034 return cell;
7035 }
7036
7037 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7038 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7039 }*/
7040
7041 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7042 Package *package([self packageAtIndexPath:path]);
7043 PackageController *view([delegate_ packageController]);
7044 [view setDelegate:delegate_];
7045 [view setPackage:package];
7046 [[self navigationController] pushViewController:view animated:YES];
7047 return path;
7048 }
7049
7050 - (void) refreshButtonClicked {
7051 [delegate_ beginUpdate];
7052 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7053 }
7054
7055 - (void) upgradeButtonClicked {
7056 [delegate_ distUpgrade];
7057 }
7058
7059 - (NSString *) title { return UCLocalize("CHANGES"); }
7060
7061 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7062 if ((self = [super init]) != nil) {
7063 database_ = database;
7064 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7065
7066 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7067
7068 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7069
7070 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7071 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7072 [list_ setRowHeight:73.0f];
7073 [[self view] addSubview:list_];
7074
7075 [list_ setDataSource:self];
7076 [list_ setDelegate:self];
7077
7078 delegate_ = delegate;
7079 } return self;
7080 }
7081
7082 - (void) _reloadPackages:(NSArray *)packages {
7083 _trace();
7084 for (Package *package in packages)
7085 if (
7086 [package uninstalled] && [package valid] && [package visible] ||
7087 [package upgradableAndEssential:YES]
7088 )
7089 CFArrayAppendValue(packages_, package);
7090
7091 _trace();
7092 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7093 _trace();
7094 }
7095
7096 - (void) reloadData {
7097 NSArray *packages = [database_ packages];
7098
7099 CFArrayRemoveAllValues(packages_);
7100
7101 [sections_ removeAllObjects];
7102
7103 #if 0
7104 UIProgressHUD *hud([delegate_ addProgressHUD]);
7105 // XXX: localize
7106 [hud setText:@"Loading Changes"];
7107 //NSLog(@"HUD:%@::%@", delegate_, hud);
7108 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7109 [delegate_ removeProgressHUD:hud];
7110 #else
7111 [self _reloadPackages:packages];
7112 #endif
7113
7114 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7115 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7116 Section *section = nil;
7117 NSDate *last = nil;
7118
7119 upgrades_ = 0;
7120 bool unseens = false;
7121
7122 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7123
7124 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7125 Package *package = [self packageAtIndex:offset];
7126
7127 BOOL uae = [package upgradableAndEssential:YES];
7128
7129 if (!uae) {
7130 unseens = true;
7131 NSDate *seen;
7132
7133 _profile(ChangesController$reloadData$Remember)
7134 seen = [package seen];
7135 _end
7136
7137 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7138 last = seen;
7139
7140 NSString *name;
7141 if (seen == nil)
7142 name = UCLocalize("UNKNOWN");
7143 else {
7144 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7145 [name autorelease];
7146 }
7147
7148 _profile(ChangesController$reloadData$Allocate)
7149 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7150 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7151 [sections_ addObject:section];
7152 _end
7153 }
7154
7155 [section addToCount];
7156 } else if ([package ignored])
7157 [ignored addToCount];
7158 else {
7159 ++upgrades_;
7160 [upgradable addToCount];
7161 }
7162 }
7163 _trace();
7164
7165 CFRelease(formatter);
7166
7167 if (unseens) {
7168 Section *last = [sections_ lastObject];
7169 size_t count = [last count];
7170 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7171 [sections_ removeLastObject];
7172 }
7173
7174 if ([ignored count] != 0)
7175 [sections_ insertObject:ignored atIndex:0];
7176 if (upgrades_ != 0)
7177 [sections_ insertObject:upgradable atIndex:0];
7178
7179 [list_ reloadData];
7180
7181 if (upgrades_ > 0)
7182 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7183 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7184 style:UIBarButtonItemStylePlain
7185 target:self
7186 action:@selector(upgradeButtonClicked)
7187 ] autorelease]];
7188
7189 if (![delegate_ updating])
7190 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7191 initWithTitle:UCLocalize("REFRESH")
7192 style:UIBarButtonItemStylePlain
7193 target:self
7194 action:@selector(refreshButtonClicked)
7195 ] autorelease]];
7196 }
7197
7198 @end
7199 /* }}} */
7200 /* Search Controller {{{ */
7201 @interface SearchController : FilteredPackageController <
7202 UISearchBarDelegate
7203 > {
7204 UISearchBar *search_;
7205 }
7206
7207 - (id) initWithDatabase:(Database *)database;
7208 - (void) reloadData;
7209
7210 @end
7211
7212 @implementation SearchController
7213
7214 - (void) dealloc {
7215 [search_ release];
7216 [super dealloc];
7217 }
7218
7219 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7220 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7221 [search_ resignFirstResponder];
7222 [self reloadData];
7223 }
7224
7225 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7226 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7227 [self reloadData];
7228 }
7229
7230 - (NSString *) title { return nil; }
7231
7232 - (id) initWithDatabase:(Database *)database {
7233 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7234 }
7235
7236 - (void)viewDidAppear:(BOOL)animated {
7237 [super viewDidAppear:animated];
7238 if (!search_) {
7239 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7240 [search_ layoutSubviews];
7241 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7242 UITextField *textField = [search_ searchField];
7243 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7244 [search_ setDelegate:self];
7245 [textField setEnablesReturnKeyAutomatically:NO];
7246 [[self navigationItem] setTitleView:textField];
7247 }
7248 }
7249
7250 - (void) _reloadData {
7251 }
7252
7253 - (void) reloadData {
7254 _profile(SearchController$reloadData)
7255 [packages_ reloadData];
7256 _end
7257 PrintTimes();
7258 [packages_ resetCursor];
7259 }
7260
7261 - (void) didSelectPackage:(Package *)package {
7262 [search_ resignFirstResponder];
7263 [super didSelectPackage:package];
7264 }
7265
7266 @end
7267 /* }}} */
7268 /* Settings Controller {{{ */
7269 @interface SettingsController : CYViewController <
7270 UITableViewDataSource,
7271 UITableViewDelegate
7272 > {
7273 _transient Database *database_;
7274 NSString *name_;
7275 Package *package_;
7276 UITableView *table_;
7277 UISwitch *subscribedSwitch_;
7278 UISwitch *ignoredSwitch_;
7279 UITableViewCell *subscribedCell_;
7280 UITableViewCell *ignoredCell_;
7281 }
7282
7283 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7284
7285 @end
7286
7287 @implementation SettingsController
7288
7289 - (void) dealloc {
7290 [name_ release];
7291 if (package_ != nil)
7292 [package_ release];
7293 [table_ release];
7294 [subscribedSwitch_ release];
7295 [ignoredSwitch_ release];
7296 [subscribedCell_ release];
7297 [ignoredCell_ release];
7298
7299 [super dealloc];
7300 }
7301
7302 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7303 if (package_ == nil)
7304 return 0;
7305
7306 return 1;
7307 }
7308
7309 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7310 if (package_ == nil)
7311 return 0;
7312
7313 return 1;
7314 }
7315
7316 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7317 return UCLocalize("SHOW_ALL_CHANGES_EX");
7318 }
7319
7320 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7321 if (package_ == nil)
7322 return;
7323
7324 NSMutableDictionary *metadata([package_ metadata]);
7325
7326 BOOL before;
7327 if (NSNumber *number = [metadata objectForKey:key])
7328 before = [number boolValue];
7329 else
7330 before = NO;
7331
7332 if (value != before) {
7333 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7334 Changed_ = true;
7335 [delegate_ updateData];
7336 }
7337 }
7338
7339 - (void) onSubscribed:(id)control {
7340 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7341 }
7342
7343 - (void) onIgnored:(id)control {
7344 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
7345 }
7346
7347 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7348 if (package_ == nil)
7349 return nil;
7350
7351 switch ([indexPath row]) {
7352 case 0: return subscribedCell_;
7353 case 1: return ignoredCell_;
7354
7355 _nodefault
7356 }
7357
7358 return nil;
7359 }
7360
7361 - (NSString *) title { return UCLocalize("SETTINGS"); }
7362
7363 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7364 if ((self = [super init])) {
7365 database_ = database;
7366 name_ = [package retain];
7367
7368 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7369
7370 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7371 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7372 [[self view] addSubview:table_];
7373
7374 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7375 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7376 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7377
7378 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7379 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7380 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7381
7382 subscribedCell_ = [[UITableViewCell alloc] init];
7383 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7384 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7385 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7386
7387 ignoredCell_ = [[UITableViewCell alloc] init];
7388 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7389 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7390 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7391
7392 [table_ setDataSource:self];
7393 [table_ setDelegate:self];
7394 [self reloadData];
7395 } return self;
7396 }
7397
7398 - (void) reloadData {
7399 if (package_ != nil)
7400 [package_ autorelease];
7401 package_ = [database_ packageWithName:name_];
7402 if (package_ != nil) {
7403 [package_ retain];
7404 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7405 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7406 }
7407
7408 [table_ reloadData];
7409 }
7410
7411 @end
7412 /* }}} */
7413 /* Signature Controller {{{ */
7414 @interface SignatureController : CYBrowserController {
7415 _transient Database *database_;
7416 NSString *package_;
7417 }
7418
7419 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7420
7421 @end
7422
7423 @implementation SignatureController
7424
7425 - (void) dealloc {
7426 [package_ release];
7427 [super dealloc];
7428 }
7429
7430 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7431 // XXX: dude!
7432 [super webView:view didClearWindowObject:window forFrame:frame];
7433 }
7434
7435 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7436 if ((self = [super init]) != nil) {
7437 database_ = database;
7438 package_ = [package retain];
7439 [self reloadData];
7440 } return self;
7441 }
7442
7443 - (void) reloadData {
7444 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7445 }
7446
7447 @end
7448 /* }}} */
7449
7450 /* Role Controller {{{ */
7451 @interface RoleController : CYViewController <
7452 UITableViewDataSource,
7453 UITableViewDelegate
7454 > {
7455 _transient Database *database_;
7456 // XXX: ok, "roledelegate_"?...
7457 _transient id roledelegate_;
7458 UITableView *table_;
7459 UISegmentedControl *segment_;
7460 UIView *container_;
7461 }
7462
7463 - (void) showDoneButton;
7464 - (void) resizeSegmentedControl;
7465
7466 @end
7467
7468 @implementation RoleController
7469 - (void) dealloc {
7470 [table_ release];
7471 [segment_ release];
7472 [container_ release];
7473
7474 [super dealloc];
7475 }
7476
7477 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7478 if ((self = [super init])) {
7479 database_ = database;
7480 roledelegate_ = delegate;
7481
7482 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7483
7484 NSArray *items = [NSArray arrayWithObjects:
7485 UCLocalize("USER"),
7486 UCLocalize("HACKER"),
7487 UCLocalize("DEVELOPER"),
7488 nil];
7489 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7490 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7491 [container_ addSubview:segment_];
7492
7493 int index = -1;
7494 if ([Role_ isEqualToString:@"User"]) index = 0;
7495 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7496 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7497 if (index != -1) {
7498 [segment_ setSelectedSegmentIndex:index];
7499 [self showDoneButton];
7500 }
7501
7502 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7503 [self resizeSegmentedControl];
7504
7505 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7506 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7507 [table_ setDelegate:self];
7508 [table_ setDataSource:self];
7509 [[self view] addSubview:table_];
7510 [table_ reloadData];
7511 } return self;
7512 }
7513
7514 - (void) resizeSegmentedControl {
7515 CGFloat width = [[self view] frame].size.width;
7516 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7517 }
7518
7519 - (void) viewWillAppear:(BOOL)animated {
7520 [super viewWillAppear:animated];
7521
7522 [self resizeSegmentedControl];
7523 }
7524
7525 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7526 [self resizeSegmentedControl];
7527 }
7528
7529 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7530 [self resizeSegmentedControl];
7531 }
7532
7533 - (void) save {
7534 NSString *role(nil);
7535
7536 switch ([segment_ selectedSegmentIndex]) {
7537 case 0: role = @"User"; break;
7538 case 1: role = @"Hacker"; break;
7539 case 2: role = @"Developer"; break;
7540
7541 _nodefault
7542 }
7543
7544 if (![role isEqualToString:Role_]) {
7545 bool rolling(Role_ == nil);
7546 Role_ = role;
7547
7548 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7549 Role_, @"Role",
7550 nil];
7551
7552 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7553
7554 Changed_ = true;
7555
7556 if (rolling)
7557 [roledelegate_ loadData];
7558 else
7559 [roledelegate_ updateData];
7560 }
7561 }
7562
7563 - (void) segmentChanged:(UISegmentedControl *)control {
7564 [self showDoneButton];
7565 }
7566
7567 - (void) saveAndClose {
7568 [self save];
7569
7570 [[self navigationItem] setRightBarButtonItem:nil];
7571 [[self navigationController] dismissModalViewControllerAnimated:YES];
7572 }
7573
7574 - (void) doneButtonClicked {
7575 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7576 [spinner startAnimating];
7577 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7578 [[self navigationItem] setRightBarButtonItem:spinItem];
7579
7580 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7581 }
7582
7583 - (void) showDoneButton {
7584 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7585 initWithTitle:UCLocalize("DONE")
7586 style:UIBarButtonItemStyleDone
7587 target:self
7588 action:@selector(doneButtonClicked)
7589 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
7590 }
7591
7592 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7593 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7594 return 6;
7595 }
7596
7597 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7598 return 0; // :(
7599 }
7600
7601 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7602 return nil; // This method is required by the protocol.
7603 }
7604
7605 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7606 if (section == 1)
7607 return UCLocalize("ROLE_EX");
7608 if (section == 4)
7609 return [NSString stringWithFormat:
7610 @"%@: %@\n%@: %@\n%@: %@",
7611 UCLocalize("USER"), UCLocalize("USER_EX"),
7612 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7613 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7614 ];
7615 else return nil;
7616 }
7617
7618 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7619 return section == 3 ? 44.0f : 0;
7620 }
7621
7622 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7623 return section == 3 ? container_ : nil;
7624 }
7625
7626 @end
7627 /* }}} */
7628 /* Stash Controller {{{ */
7629 @interface CYStashController : CYViewController {
7630 // XXX: just delete these things
7631 _transient UIActivityIndicatorView *spinner_;
7632 _transient UILabel *status_;
7633 _transient UILabel *caption_;
7634 }
7635 @end
7636
7637 @implementation CYStashController
7638 - (id) init {
7639 if ((self = [super init])) {
7640 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7641
7642 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
7643 CGRect spinrect = [spinner_ frame];
7644 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7645 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7646 [spinner_ setFrame:spinrect];
7647 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7648 [[self view] addSubview:spinner_];
7649 [spinner_ startAnimating];
7650
7651 CGRect captrect;
7652 captrect.size.width = [[self view] frame].size.width;
7653 captrect.size.height = 40.0f;
7654 captrect.origin.x = 0;
7655 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7656 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
7657 [caption_ setText:@"Initializing Filesystem"];
7658 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7659 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7660 [caption_ setTextColor:[UIColor whiteColor]];
7661 [caption_ setBackgroundColor:[UIColor clearColor]];
7662 [caption_ setShadowColor:[UIColor blackColor]];
7663 [caption_ setTextAlignment:UITextAlignmentCenter];
7664 [[self view] addSubview:caption_];
7665
7666 CGRect statusrect;
7667 statusrect.size.width = [[self view] frame].size.width;
7668 statusrect.size.height = 30.0f;
7669 statusrect.origin.x = 0;
7670 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7671 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
7672 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7673 [status_ setText:@"(Cydia will exit when complete.)"];
7674 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7675 [status_ setTextColor:[UIColor whiteColor]];
7676 [status_ setBackgroundColor:[UIColor clearColor]];
7677 [status_ setShadowColor:[UIColor blackColor]];
7678 [status_ setTextAlignment:UITextAlignmentCenter];
7679 [[self view] addSubview:status_];
7680 } return self;
7681 }
7682
7683 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7684 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7685 }
7686 @end
7687 /* }}} */
7688
7689 /* Cydia Container {{{ */
7690 @interface CYContainer : UIViewController <ProgressDelegate> {
7691 _transient Database *database_;
7692 RefreshBar *refreshbar_;
7693
7694 bool dropped_;
7695 bool updating_;
7696 // XXX: ok, "updatedelegate_"?...
7697 _transient NSObject<CydiaDelegate> *updatedelegate_;
7698 // XXX: can't we query for this variable when we need it?
7699 _transient UITabBarController *root_;
7700 }
7701
7702 - (void) setTabBarController:(UITabBarController *)controller;
7703
7704 - (void) dropBar:(BOOL)animated;
7705 - (void) beginUpdate;
7706 - (void) raiseBar:(BOOL)animated;
7707 - (BOOL) updating;
7708
7709 @end
7710
7711 @implementation CYContainer
7712
7713 - (BOOL) _reallyWantsFullScreenLayout {
7714 return YES;
7715 }
7716
7717 // NOTE: UIWindow only sends the top controller these messages,
7718 // So we have to forward them on.
7719
7720 - (void) viewDidAppear:(BOOL)animated {
7721 [super viewDidAppear:animated];
7722 [root_ viewDidAppear:animated];
7723 }
7724
7725 - (void) viewWillAppear:(BOOL)animated {
7726 [super viewWillAppear:animated];
7727 [root_ viewWillAppear:animated];
7728 }
7729
7730 - (void) viewDidDisappear:(BOOL)animated {
7731 [super viewDidDisappear:animated];
7732 [root_ viewDidDisappear:animated];
7733 }
7734
7735 - (void) viewWillDisappear:(BOOL)animated {
7736 [super viewWillDisappear:animated];
7737 [root_ viewWillDisappear:animated];
7738 }
7739
7740 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7741 return ![updatedelegate_ hudIsShowing] && (IsWildcat_ || orientation == UIInterfaceOrientationPortrait);
7742 }
7743
7744 - (void) setTabBarController:(UITabBarController *)controller {
7745 root_ = controller;
7746 [[self view] addSubview:[root_ view]];
7747 }
7748
7749 - (void) setUpdate:(NSDate *)date {
7750 [self beginUpdate];
7751 }
7752
7753 - (void) beginUpdate {
7754 [self dropBar:YES];
7755 [refreshbar_ start];
7756
7757 updating_ = true;
7758
7759 [NSThread
7760 detachNewThreadSelector:@selector(performUpdate)
7761 toTarget:self
7762 withObject:nil
7763 ];
7764 }
7765
7766 - (void) performUpdate { _pooled
7767 Status status;
7768 status.setDelegate(self);
7769 [database_ updateWithStatus:status];
7770
7771 [self
7772 performSelectorOnMainThread:@selector(completeUpdate)
7773 withObject:nil
7774 waitUntilDone:NO
7775 ];
7776 }
7777
7778 - (void) completeUpdate {
7779 if (!updating_)
7780 return;
7781 updating_ = false;
7782
7783 [self raiseBar:YES];
7784 [refreshbar_ stop];
7785 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7786 }
7787
7788 - (void) cancelUpdate {
7789 updating_ = false;
7790 [self raiseBar:YES];
7791 [refreshbar_ stop];
7792 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7793 }
7794
7795 - (void) cancelPressed {
7796 [self cancelUpdate];
7797 }
7798
7799 - (BOOL) updating {
7800 return updating_;
7801 }
7802
7803 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7804 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7805 }
7806
7807 - (void) startProgress {
7808 }
7809
7810 - (void) setProgressTitle:(NSString *)title {
7811 [self
7812 performSelectorOnMainThread:@selector(_setProgressTitle:)
7813 withObject:title
7814 waitUntilDone:YES
7815 ];
7816 }
7817
7818 - (bool) isCancelling:(size_t)received {
7819 return !updating_;
7820 }
7821
7822 - (void) setProgressPercent:(float)percent {
7823 [self
7824 performSelectorOnMainThread:@selector(_setProgressPercent:)
7825 withObject:[NSNumber numberWithFloat:percent]
7826 waitUntilDone:YES
7827 ];
7828 }
7829
7830 - (void) addProgressOutput:(NSString *)output {
7831 [self
7832 performSelectorOnMainThread:@selector(_addProgressOutput:)
7833 withObject:output
7834 waitUntilDone:YES
7835 ];
7836 }
7837
7838 - (void) _setProgressTitle:(NSString *)title {
7839 [refreshbar_ setPrompt:title];
7840 }
7841
7842 - (void) _setProgressPercent:(NSNumber *)percent {
7843 [refreshbar_ setProgress:[percent floatValue]];
7844 }
7845
7846 - (void) _addProgressOutput:(NSString *)output {
7847 }
7848
7849 - (void) setUpdateDelegate:(id)delegate {
7850 updatedelegate_ = delegate;
7851 }
7852
7853 - (CGFloat) statusBarHeight {
7854 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7855 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7856 } else {
7857 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7858 }
7859 }
7860
7861 - (void) dropBar:(BOOL)animated {
7862 if (dropped_)
7863 return;
7864 dropped_ = true;
7865
7866 [[self view] addSubview:refreshbar_];
7867
7868 CGFloat sboffset = [self statusBarHeight];
7869
7870 CGRect barframe = [refreshbar_ frame];
7871 barframe.origin.y = sboffset;
7872 [refreshbar_ setFrame:barframe];
7873
7874 if (animated)
7875 [UIView beginAnimations:nil context:NULL];
7876 CGRect viewframe = [[root_ view] frame];
7877 viewframe.origin.y += barframe.size.height + sboffset;
7878 viewframe.size.height -= barframe.size.height + sboffset;
7879 [[root_ view] setFrame:viewframe];
7880 if (animated)
7881 [UIView commitAnimations];
7882
7883 // Ensure bar has the proper width for our view, it might have changed
7884 barframe.size.width = viewframe.size.width;
7885 [refreshbar_ setFrame:barframe];
7886
7887 // XXX: fix Apple's layout bug
7888 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7889 }
7890
7891 - (void) raiseBar:(BOOL)animated {
7892 if (!dropped_)
7893 return;
7894 dropped_ = false;
7895
7896 [refreshbar_ removeFromSuperview];
7897
7898 CGFloat sboffset = [self statusBarHeight];
7899
7900 if (animated)
7901 [UIView beginAnimations:nil context:NULL];
7902 CGRect barframe = [refreshbar_ frame];
7903 CGRect viewframe = [[root_ view] frame];
7904 viewframe.origin.y -= barframe.size.height + sboffset;
7905 viewframe.size.height += barframe.size.height + sboffset;
7906 [[root_ view] setFrame:viewframe];
7907 if (animated)
7908 [UIView commitAnimations];
7909
7910 // XXX: fix Apple's layout bug
7911 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7912 }
7913
7914 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7915 // XXX: fix Apple's layout bug
7916 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7917 }
7918
7919 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7920 if (dropped_) {
7921 [self raiseBar:NO];
7922 [self dropBar:NO];
7923 }
7924
7925 // XXX: fix Apple's layout bug
7926 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7927 }
7928
7929 - (void) statusBarFrameChanged:(NSNotification *)notification {
7930 if (dropped_) {
7931 [self raiseBar:NO];
7932 [self dropBar:NO];
7933 }
7934 }
7935
7936 - (void) dealloc {
7937 [refreshbar_ release];
7938 [[NSNotificationCenter defaultCenter] removeObserver:self];
7939 [super dealloc];
7940 }
7941
7942 - (id) initWithDatabase:(Database *)database {
7943 if ((self = [super init]) != nil) {
7944 database_ = database;
7945
7946 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7947 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7948
7949 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7950 } return self;
7951 }
7952
7953 @end
7954 /* }}} */
7955
7956 typedef enum {
7957 kCydiaTag = 0,
7958 kSectionsTag = 1,
7959 kChangesTag = 2,
7960 kManageTag = 3,
7961 kInstalledTag = 4,
7962 kSourcesTag = 5,
7963 kSearchTag = 6
7964 } CYTabTag;
7965
7966 @interface Cydia : UIApplication <
7967 ConfirmationControllerDelegate,
7968 ProgressControllerDelegate,
7969 CydiaDelegate,
7970 UINavigationControllerDelegate,
7971 UITabBarControllerDelegate
7972 > {
7973 // XXX: evaluate all fields for _transient
7974
7975 UIWindow *window_;
7976 CYContainer *container_;
7977 CYTabBarController *tabbar_;
7978
7979 NSMutableArray *essential_;
7980 NSMutableArray *broken_;
7981
7982 Database *database_;
7983
7984 int tag_;
7985
7986 UIKeyboard *keyboard_;
7987 int huds_;
7988
7989 SectionsController *sections_;
7990 ChangesController *changes_;
7991 ManageController *manage_;
7992 SearchController *search_;
7993 SourceTable *sources_;
7994 InstalledController *installed_;
7995 id queueDelegate_;
7996
7997 CYStashController *stash_;
7998
7999 bool loaded_;
8000 }
8001
8002 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
8003 - (void) setPage:(CYViewController *)page;
8004 - (void) loadData;
8005
8006 @end
8007
8008 static _finline void _setHomePage(Cydia *self) {
8009 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
8010 }
8011
8012 @implementation Cydia
8013
8014 - (void) beginUpdate {
8015 [container_ beginUpdate];
8016 }
8017
8018 - (BOOL) updating {
8019 return [container_ updating];
8020 }
8021
8022 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
8023 return window_;
8024 }
8025
8026 - (void) _loaded {
8027 if ([broken_ count] != 0) {
8028 int count = [broken_ count];
8029
8030 UIAlertView *alert = [[[UIAlertView alloc]
8031 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8032 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8033 delegate:self
8034 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8035 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8036 ] autorelease];
8037
8038 [alert setContext:@"fixhalf"];
8039 [alert show];
8040 } else if (!Ignored_ && [essential_ count] != 0) {
8041 int count = [essential_ count];
8042
8043 UIAlertView *alert = [[[UIAlertView alloc]
8044 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8045 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8046 delegate:self
8047 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8048 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8049 ] autorelease];
8050
8051 [alert setContext:@"upgrade"];
8052 [alert show];
8053 }
8054 }
8055
8056 - (void) _saveConfig {
8057 if (Changed_) {
8058 _trace();
8059 NSString *error(nil);
8060 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8061 _trace();
8062 NSError *error(nil);
8063 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8064 NSLog(@"failure to save metadata data: %@", error);
8065 _trace();
8066 } else {
8067 NSLog(@"failure to serialize metadata: %@", error);
8068 return;
8069 }
8070
8071 Changed_ = false;
8072 }
8073 }
8074
8075 - (void) _updateData {
8076 [self _saveConfig];
8077
8078 /* XXX: this is just stupid */
8079 if (tag_ != 1 && sections_ != nil)
8080 [sections_ reloadData];
8081 if (tag_ != 2 && changes_ != nil)
8082 [changes_ reloadData];
8083 if (tag_ != 4 && search_ != nil)
8084 [search_ reloadData];
8085
8086 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8087 }
8088
8089 - (int)indexOfTabWithTag:(int)tag {
8090 int i = 0;
8091 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8092 if ([[controller tabBarItem] tag] == tag)
8093 return i;
8094 i += 1;
8095 }
8096
8097 return -1;
8098 }
8099
8100 - (void) _refreshIfPossible {
8101 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8102
8103 bool recently = false;
8104 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8105 if (update != nil) {
8106 NSTimeInterval interval([update timeIntervalSinceNow]);
8107 if (interval <= 0 && interval > -(15*60))
8108 recently = true;
8109 }
8110
8111 // Don't automatic refresh if:
8112 // - We already refreshed recently.
8113 // - We already auto-refreshed this launch.
8114 // - Auto-refresh is disabled.
8115 if (recently || loaded_ || ManualRefresh) {
8116 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8117
8118 // If we are cancelling due to ManualRefresh or a recent refresh
8119 // we need to make sure it knows it's already loaded.
8120 loaded_ = true;
8121 return;
8122 } else {
8123 // We are going to load, so remember that.
8124 loaded_ = true;
8125 }
8126
8127 SCNetworkReachabilityFlags flags; {
8128 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8129 SCNetworkReachabilityGetFlags(reachability, &flags);
8130 CFRelease(reachability);
8131 }
8132
8133 // XXX: this elaborate mess is what Apple is using to determine this? :(
8134 // XXX: do we care if the user has to intervene? maybe that's ok?
8135 bool reachable(
8136 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8137 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8138 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8139 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8140 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8141 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8142 )
8143 );
8144
8145 // If we can reach the server, auto-refresh!
8146 if (reachable)
8147 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8148
8149 [pool release];
8150 }
8151
8152 - (void) refreshIfPossible {
8153 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8154 }
8155
8156 - (void) _reloadData {
8157 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8158 [hud setText:UCLocalize("RELOADING_DATA")];
8159
8160 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8161
8162 if (hud != nil)
8163 [self removeProgressHUD:hud];
8164
8165 size_t changes(0);
8166
8167 [essential_ removeAllObjects];
8168 [broken_ removeAllObjects];
8169
8170 NSArray *packages([database_ packages]);
8171 for (Package *package in packages) {
8172 if ([package half])
8173 [broken_ addObject:package];
8174 if ([package upgradableAndEssential:NO]) {
8175 if ([package essential])
8176 [essential_ addObject:package];
8177 ++changes;
8178 }
8179 }
8180
8181 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8182 if (changes != 0) {
8183 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8184 [changesItem setBadgeValue:badge];
8185 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8186
8187 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8188 [self setApplicationBadge:badge];
8189 else
8190 [self setApplicationBadgeString:badge];
8191 } else {
8192 [changesItem setBadgeValue:nil];
8193 [changesItem setAnimatedBadge:NO];
8194
8195 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8196 [self removeApplicationBadge];
8197 else // XXX: maybe use setApplicationBadgeString also?
8198 [self setApplicationIconBadgeNumber:0];
8199 }
8200
8201 [self _updateData];
8202
8203 [self refreshIfPossible];
8204 }
8205
8206 - (void) updateData {
8207 [database_ setVisible];
8208 [self _updateData];
8209 }
8210
8211 - (void) update_ {
8212 [database_ update];
8213 }
8214
8215 - (void) syncData {
8216 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8217 _assert(file != NULL);
8218
8219 for (NSString *key in [Sources_ allKeys]) {
8220 NSDictionary *source([Sources_ objectForKey:key]);
8221
8222 fprintf(file, "%s %s %s\n",
8223 [[source objectForKey:@"Type"] UTF8String],
8224 [[source objectForKey:@"URI"] UTF8String],
8225 [[source objectForKey:@"Distribution"] UTF8String]
8226 );
8227 }
8228
8229 fclose(file);
8230
8231 [self _saveConfig];
8232
8233 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8234 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8235 if (IsWildcat_)
8236 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8237 [container_ presentModalViewController:navigation animated:YES];
8238
8239 [progress
8240 detachNewThreadSelector:@selector(update_)
8241 toTarget:self
8242 withObject:nil
8243 title:UCLocalize("UPDATING_SOURCES")
8244 ];
8245 }
8246
8247 - (void) reloadData {
8248 @synchronized (self) {
8249 [self _reloadData];
8250 }
8251 }
8252
8253 - (void) resolve {
8254 pkgProblemResolver *resolver = [database_ resolver];
8255
8256 resolver->InstallProtect();
8257 if (!resolver->Resolve(true))
8258 _error->Discard();
8259 }
8260
8261 - (CGRect) popUpBounds {
8262 return [[tabbar_ view] bounds];
8263 }
8264
8265 - (bool) perform {
8266 if (![database_ prepare])
8267 return false;
8268
8269 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8270 [page setDelegate:self];
8271 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8272 [confirm_ setDelegate:self];
8273
8274 if (IsWildcat_)
8275 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8276 [container_ presentModalViewController:confirm_ animated:YES];
8277
8278 return true;
8279 }
8280
8281 - (void) queue {
8282 @synchronized (self) {
8283 [self perform];
8284 }
8285 }
8286
8287 - (void) clearPackage:(Package *)package {
8288 @synchronized (self) {
8289 [package clear];
8290 [self resolve];
8291 [self perform];
8292 }
8293 }
8294
8295 - (void) installPackages:(NSArray *)packages {
8296 @synchronized (self) {
8297 for (Package *package in packages)
8298 [package install];
8299 [self resolve];
8300 [self perform];
8301 }
8302 }
8303
8304 - (void) installPackage:(Package *)package {
8305 @synchronized (self) {
8306 [package install];
8307 [self resolve];
8308 [self perform];
8309 }
8310 }
8311
8312 - (void) removePackage:(Package *)package {
8313 @synchronized (self) {
8314 [package remove];
8315 [self resolve];
8316 [self perform];
8317 }
8318 }
8319
8320 - (void) distUpgrade {
8321 @synchronized (self) {
8322 if (![database_ upgrade])
8323 return;
8324 [self perform];
8325 }
8326 }
8327
8328 - (void) complete {
8329 @synchronized (self) {
8330 [self _reloadData];
8331 }
8332 }
8333
8334 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8335 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8336
8337 if (navigation != nil) {
8338 [navigation pushViewController:progress animated:YES];
8339 } else {
8340 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8341 if (IsWildcat_)
8342 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8343 [container_ presentModalViewController:navigation animated:YES];
8344 }
8345
8346 [progress
8347 detachNewThreadSelector:@selector(perform)
8348 toTarget:database_
8349 withObject:nil
8350 title:UCLocalize("RUNNING")
8351 ];
8352 }
8353
8354 - (void) progressControllerIsComplete:(ProgressController *)progress {
8355 [self complete];
8356 }
8357
8358 - (void) setPage:(CYViewController *)page {
8359 [page setDelegate:self];
8360
8361 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8362 [navController setViewControllers:[NSArray arrayWithObject:page]];
8363 for (CYNavigationController *page in [tabbar_ viewControllers])
8364 if (page != navController)
8365 [page setViewControllers:nil];
8366 }
8367
8368 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8369 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8370 [browser loadURL:url];
8371 return browser;
8372 }
8373
8374 - (SectionsController *) sectionsController {
8375 if (sections_ == nil)
8376 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8377 return sections_;
8378 }
8379
8380 - (ChangesController *) changesController {
8381 if (changes_ == nil)
8382 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8383 return changes_;
8384 }
8385
8386 - (ManageController *) manageController {
8387 if (manage_ == nil) {
8388 manage_ = (ManageController *) [[self
8389 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8390 withClass:[ManageController class]
8391 ] retain];
8392 if (!IsWildcat_)
8393 queueDelegate_ = manage_;
8394 }
8395 return manage_;
8396 }
8397
8398 - (SearchController *) searchController {
8399 if (search_ == nil)
8400 search_ = [[SearchController alloc] initWithDatabase:database_];
8401 return search_;
8402 }
8403
8404 - (SourceTable *) sourcesController {
8405 if (sources_ == nil)
8406 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8407 return sources_;
8408 }
8409
8410 - (InstalledController *) installedController {
8411 if (installed_ == nil) {
8412 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8413 if (IsWildcat_)
8414 queueDelegate_ = installed_;
8415 }
8416 return installed_;
8417 }
8418
8419 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8420 int tag = [[viewController tabBarItem] tag];
8421 if (tag == tag_) {
8422 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8423 return;
8424 } else if (tag_ == 1) {
8425 [[self sectionsController] resetView];
8426 }
8427
8428 switch (tag) {
8429 case kCydiaTag: _setHomePage(self); break;
8430
8431 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8432 case kChangesTag: [self setPage:[self changesController]]; break;
8433 case kManageTag: [self setPage:[self manageController]]; break;
8434 case kInstalledTag: [self setPage:[self installedController]]; break;
8435 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8436 case kSearchTag: [self setPage:[self searchController]]; break;
8437
8438 _nodefault
8439 }
8440
8441 tag_ = tag;
8442 }
8443
8444 - (void) showSettings {
8445 RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease];
8446 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8447 if (IsWildcat_)
8448 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8449 [container_ presentModalViewController:nav animated:YES];
8450 }
8451
8452 - (void) setPackageController:(PackageController *)view {
8453 WebThreadLock();
8454 [view setPackage:nil];
8455 WebThreadUnlock();
8456 }
8457
8458 - (PackageController *) _packageController {
8459 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8460 }
8461
8462 - (PackageController *) packageController {
8463 return [self _packageController];
8464 }
8465
8466 // Returns the navigation controller for the queuing badge.
8467 - (id) queueBadgeController {
8468 int index = [self indexOfTabWithTag:kManageTag];
8469 if (index == -1)
8470 index = [self indexOfTabWithTag:kInstalledTag];
8471
8472 return [[tabbar_ viewControllers] objectAtIndex:index];
8473 }
8474
8475 - (void) cancelAndClear:(bool)clear {
8476 @synchronized (self) {
8477 if (clear) {
8478 [database_ clear];
8479
8480 // Stop queuing.
8481 Queuing_ = false;
8482 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
8483 } else {
8484 // Start queuing.
8485 Queuing_ = true;
8486 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8487 }
8488
8489 // Show the changes in the current view.
8490 [(CYNavigationController *) [tabbar_ selectedViewController] reloadData];
8491 [queueDelegate_ queueStatusDidChange];
8492 }
8493 }
8494
8495 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8496 NSString *context([alert context]);
8497
8498 if ([context isEqualToString:@"fixhalf"]) {
8499 if (button == [alert firstOtherButtonIndex]) {
8500 @synchronized (self) {
8501 for (Package *broken in broken_) {
8502 [broken remove];
8503
8504 NSString *id = [broken id];
8505 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8506 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8507 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8508 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8509 }
8510
8511 [self resolve];
8512 [self perform];
8513 }
8514 } else if (button == [alert cancelButtonIndex]) {
8515 [broken_ removeAllObjects];
8516 [self _loaded];
8517 }
8518
8519 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8520 } else if ([context isEqualToString:@"upgrade"]) {
8521 if (button == [alert firstOtherButtonIndex]) {
8522 @synchronized (self) {
8523 for (Package *essential in essential_)
8524 [essential install];
8525
8526 [self resolve];
8527 [self perform];
8528 }
8529 } else if (button == [alert firstOtherButtonIndex] + 1) {
8530 [self distUpgrade];
8531 } else if (button == [alert cancelButtonIndex]) {
8532 Ignored_ = YES;
8533 }
8534
8535 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8536 }
8537 }
8538
8539 - (void) system:(NSString *)command { _pooled
8540 system([command UTF8String]);
8541 }
8542
8543 - (void) applicationWillSuspend {
8544 [database_ clean];
8545 [super applicationWillSuspend];
8546 }
8547
8548 - (BOOL) hudIsShowing {
8549 return (huds_ > 0);
8550 }
8551
8552 - (void) applicationSuspend:(__GSEvent *)event {
8553 // Use external process status API internally.
8554 // This is probably a really bad idea.
8555 uint64_t status = 0;
8556 int notify_token;
8557 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
8558 notify_get_state(notify_token, &status);
8559 notify_cancel(notify_token);
8560 }
8561
8562 if (![self hudIsShowing] && status == 0)
8563 [super applicationSuspend:event];
8564 }
8565
8566 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8567 if (![self hudIsShowing])
8568 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8569 }
8570
8571 - (void) _setSuspended:(BOOL)value {
8572 if (![self hudIsShowing])
8573 [super _setSuspended:value];
8574 }
8575
8576 - (UIProgressHUD *) addProgressHUD {
8577 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8578 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8579
8580 [window_ setUserInteractionEnabled:NO];
8581 [hud show:YES];
8582
8583 UIViewController *target = container_;
8584 while ([target modalViewController] != nil) target = [target modalViewController];
8585 [[target view] addSubview:hud];
8586
8587 huds_++;
8588 return hud;
8589 }
8590
8591 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8592 [hud show:NO];
8593 [hud removeFromSuperview];
8594 [window_ setUserInteractionEnabled:YES];
8595 huds_--;
8596 }
8597
8598 - (CYViewController *) pageForPackage:(NSString *)name {
8599 if (Package *package = [database_ packageWithName:name]) {
8600 PackageController *view([self packageController]);
8601 [view setPackage:package];
8602 return view;
8603 } else {
8604 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8605 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8606 return [self _pageForURL:url withClass:[CYBrowserController class]];
8607 }
8608 }
8609
8610 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8611 if (tag != NULL)
8612 *tag = -1;
8613
8614 NSString *href([url absoluteString]);
8615 if ([href hasPrefix:@"apptapp://package/"])
8616 return [self pageForPackage:[href substringFromIndex:18]];
8617
8618 NSString *scheme([[url scheme] lowercaseString]);
8619 if (![scheme isEqualToString:@"cydia"])
8620 return nil;
8621 NSString *path([url absoluteString]);
8622 if ([path length] < 8)
8623 return nil;
8624 path = [path substringFromIndex:8];
8625 if (![path hasPrefix:@"/"])
8626 path = [@"/" stringByAppendingString:path];
8627
8628 if ([path isEqualToString:@"/add-source"])
8629 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8630 else if ([path isEqualToString:@"/storage"])
8631 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8632 else if ([path isEqualToString:@"/sources"])
8633 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8634 else if ([path isEqualToString:@"/packages"])
8635 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8636 else if ([path hasPrefix:@"/url/"])
8637 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8638 else if ([path hasPrefix:@"/launch/"])
8639 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8640 else if ([path hasPrefix:@"/package-settings/"])
8641 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8642 else if ([path hasPrefix:@"/package-signature/"])
8643 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8644 else if ([path hasPrefix:@"/package/"])
8645 return [self pageForPackage:[path substringFromIndex:9]];
8646 else if ([path hasPrefix:@"/files/"]) {
8647 NSString *name = [path substringFromIndex:7];
8648
8649 if (Package *package = [database_ packageWithName:name]) {
8650 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8651 [files setPackage:package];
8652 return files;
8653 }
8654 }
8655
8656 return nil;
8657 }
8658
8659 - (void) applicationOpenURL:(NSURL *)url {
8660 [super applicationOpenURL:url];
8661 int tag;
8662 if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
8663 [self setPage:page];
8664 tag_ = tag;
8665 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8666 }
8667 }
8668
8669 - (void) applicationWillResignActive:(UIApplication *)application {
8670 // Stop refreshing if you get a phone call or lock the device.
8671 if ([container_ updating])
8672 [container_ cancelUpdate];
8673
8674 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8675 [super applicationWillResignActive:application];
8676 }
8677
8678 - (void) addStashController {
8679 stash_ = [[CYStashController alloc] init];
8680 [window_ addSubview:[stash_ view]];
8681 }
8682
8683 - (void) removeStashController {
8684 [[stash_ view] removeFromSuperview];
8685 [stash_ release];
8686 }
8687
8688 - (void) stash {
8689 [self setIdleTimerDisabled:YES];
8690
8691 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8692 [self setStatusBarShowsProgress:YES];
8693 UpdateExternalStatus(1);
8694
8695 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8696
8697 UpdateExternalStatus(0);
8698 [self setStatusBarShowsProgress:NO];
8699
8700 [self removeStashController];
8701
8702 if (ExecFork() == 0) {
8703 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8704 perror("launchctl stop");
8705 }
8706 }
8707
8708 - (void) setupTabBarController {
8709 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8710 [tabbar_ setDelegate:self];
8711
8712 NSMutableArray *items([NSMutableArray arrayWithObjects:
8713 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8714 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8715 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8716 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8717 nil]);
8718
8719 if (IsWildcat_) {
8720 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8721 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8722 } else {
8723 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8724 }
8725
8726 NSMutableArray *controllers([NSMutableArray array]);
8727
8728 for (UITabBarItem *item in items) {
8729 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8730 [controller setTabBarItem:item];
8731 [controllers addObject:controller];
8732 }
8733
8734 [tabbar_ setViewControllers:controllers];
8735 }
8736
8737 - (void) applicationDidFinishLaunching:(id)unused {
8738 [CYBrowserController _initialize];
8739
8740 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8741
8742 Font12_ = [[UIFont systemFontOfSize:12] retain];
8743 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8744 Font14_ = [[UIFont systemFontOfSize:14] retain];
8745 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8746 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8747
8748 tag_ = 0;
8749
8750 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8751 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8752
8753 UIScreen *screen([UIScreen mainScreen]);
8754
8755 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8756 [window_ orderFront:self];
8757 [window_ makeKey:self];
8758 [window_ setHidden:NO];
8759
8760 if (
8761 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8762 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8763 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8764 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8765 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8766 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8767 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8768 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8769 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8770 false
8771 ) {
8772 [self addStashController];
8773 // XXX: this would be much cleaner as a yieldToSelector:
8774 // that way the removeStashController could happen right here inline
8775 // we also could no longer require the useless stash_ field anymore
8776 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8777 return;
8778 }
8779
8780 database_ = [Database sharedInstance];
8781
8782 [self setupTabBarController];
8783
8784 container_ = [[CYContainer alloc] initWithDatabase:database_];
8785 [container_ setUpdateDelegate:self];
8786 [container_ setTabBarController:tabbar_];
8787 [window_ addSubview:[container_ view]];
8788
8789 // Show pinstripes while loading data.
8790 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8791
8792 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8793 _trace();
8794 }
8795
8796 - (void) loadData {
8797 _trace();
8798 if (Role_ == nil) {
8799 [self showSettings];
8800 return;
8801 }
8802
8803 [window_ setUserInteractionEnabled:NO];
8804
8805 UIView *container = [[[UIView alloc] init] autorelease];
8806 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8807
8808 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
8809 [spinner startAnimating];
8810 [container addSubview:spinner];
8811
8812 UILabel *label = [[[UILabel alloc] init] autorelease];
8813 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8814 [label setBackgroundColor:[UIColor clearColor]];
8815 [label setTextColor:[UIColor blackColor]];
8816 [label setShadowColor:[UIColor whiteColor]];
8817 [label setShadowOffset:CGSizeMake(0, 1)];
8818 [label setText:UCLocalize("LOADING_DATA")];
8819 [container addSubview:label];
8820
8821 CGSize viewsize = [[tabbar_ view] frame].size;
8822 CGSize spinnersize = [spinner bounds].size;
8823 CGSize textsize = [[label text] sizeWithFont:[label font]];
8824 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8825
8826 CGRect containrect = {
8827 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8828 CGSizeMake(bothwidth, spinnersize.height)
8829 };
8830 CGRect textrect = {
8831 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8832 textsize
8833 };
8834 CGRect spinrect = {
8835 CGPointZero,
8836 spinnersize
8837 };
8838
8839 [container setFrame:containrect];
8840 [spinner setFrame:spinrect];
8841 [label setFrame:textrect];
8842 [[container_ view] addSubview:container];
8843
8844 [self reloadData];
8845 PrintTimes();
8846
8847 // Show the home page
8848 [tabbar_ setSelectedIndex:0];
8849 _setHomePage(self);
8850 [window_ setUserInteractionEnabled:YES];
8851
8852 // XXX: does this actually slow anything down?
8853 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8854 [container removeFromSuperview];
8855 }
8856
8857 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8858 if (item != nil && IsWildcat_) {
8859 [sheet showFromBarButtonItem:item animated:YES];
8860 } else {
8861 [sheet showInView:window_];
8862 }
8863 }
8864
8865 @end
8866
8867 /*IMP alloc_;
8868 id Alloc_(id self, SEL selector) {
8869 id object = alloc_(self, selector);
8870 lprintf("[%s]A-%p\n", self->isa->name, object);
8871 return object;
8872 }*/
8873
8874 /*IMP dealloc_;
8875 id Dealloc_(id self, SEL selector) {
8876 id object = dealloc_(self, selector);
8877 lprintf("[%s]D-%p\n", self->isa->name, object);
8878 return object;
8879 }*/
8880
8881 Class $WebDefaultUIKitDelegate;
8882
8883 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8884 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8885 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8886 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8887 }
8888
8889 static NSNumber *shouldPlayKeyboardSounds;
8890
8891 Class $UIHardware;
8892
8893 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8894 switch (sound) {
8895 case 1104: // Keyboard Button Clicked
8896 case 1105: // Keyboard Delete Repeated
8897 if (shouldPlayKeyboardSounds == nil) {
8898 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8899 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8900 }
8901
8902 if (![shouldPlayKeyboardSounds boolValue])
8903 break;
8904
8905 default:
8906 _UIHardware$_playSystemSound$(self, _cmd, sound);
8907 }
8908 }
8909
8910 int main(int argc, char *argv[]) { _pooled
8911 _trace();
8912
8913 if (Class $UIDevice = objc_getClass("UIDevice")) {
8914 UIDevice *device([$UIDevice currentDevice]);
8915 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8916 } else
8917 IsWildcat_ = false;
8918
8919 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8920
8921 /* Library Hacks {{{ */
8922 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8923
8924 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8925 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8926 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8927 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8928 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8929 }
8930
8931 $UIHardware = objc_getClass("UIHardware");
8932 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8933 if (UIHardware$_playSystemSound$ != NULL) {
8934 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8935 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8936 }
8937 /* }}} */
8938 /* Set Locale {{{ */
8939 Locale_ = CFLocaleCopyCurrent();
8940 Languages_ = [NSLocale preferredLanguages];
8941 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8942 //NSLog(@"%@", [Languages_ description]);
8943
8944 const char *lang;
8945 if (Languages_ == nil || [Languages_ count] == 0)
8946 // XXX: consider just setting to C and then falling through?
8947 lang = NULL;
8948 else {
8949 lang = [[Languages_ objectAtIndex:0] UTF8String];
8950 setenv("LANG", lang, true);
8951 }
8952
8953 //std::setlocale(LC_ALL, lang);
8954 NSLog(@"Setting Language: %s", lang);
8955 /* }}} */
8956
8957 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8958
8959 /* Parse Arguments {{{ */
8960 bool substrate(false);
8961
8962 if (argc != 0) {
8963 char **args(argv);
8964 int arge(1);
8965
8966 for (int argi(1); argi != argc; ++argi)
8967 if (strcmp(argv[argi], "--") == 0) {
8968 arge = argi;
8969 argv[argi] = argv[0];
8970 argv += argi;
8971 argc -= argi;
8972 break;
8973 }
8974
8975 for (int argi(1); argi != arge; ++argi)
8976 if (strcmp(args[argi], "--substrate") == 0)
8977 substrate = true;
8978 else
8979 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8980 }
8981 /* }}} */
8982
8983 App_ = [[NSBundle mainBundle] bundlePath];
8984 Home_ = NSHomeDirectory();
8985 Advanced_ = YES;
8986
8987 setuid(0);
8988 setgid(0);
8989
8990 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8991 alloc_ = alloc->method_imp;
8992 alloc->method_imp = (IMP) &Alloc_;*/
8993
8994 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8995 dealloc_ = dealloc->method_imp;
8996 dealloc->method_imp = (IMP) &Dealloc_;*/
8997
8998 /* System Information {{{ */
8999 size_t size;
9000
9001 int maxproc;
9002 size = sizeof(maxproc);
9003 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9004 perror("sysctlbyname(\"kern.maxproc\", ?)");
9005 else if (maxproc < 64) {
9006 maxproc = 64;
9007 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9008 perror("sysctlbyname(\"kern.maxproc\", #)");
9009 }
9010
9011 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9012 char *osversion = new char[size];
9013 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9014 perror("sysctlbyname(\"kern.osversion\", ?)");
9015 else
9016 System_ = [NSString stringWithUTF8String:osversion];
9017
9018 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9019 char *machine = new char[size];
9020 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9021 perror("sysctlbyname(\"hw.machine\", ?)");
9022 else
9023 Machine_ = machine;
9024
9025 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9026 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9027 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9028 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9029 CFRelease(serial);
9030 }
9031
9032 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9033 NSData *data((NSData *) ecid);
9034 size_t length([data length]);
9035 uint8_t bytes[length];
9036 [data getBytes:bytes];
9037 char string[length * 2 + 1];
9038 for (size_t i(0); i != length; ++i)
9039 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9040 ChipID_ = [NSString stringWithUTF8String:string];
9041 CFRelease(ecid);
9042 }
9043
9044 IOObjectRelease(service);
9045 }
9046 }
9047
9048 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9049
9050 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9051 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9052 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9053
9054 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9055 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9056 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9057
9058 if (mcc != NULL && mnc != NULL)
9059 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9060
9061 if (mnc != NULL)
9062 CFRelease(mnc);
9063 if (mcc != NULL)
9064 CFRelease(mcc);
9065
9066 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9067 Build_ = [system objectForKey:@"ProductBuildVersion"];
9068 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9069 Product_ = [info objectForKey:@"SafariProductVersion"];
9070 Safari_ = [info objectForKey:@"CFBundleVersion"];
9071 }
9072 /* }}} */
9073 /* Load Database {{{ */
9074 _trace();
9075 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9076 _trace();
9077 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9078
9079 if (Metadata_ == NULL)
9080 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9081 else {
9082 Settings_ = [Metadata_ objectForKey:@"Settings"];
9083
9084 Packages_ = [Metadata_ objectForKey:@"Packages"];
9085 Sections_ = [Metadata_ objectForKey:@"Sections"];
9086 Sources_ = [Metadata_ objectForKey:@"Sources"];
9087
9088 Token_ = [Metadata_ objectForKey:@"Token"];
9089 }
9090
9091 if (Settings_ != nil)
9092 Role_ = [Settings_ objectForKey:@"Role"];
9093
9094 if (Packages_ == nil) {
9095 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
9096 [Metadata_ setObject:Packages_ forKey:@"Packages"];
9097 }
9098
9099 if (Sections_ == nil) {
9100 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9101 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9102 }
9103
9104 if (Sources_ == nil) {
9105 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9106 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9107 }
9108 /* }}} */
9109
9110 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9111
9112 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9113 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9114 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9115 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9116 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9117 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9118
9119 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9120
9121 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9122 unlink("/tmp/.cydia.fw");
9123 goto firmware;
9124 } else if (access("/User", F_OK) != 0 || version < 2) {
9125 firmware:
9126 _trace();
9127 system("/usr/libexec/cydia/firmware.sh");
9128 _trace();
9129 }
9130
9131 _assert([[NSFileManager defaultManager]
9132 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9133 withIntermediateDirectories:YES
9134 attributes:nil
9135 error:NULL
9136 ]);
9137
9138 if (access("/tmp/cydia.chk", F_OK) == 0) {
9139 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9140 _assert(errno == ENOENT);
9141 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9142 _assert(errno == ENOENT);
9143 }
9144
9145 /* APT Initialization {{{ */
9146 _assert(pkgInitConfig(*_config));
9147 _assert(pkgInitSystem(*_config, _system));
9148
9149 if (lang != NULL)
9150 _config->Set("APT::Acquire::Translation", lang);
9151
9152 // XXX: this timeout might be important :(
9153 //_config->Set("Acquire::http::Timeout", 15);
9154
9155 _config->Set("Acquire::http::MaxParallel", 3);
9156 /* }}} */
9157 /* Color Choices {{{ */
9158 space_ = CGColorSpaceCreateDeviceRGB();
9159
9160 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9161 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9162 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9163 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9164 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9165 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9166 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9167 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9168 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9169
9170 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9171 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9172 /* }}}*/
9173 /* UIKit Configuration {{{ */
9174 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9175 if ($GSFontSetUseLegacyFontMetrics != NULL)
9176 $GSFontSetUseLegacyFontMetrics(YES);
9177
9178 // XXX: I have a feeling this was important
9179 //UIKeyboardDisableAutomaticAppearance();
9180 /* }}} */
9181
9182 Colon_ = UCLocalize("COLON_DELIMITED");
9183 Error_ = UCLocalize("ERROR");
9184 Warning_ = UCLocalize("WARNING");
9185
9186 _trace();
9187 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9188
9189 CGColorSpaceRelease(space_);
9190 CFRelease(Locale_);
9191
9192 return value;
9193 }