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