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