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