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