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