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