1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2010 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
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
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.
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.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "UICaboodle/UCPlatform.h"
45 #include "UICaboodle/UCLocalize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
111 #include <mach-o/nlist.h>
121 #include <ext/hash_map>
123 #include "UICaboodle/BrowserView.h"
125 #include "substrate.h"
132 #define _timestamp ({ \
134 gettimeofday(&tv, NULL); \
135 tv.tv_sec * 1000000 + tv.tv_usec; \
138 typedef std::vector<class ProfileTime *> TimeList;
148 ProfileTime(const char *name) :
152 times_.push_back(this);
155 void AddTime(uint64_t time) {
162 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
174 ProfileTimer(ProfileTime &time) :
181 time_.AddTime(_timestamp - start_);
186 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
188 std::cerr << "========" << std::endl;
191 #define _profile(name) { \
192 static ProfileTime name(#name); \
193 ProfileTimer _ ## name(name);
198 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
200 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
202 void NSLogPoint(const char *fix, const CGPoint &point) {
203 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
206 void NSLogRect(const char *fix, const CGRect &rect) {
207 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
210 static _finline NSString *CydiaURL(NSString *path) {
212 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
213 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
214 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
215 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
216 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
217 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
220 static _finline void UpdateExternalStatus(uint64_t newStatus) {
222 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
223 notify_set_state(notify_token, newStatus);
224 notify_cancel(notify_token);
226 notify_post("com.saurik.Cydia.status");
229 /* [NSObject yieldToSelector:(withObject:)] {{{*/
230 @interface NSObject (Cydia)
231 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
232 - (id) yieldToSelector:(SEL)selector;
235 @implementation NSObject (Cydia)
240 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
241 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
242 id object([[context objectAtIndex:1] nonretainedObjectValue]);
243 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
245 /* XXX: deal with exceptions */
246 id value([self performSelector:selector withObject:object]);
248 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
249 [context removeAllObjects];
250 if ([signature methodReturnLength] != 0 && value != nil)
251 [context addObject:value];
256 performSelectorOnMainThread:@selector(doNothing)
262 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
263 /*return [self performSelector:selector withObject:object];*/
265 volatile bool stopped(false);
267 NSMutableArray *context([NSMutableArray arrayWithObjects:
268 [NSValue valueWithPointer:selector],
269 [NSValue valueWithNonretainedObject:object],
270 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
273 NSThread *thread([[[NSThread alloc]
275 selector:@selector(_yieldToContext:)
281 NSRunLoop *loop([NSRunLoop currentRunLoop]);
282 NSDate *future([NSDate distantFuture]);
284 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
286 return [context count] == 0 ? nil : [context objectAtIndex:0];
289 - (id) yieldToSelector:(SEL)selector {
290 return [self yieldToSelector:selector withObject:nil];
296 @interface CYActionSheet : UIAlertView {
300 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
303 @implementation CYActionSheet
305 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
306 if ((self = [super init])) {
307 [self setTitle:title];
308 [self setDelegate:self];
309 for (NSString *button in buttons) [self addButtonWithTitle:button];
310 [self setCancelButtonIndex:index];
314 - (void) _updateFrameForDisplay {
315 [super _updateFrameForDisplay];
316 if ([self cancelButtonIndex] == -1) {
317 NSArray *buttons = [self buttons];
318 if ([buttons count]) {
319 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
320 for (UIThreePartButton *button in buttons)
321 [button setBackground:background forState:0];
326 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
327 button_ = buttonIndex + 1;
331 [self dismissWithClickedButtonIndex:-1 animated:YES];
334 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
335 [self setRunsModal:YES];
343 /* NSForcedOrderingSearch doesn't work on the iPhone */
344 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
345 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
346 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
348 /* Information Dictionaries {{{ */
349 @interface NSMutableArray (Cydia)
350 - (void) addInfoDictionary:(NSDictionary *)info;
353 @implementation NSMutableArray (Cydia)
355 - (void) addInfoDictionary:(NSDictionary *)info {
356 [self addObject:info];
361 @interface NSMutableDictionary (Cydia)
362 - (void) addInfoDictionary:(NSDictionary *)info;
365 @implementation NSMutableDictionary (Cydia)
367 - (void) addInfoDictionary:(NSDictionary *)info {
368 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
374 #define lprintf(args...) fprintf(stderr, args)
377 #define TraceLogging (1 && !ForRelease)
378 #define HistogramInsertionSort (0 && !ForRelease)
379 #define ProfileTimes (0 && !ForRelease)
380 #define ForSaurik (0 && !ForRelease)
381 #define LogBrowser (0 && !ForRelease)
382 #define TrackResize (0 && !ForRelease)
383 #define ManualRefresh (1 && !ForRelease)
384 #define ShowInternals (0 && !ForRelease)
385 #define IgnoreInstall (0 && !ForRelease)
386 #define AlwaysReload (0 && !ForRelease)
390 #define _trace(args...)
395 #define _profile(name) {
398 #define PrintTimes() do {} while (false)
402 typedef uint32_t (*SKRadixFunction)(id, void *);
404 @interface NSMutableArray (Radix)
405 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
406 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
414 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
415 struct RadixItem_ *lhs(swap), *rhs(swap + count);
417 static const size_t width = 32;
418 static const size_t bits = 11;
419 static const size_t slots = 1 << bits;
420 static const size_t passes = (width + (bits - 1)) / bits;
422 size_t *hist(new size_t[slots]);
424 for (size_t pass(0); pass != passes; ++pass) {
425 memset(hist, 0, sizeof(size_t) * slots);
427 for (size_t i(0); i != count; ++i) {
428 uint32_t key(lhs[i].key);
430 key &= _not(uint32_t) >> width - bits;
435 for (size_t i(0); i != slots; ++i) {
436 size_t local(offset);
441 for (size_t i(0); i != count; ++i) {
442 uint32_t key(lhs[i].key);
444 key &= _not(uint32_t) >> width - bits;
445 rhs[hist[key]++] = lhs[i];
448 RadixItem_ *tmp(lhs);
455 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
456 for (size_t i(0); i != count; ++i)
457 [values addObject:[self objectAtIndex:lhs[i].index]];
458 [self setArray:values];
463 @implementation NSMutableArray (Radix)
465 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
466 size_t count([self count]);
471 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
472 [invocation setSelector:selector];
473 [invocation setArgument:&object atIndex:2];
475 /* XXX: this is an unsafe optimization of doomy hell */
476 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
477 _assert(method != NULL);
478 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
479 _assert(imp != NULL);
482 struct RadixItem_ *swap(new RadixItem_[count * 2]);
484 for (size_t i(0); i != count; ++i) {
485 RadixItem_ &item(swap[i]);
488 id object([self objectAtIndex:i]);
491 [invocation setTarget:object];
493 [invocation getReturnValue:&item.key];
495 item.key = imp(object, selector, object);
499 RadixSort_(self, count, swap);
502 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
503 size_t count([self count]);
504 struct RadixItem_ *swap(new RadixItem_[count * 2]);
506 for (size_t i(0); i != count; ++i) {
507 RadixItem_ &item(swap[i]);
510 id object([self objectAtIndex:i]);
511 item.key = function(object, argument);
514 RadixSort_(self, count, swap);
519 /* Insertion Sort {{{ */
521 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
522 const char *ptr = (const char *)list;
524 CFIndex half = count / 2;
525 const char *probe = ptr + elementSize * half;
526 CFComparisonResult cr = comparator(element, probe, context);
527 if (0 == cr) return (probe - (const char *)list) / elementSize;
528 ptr = (cr < 0) ? ptr : probe + elementSize;
529 count = (cr < 0) ? half : (half + (count & 1) - 1);
531 return (ptr - (const char *)list) / elementSize;
534 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
535 const char *ptr = (const char *)list;
537 CFIndex half = count / 2;
538 const char *probe = ptr + elementSize * half;
539 CFComparisonResult cr = comparator(element, probe, context);
540 if (0 == cr) return (probe - (const char *)list) / elementSize;
541 ptr = (cr < 0) ? ptr : probe + elementSize;
542 count = (cr < 0) ? half : (half + (count & 1) - 1);
544 return (ptr - (const char *)list) / elementSize;
547 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
548 if (range.length == 0)
550 const void **values(new const void *[range.length]);
551 CFArrayGetValues(array, range, values);
553 #if HistogramInsertionSort
554 uint32_t total(0), *offsets(new uint32_t[range.length]);
557 for (CFIndex index(1); index != range.length; ++index) {
558 const void *value(values[index]);
559 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
560 CFIndex correct(index);
561 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
564 if (correct != index) {
565 size_t offset(index - correct);
566 #if HistogramInsertionSort
570 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
572 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
573 values[correct] = value;
577 CFArrayReplaceValues(array, range, values, range.length);
580 #if HistogramInsertionSort
581 for (CFIndex index(0); index != range.length; ++index)
582 if (offsets[index] != 0)
583 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
584 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
591 /* Apple Bug Fixes {{{ */
592 @implementation UIWebDocumentView (Cydia)
594 - (void) _setScrollerOffset:(CGPoint)offset {
595 UIScroller *scroller([self _scroller]);
597 CGSize size([scroller contentSize]);
598 CGSize bounds([scroller bounds].size);
601 max.x = size.width - bounds.width;
602 max.y = size.height - bounds.height;
610 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
611 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
613 [scroller setOffset:offset];
619 @implementation WebScriptObject (NSFastEnumeration)
621 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
622 size_t length([self count] - state->state);
625 else if (length > count)
627 for (size_t i(0); i != length; ++i)
628 objects[i] = [self objectAtIndex:state->state++];
629 state->itemsPtr = objects;
630 state->mutationsPtr = (unsigned long *) self;
636 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
637 size_t length([self length] - state->state);
640 else if (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;
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;
659 @implementation NSString (Cydia)
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];
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];
671 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
672 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
675 - (NSComparisonResult) compareByPath:(NSString *)other {
676 NSString *prefix = [self commonPrefixWithString:other options:0];
677 size_t length = [prefix length];
679 NSRange lrange = NSMakeRange(length, [self length] - length);
680 NSRange rrange = NSMakeRange(length, [other length] - length);
682 lrange = [self rangeOfString:@"/" options:0 range:lrange];
683 rrange = [other rangeOfString:@"/" options:0 range:rrange];
685 NSComparisonResult value;
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;
694 value = NSOrderedSame;
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)];
701 NSComparisonResult result = [lpath compare:rpath];
702 return result == NSOrderedSame ? value : result;
705 - (NSString *) stringByCachingURLWithCurrentCDN {
707 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
708 withString:@"://cache.cydia.saurik.com/"
712 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
713 return [(id)CFURLCreateStringByAddingPercentEscapes(
718 kCFStringEncodingUTF8
725 /* C++ NSString Wrapper Cache {{{ */
732 _finline void clear_() {
733 if (cache_ != NULL) {
740 _finline bool empty() const {
744 _finline size_t size() const {
748 _finline char *data() const {
752 _finline void clear() {
757 _finline CYString() :
764 _finline ~CYString() {
768 void operator =(const CYString &rhs) {
772 if (rhs.cache_ == nil)
775 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
778 void set(apr_pool_t *pool, const char *data, size_t size) {
784 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
785 memcpy(temp, data, size);
792 _finline void set(apr_pool_t *pool, const char *data) {
793 set(pool, data, data == NULL ? 0 : strlen(data));
796 _finline void set(apr_pool_t *pool, const std::string &rhs) {
797 set(pool, rhs.data(), rhs.size());
800 bool operator ==(const CYString &rhs) const {
801 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
804 operator CFStringRef() {
805 if (cache_ == NULL) {
808 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
810 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
814 _finline operator id() {
815 return (NSString *) static_cast<CFStringRef>(*this);
819 /* C++ NSString Algorithm Adapters {{{ */
821 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
824 struct NSStringMapHash :
825 std::unary_function<NSString *, size_t>
827 _finline size_t operator ()(NSString *value) const {
828 return CFStringHashNSString((CFStringRef) value);
832 struct NSStringMapLess :
833 std::binary_function<NSString *, NSString *, bool>
835 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
836 return [lhs compare:rhs] == NSOrderedAscending;
840 struct NSStringMapEqual :
841 std::binary_function<NSString *, NSString *, bool>
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];
851 /* Perl-Compatible RegEx {{{ */
861 Pcre(const char *regex) :
866 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
869 lprintf("%d:%s\n", offset, error);
873 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
874 matches_ = new int[(capture_ + 1) * 3];
882 NSString *operator [](size_t match) {
883 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
886 bool operator ()(NSString *data) {
887 // XXX: length is for characters, not for bytes
888 return operator ()([data UTF8String], [data length]);
891 bool operator ()(const char *data, size_t size) {
893 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
897 /* Mime Addresses {{{ */
898 @interface Address : NSObject {
904 - (NSString *) address;
906 - (void) setAddress:(NSString *)address;
908 + (Address *) addressWithString:(NSString *)string;
909 - (Address *) initWithString:(NSString *)string;
912 @implementation Address
921 - (NSString *) name {
925 - (NSString *) address {
929 - (void) setAddress:(NSString *)address {
931 [address_ autorelease];
935 address_ = [address retain];
938 + (Address *) addressWithString:(NSString *)string {
939 return [[[Address alloc] initWithString:string] autorelease];
942 + (NSArray *) _attributeKeys {
943 return [NSArray arrayWithObjects:@"address", @"name", nil];
946 - (NSArray *) attributeKeys {
947 return [[self class] _attributeKeys];
950 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
951 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
954 - (Address *) initWithString:(NSString *)string {
955 if ((self = [super init]) != nil) {
956 const char *data = [string UTF8String];
957 size_t size = [string length];
959 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
961 if (address_r(data, size)) {
962 name_ = [address_r[1] retain];
963 address_ = [address_r[2] retain];
965 name_ = [string retain];
973 /* CoreGraphics Primitives {{{ */
984 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
987 Set(space, red, green, blue, alpha);
992 CGColorRelease(color_);
999 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1001 float color[] = {red, green, blue, alpha};
1002 color_ = CGColorCreate(space, (CGFloat *) color);
1005 operator CGColorRef() {
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;
1018 static NSArray *Finishes_;
1020 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1021 #define NotifyConfig_ "/etc/notify.conf"
1023 static bool Queuing_;
1025 static CYColor Blue_;
1026 static CYColor Blueish_;
1027 static CYColor Black_;
1028 static CYColor Off_;
1029 static CYColor White_;
1030 static CYColor Gray_;
1031 static CYColor Green_;
1032 static CYColor Purple_;
1033 static CYColor Purplish_;
1035 static UIColor *InstallingColor_;
1036 static UIColor *RemovingColor_;
1038 static NSString *App_;
1039 static NSString *Home_;
1041 static BOOL Advanced_;
1042 static BOOL Ignored_;
1044 static UIFont *Font12_;
1045 static UIFont *Font12Bold_;
1046 static UIFont *Font14_;
1047 static UIFont *Font18Bold_;
1048 static UIFont *Font22Bold_;
1050 static const char *Machine_ = NULL;
1051 static NSString *System_ = nil;
1052 static NSString *SerialNumber_ = nil;
1053 static NSString *ChipID_ = nil;
1054 static NSString *Token_ = nil;
1055 static NSString *UniqueID_ = nil;
1056 static NSString *Build_ = nil;
1057 static NSString *Product_ = nil;
1058 static NSString *Safari_ = nil;
1060 static CFLocaleRef Locale_;
1061 static NSArray *Languages_;
1062 static CGColorSpaceRef space_;
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_;
1074 static bool IsWildcat_;
1077 /* Display Helpers {{{ */
1078 inline float Interpolate(float begin, float end, float fraction) {
1079 return (end - begin) * fraction + begin;
1082 /* XXX: localize this! */
1083 NSString *SizeString(double size) {
1084 bool negative = size < 0;
1089 while (size > 1024) {
1094 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1096 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1099 static _finline CFStringRef CFCString(const char *value) {
1100 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1103 const char *StripVersion_(const char *version) {
1104 const char *colon(strchr(version, ':'));
1106 version = colon + 1;
1110 CFStringRef StripVersion(const char *version) {
1111 const char *colon(strchr(version, ':'));
1113 version = colon + 1;
1114 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1116 return CFCString(version);
1119 NSString *LocalizeSection(NSString *section) {
1120 static Pcre title_r("^(.*?) \\((.*)\\)$");
1121 if (title_r(section)) {
1122 NSString *parent(title_r[1]);
1123 NSString *child(title_r[2]);
1125 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1126 LocalizeSection(parent),
1127 LocalizeSection(child)
1131 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1134 NSString *Simplify(NSString *title) {
1135 const char *data = [title UTF8String];
1136 size_t size = [title length];
1138 static Pcre square_r("^\\[(.*)\\]$");
1139 if (square_r(data, size))
1140 return Simplify(square_r[1]);
1142 static Pcre paren_r("^\\((.*)\\)$");
1143 if (paren_r(data, size))
1144 return Simplify(paren_r[1]);
1146 static Pcre title_r("^(.*?) \\((.*)\\)$");
1147 if (title_r(data, size))
1148 return Simplify(title_r[1]);
1154 NSString *GetLastUpdate() {
1155 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1158 return UCLocalize("NEVER_OR_UNKNOWN");
1160 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1161 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1163 CFRelease(formatter);
1165 return [(NSString *) formatted autorelease];
1168 bool isSectionVisible(NSString *section) {
1169 NSDictionary *metadata([Sections_ objectForKey:section]);
1170 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1171 return hidden == nil || ![hidden boolValue];
1176 /* Delegate Prototypes {{{ */
1180 @interface NSObject (ProgressDelegate)
1183 @protocol ProgressDelegate
1184 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1185 - (void) setProgressTitle:(NSString *)title;
1186 - (void) setProgressPercent:(float)percent;
1187 - (void) startProgress;
1188 - (void) addProgressOutput:(NSString *)output;
1189 - (bool) isCancelling:(size_t)received;
1192 @protocol ConfigurationDelegate
1193 - (void) repairWithSelector:(SEL)selector;
1194 - (void) setConfigurationData:(NSString *)data;
1197 @class PackageController;
1199 @protocol CydiaDelegate
1200 - (void) setPackageController:(PackageController *)view;
1201 - (void) clearPackage:(Package *)package;
1202 - (void) installPackage:(Package *)package;
1203 - (void) installPackages:(NSArray *)packages;
1204 - (void) removePackage:(Package *)package;
1205 - (void) beginUpdate;
1207 - (void) distUpgrade;
1209 - (void) updateData;
1211 - (void) showSettings;
1212 - (UIProgressHUD *) addProgressHUD;
1213 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1214 - (CYViewController *) pageForPackage:(NSString *)name;
1215 - (PackageController *) packageController;
1216 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1220 /* Status Delegation {{{ */
1222 public pkgAcquireStatus
1225 _transient NSObject<ProgressDelegate> *delegate_;
1233 void setDelegate(id delegate) {
1234 delegate_ = delegate;
1237 NSObject<ProgressDelegate> *getDelegate() const {
1241 virtual bool MediaChange(std::string media, std::string drive) {
1245 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1248 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1249 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1250 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1253 virtual void Done(pkgAcquire::ItemDesc &item) {
1256 virtual void Fail(pkgAcquire::ItemDesc &item) {
1258 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1259 item.Owner->Status == pkgAcquire::Item::StatDone
1263 std::string &error(item.Owner->ErrorText);
1267 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1268 NSArray *fields([description componentsSeparatedByString:@" "]);
1269 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1271 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1272 withObject:[NSArray arrayWithObjects:
1273 [NSString stringWithUTF8String:error.c_str()],
1280 virtual bool Pulse(pkgAcquire *Owner) {
1281 bool value = pkgAcquireStatus::Pulse(Owner);
1284 double(CurrentBytes + CurrentItems) /
1285 double(TotalBytes + TotalItems)
1288 [delegate_ setProgressPercent:percent];
1289 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1292 virtual void Start() {
1293 [delegate_ startProgress];
1296 virtual void Stop() {
1300 /* Progress Delegation {{{ */
1305 _transient id<ProgressDelegate> delegate_;
1309 virtual void Update() {
1310 /*if (abs(Percent - percent_) > 2)
1311 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1315 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1316 [delegate_ setProgressPercent:(Percent / 100)];*/
1326 void setDelegate(id delegate) {
1327 delegate_ = delegate;
1330 id getDelegate() const {
1334 virtual void Done() {
1336 //[delegate_ setProgressPercent:1];
1341 /* Database Interface {{{ */
1342 typedef std::map< unsigned long, _H<Source> > SourceMap;
1344 @interface Database : NSObject {
1350 pkgCacheFile cache_;
1351 pkgDepCache::Policy *policy_;
1352 pkgRecords *records_;
1353 pkgProblemResolver *resolver_;
1354 pkgAcquire *fetcher_;
1356 SPtr<pkgPackageManager> manager_;
1357 pkgSourceList *list_;
1360 NSMutableArray *packages_;
1362 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1371 + (Database *) sharedInstance;
1374 - (void) _readCydia:(NSNumber *)fd;
1375 - (void) _readStatus:(NSNumber *)fd;
1376 - (void) _readOutput:(NSNumber *)fd;
1380 - (Package *) packageWithName:(NSString *)name;
1382 - (pkgCacheFile &) cache;
1383 - (pkgDepCache::Policy *) policy;
1384 - (pkgRecords *) records;
1385 - (pkgProblemResolver *) resolver;
1386 - (pkgAcquire &) fetcher;
1387 - (pkgSourceList &) list;
1388 - (NSArray *) packages;
1389 - (NSArray *) sources;
1390 - (void) reloadData;
1398 - (void) setVisible;
1400 - (void) updateWithStatus:(Status &)status;
1402 - (void) setDelegate:(id)delegate;
1403 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1406 /* Delegate Helpers {{{ */
1407 @implementation NSObject (ProgressDelegate)
1409 - (void) _setProgressErrorPackage:(NSArray *)args {
1410 [self performSelector:@selector(setProgressError:forPackage:)
1411 withObject:[args objectAtIndex:0]
1412 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1416 - (void) _setProgressErrorTitle:(NSArray *)args {
1417 [self performSelector:@selector(setProgressError:withTitle:)
1418 withObject:[args objectAtIndex:0]
1419 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1423 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1424 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1425 withObject:[NSArray arrayWithObjects:error, title, nil]
1430 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1431 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1433 [self performSelector:@selector(setProgressError:withTitle:)
1435 withObject:(package == nil ? id : [package name])
1442 /* Source Class {{{ */
1443 @interface Source : NSObject {
1444 CYString depiction_;
1445 CYString description_;
1451 CYString distribution_;
1456 NSString *authority_;
1458 CYString defaultIcon_;
1460 NSDictionary *record_;
1464 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1466 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1468 - (NSString *) depictionForPackage:(NSString *)package;
1469 - (NSString *) supportForPackage:(NSString *)package;
1471 - (NSDictionary *) record;
1475 - (NSString *) distribution;
1476 - (NSString *) type;
1478 - (NSString *) host;
1480 - (NSString *) name;
1481 - (NSString *) description;
1482 - (NSString *) label;
1483 - (NSString *) origin;
1484 - (NSString *) version;
1486 - (NSString *) defaultIcon;
1490 @implementation Source
1494 distribution_.clear();
1497 description_.clear();
1503 defaultIcon_.clear();
1505 if (record_ != nil) {
1515 if (authority_ != nil) {
1516 [authority_ release];
1526 + (NSArray *) _attributeKeys {
1527 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1530 - (NSArray *) attributeKeys {
1531 return [[self class] _attributeKeys];
1534 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1535 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1538 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1541 trusted_ = index->IsTrusted();
1543 uri_.set(pool, index->GetURI());
1544 distribution_.set(pool, index->GetDist());
1545 type_.set(pool, index->GetType());
1547 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1548 if (dindex != NULL) {
1550 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1553 pkgTagFile tags(&fd);
1555 pkgTagSection section;
1562 {"default-icon", &defaultIcon_},
1563 {"depiction", &depiction_},
1564 {"description", &description_},
1566 {"origin", &origin_},
1567 {"support", &support_},
1568 {"version", &version_},
1571 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1572 const char *start, *end;
1574 if (section.Find(names[i].name_, start, end)) {
1575 CYString &value(*names[i].value_);
1576 value.set(pool, start, end - start);
1582 record_ = [Sources_ objectForKey:[self key]];
1584 record_ = [record_ retain];
1586 NSURL *url([NSURL URLWithString:uri_]);
1590 host_ = [[host_ lowercaseString] retain];
1595 authority_ = [url path];
1597 if (authority_ != nil)
1598 authority_ = [authority_ retain];
1601 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1602 if ((self = [super init]) != nil) {
1603 [self setMetaIndex:index inPool:pool];
1607 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1608 NSDictionary *lhr = [self record];
1609 NSDictionary *rhr = [source record];
1612 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1614 NSString *lhs = [self name];
1615 NSString *rhs = [source name];
1617 if ([lhs length] != 0 && [rhs length] != 0) {
1618 unichar lhc = [lhs characterAtIndex:0];
1619 unichar rhc = [rhs characterAtIndex:0];
1621 if (isalpha(lhc) && !isalpha(rhc))
1622 return NSOrderedAscending;
1623 else if (!isalpha(lhc) && isalpha(rhc))
1624 return NSOrderedDescending;
1627 return [lhs compare:rhs options:LaxCompareOptions_];
1630 - (NSString *) depictionForPackage:(NSString *)package {
1631 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1634 - (NSString *) supportForPackage:(NSString *)package {
1635 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1638 - (NSDictionary *) record {
1646 - (NSString *) uri {
1650 - (NSString *) distribution {
1651 return distribution_;
1654 - (NSString *) type {
1658 - (NSString *) key {
1659 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1662 - (NSString *) host {
1666 - (NSString *) name {
1667 return origin_.empty() ? authority_ : origin_;
1670 - (NSString *) description {
1671 return description_;
1674 - (NSString *) label {
1675 return label_.empty() ? authority_ : label_;
1678 - (NSString *) origin {
1682 - (NSString *) version {
1686 - (NSString *) defaultIcon {
1687 return defaultIcon_;
1692 /* Relationship Class {{{ */
1693 @interface Relationship : NSObject {
1698 - (NSString *) type;
1700 - (NSString *) name;
1704 @implementation Relationship
1712 - (NSString *) type {
1720 - (NSString *) name {
1727 /* Package Class {{{ */
1728 @interface Package : NSObject {
1732 pkgCache::VerIterator version_;
1733 pkgCache::PkgIterator iterator_;
1734 _transient Database *database_;
1735 pkgCache::VerFileIterator file_;
1742 NSString *section$_;
1749 CYString installed_;
1755 CYString depiction_;
1766 NSMutableArray *tags_;
1769 NSArray *relationships_;
1771 NSMutableDictionary *metadata_;
1772 _transient NSDate *firstSeen_;
1773 _transient NSDate *lastSeen_;
1777 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1778 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1780 - (pkgCache::PkgIterator) iterator;
1783 - (NSString *) section;
1784 - (NSString *) simpleSection;
1786 - (NSString *) longSection;
1787 - (NSString *) shortSection;
1791 - (Address *) maintainer;
1793 - (NSString *) longDescription;
1794 - (NSString *) shortDescription;
1797 - (NSMutableDictionary *) metadata;
1799 - (BOOL) subscribed;
1802 - (NSString *) latest;
1803 - (NSString *) installed;
1804 - (BOOL) uninstalled;
1807 - (BOOL) upgradableAndEssential:(BOOL)essential;
1810 - (BOOL) unfiltered;
1814 - (BOOL) halfConfigured;
1815 - (BOOL) halfInstalled;
1817 - (NSString *) mode;
1819 - (void) setVisible;
1822 - (NSString *) name;
1824 - (NSString *) homepage;
1825 - (NSString *) depiction;
1826 - (Address *) author;
1828 - (NSString *) support;
1830 - (NSArray *) files;
1831 - (NSArray *) relationships;
1832 - (NSArray *) warnings;
1833 - (NSArray *) applications;
1835 - (Source *) source;
1836 - (NSString *) role;
1838 - (BOOL) matches:(NSString *)text;
1840 - (bool) hasSupportingRole;
1841 - (BOOL) hasTag:(NSString *)tag;
1842 - (NSString *) primaryPurpose;
1843 - (NSArray *) purposes;
1844 - (bool) isCommercial;
1846 - (CYString &) cyname;
1848 - (uint32_t) compareBySection:(NSArray *)sections;
1850 - (uint32_t) compareForChanges;
1855 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1856 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1857 - (bool) isInstalledAndVisible:(NSNumber *)number;
1858 - (bool) isVisibleInSection:(NSString *)section;
1859 - (bool) isVisibleInSource:(Source *)source;
1863 uint32_t PackageChangesRadix(Package *self, void *) {
1868 uint32_t timestamp : 30;
1869 uint32_t ignored : 1;
1870 uint32_t upgradable : 1;
1874 bool upgradable([self upgradableAndEssential:YES]);
1875 value.bits.upgradable = upgradable ? 1 : 0;
1878 value.bits.timestamp = 0;
1879 value.bits.ignored = [self ignored] ? 0 : 1;
1880 value.bits.upgradable = 1;
1882 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1883 value.bits.ignored = 0;
1884 value.bits.upgradable = 0;
1887 return _not(uint32_t) - value.key;
1890 _finline static void Stifle(uint8_t &value) {
1893 uint32_t PackagePrefixRadix(Package *self, void *context) {
1894 size_t offset(reinterpret_cast<size_t>(context));
1895 CYString &name([self cyname]);
1897 size_t size(name.size());
1900 char *text(name.data());
1903 if (!isdigit(text[0]))
1907 while (size != digits && isdigit(text[digits]))
1917 if (offset == 0 && zeros != 0) {
1918 memset(data, '0', zeros);
1919 memcpy(data + zeros, text, 4 - zeros);
1921 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1922 if (size <= offset - zeros)
1925 text += offset - zeros;
1926 size -= offset - zeros;
1929 memcpy(data, text, 4);
1931 memcpy(data, text, size);
1932 memset(data + size, 0, 4 - size);
1935 for (size_t i(0); i != 4; ++i)
1936 if (isalpha(data[i]))
1941 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1943 /* XXX: ntohl may be more honest */
1944 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1947 CYString &(*PackageName)(Package *self, SEL sel);
1949 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1950 _profile(PackageNameCompare)
1951 CYString &lhi(PackageName(lhs, @selector(cyname)));
1952 CYString &rhi(PackageName(rhs, @selector(cyname)));
1953 CFStringRef lhn(lhi), rhn(rhi);
1956 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1957 else if (rhn == NULL)
1958 return NSOrderedDescending;
1960 _profile(PackageNameCompare$NumbersLast)
1961 if (!lhi.empty() && !rhi.empty()) {
1962 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1963 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1964 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1965 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1966 return lha ? NSOrderedAscending : NSOrderedDescending;
1970 CFIndex length = CFStringGetLength(lhn);
1972 _profile(PackageNameCompare$Compare)
1973 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1978 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1979 return PackageNameCompare(*lhs, *rhs, context);
1982 struct PackageNameOrdering :
1983 std::binary_function<Package *, Package *, bool>
1985 _finline bool operator ()(Package *lhs, Package *rhs) const {
1986 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1990 @implementation Package
1992 - (NSString *) description {
1993 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1999 if (section$_ != nil)
2000 [section$_ release];
2005 if (sponsor$_ != nil)
2006 [sponsor$_ release];
2007 if (author$_ != nil)
2014 if (relationships_ != nil)
2015 [relationships_ release];
2016 if (metadata_ != nil)
2017 [metadata_ release];
2022 + (NSString *) webScriptNameForSelector:(SEL)selector {
2023 if (selector == @selector(hasTag:))
2029 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2030 return [self webScriptNameForSelector:selector] == nil;
2033 + (NSArray *) _attributeKeys {
2034 return [NSArray arrayWithObjects:@"applications", @"author", @"depiction", @"longDescription", @"essential", @"homepage", @"icon", @"id", @"installed", @"latest", @"longSection", @"maintainer", @"mode", @"name", @"purposes", @"section", @"shortDescription", @"shortSection", @"simpleSection", @"size", @"source", @"sponsor", @"support", @"warnings", nil];
2037 - (NSArray *) attributeKeys {
2038 return [[self class] _attributeKeys];
2041 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2042 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2052 _profile(Package$parse)
2053 pkgRecords::Parser *parser;
2055 _profile(Package$parse$Lookup)
2056 parser = &[database_ records]->Lookup(file_);
2061 _profile(Package$parse$Find)
2067 {"depiction", &depiction_},
2068 {"homepage", &homepage_},
2069 {"website", &website},
2071 {"support", &support_},
2072 {"sponsor", &sponsor_},
2073 {"author", &author_},
2076 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2077 const char *start, *end;
2079 if (parser->Find(names[i].name_, start, end)) {
2080 CYString &value(*names[i].value_);
2081 _profile(Package$parse$Value)
2082 value.set(pool_, start, end - start);
2088 _profile(Package$parse$Tagline)
2089 const char *start, *end;
2090 if (parser->ShortDesc(start, end)) {
2091 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2094 while (stop != start && stop[-1] == '\r')
2096 tagline_.set(pool_, start, stop - start);
2100 _profile(Package$parse$Retain)
2101 if (homepage_.empty())
2102 homepage_ = website;
2103 if (homepage_ == depiction_)
2109 - (void) setVisible {
2110 visible_ = required_ && [self unfiltered];
2113 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2114 if ((self = [super init]) != nil) {
2115 _profile(Package$initWithVersion)
2116 @synchronized (database) {
2117 era_ = [database era];
2121 iterator_ = version.ParentPkg();
2122 database_ = database;
2124 _profile(Package$initWithVersion$Latest)
2125 latest_ = (NSString *) StripVersion(version_.VerStr());
2128 pkgCache::VerIterator current;
2129 _profile(Package$initWithVersion$Versions)
2130 current = iterator_.CurrentVer();
2132 installed_.set(pool_, StripVersion_(current.VerStr()));
2134 if (!version_.end())
2135 file_ = version_.FileList();
2137 pkgCache &cache([database_ cache]);
2138 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2142 _profile(Package$initWithVersion$Name)
2143 id_.set(pool_, iterator_.Name());
2144 name_.set(pool, iterator_.Display());
2148 _profile(Package$initWithVersion$Source)
2149 source_ = [database_ getSource:file_.File()];
2158 _profile(Package$initWithVersion$Tags)
2159 pkgCache::TagIterator tag(iterator_.TagList());
2161 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2163 const char *name(tag.Name());
2164 [tags_ addObject:(NSString *)CFCString(name)];
2165 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2166 role_ = (NSString *) CFCString(name + 6);
2167 if (required_ && strncmp(name, "require::", 9) == 0 && (
2172 } while (!tag.end());
2176 bool changed(false);
2177 NSString *key([static_cast<id>(id_) lowercaseString]);
2179 _profile(Package$initWithVersion$Metadata)
2180 metadata_ = [Packages_ objectForKey:key];
2182 if (metadata_ == nil) {
2185 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2186 firstSeen_, @"FirstSeen",
2187 latest_, @"LastVersion",
2192 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2193 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2195 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2196 subscribed_ = [subscribed boolValue];
2198 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2200 if (firstSeen_ == nil) {
2201 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2202 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2206 if (version == nil) {
2207 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2209 } else if (![version isEqualToString:latest_]) {
2210 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2212 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2217 metadata_ = [metadata_ retain];
2220 [Packages_ setObject:metadata_ forKey:key];
2225 _profile(Package$initWithVersion$Section)
2226 section_.set(pool_, iterator_.Section());
2229 obsolete_ = [self hasTag:@"cydia::obsolete"];
2230 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2232 } _end } return self;
2235 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2236 @synchronized ([Database class]) {
2237 pkgCache::VerIterator version;
2239 _profile(Package$packageWithIterator$GetCandidateVer)
2240 version = [database policy]->GetCandidateVer(iterator);
2246 return [[[Package alloc]
2247 initWithVersion:version
2254 - (pkgCache::PkgIterator) iterator {
2258 - (NSString *) section {
2259 if (section$_ == nil) {
2260 if (section_.empty())
2263 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2264 NSString *name(section_);
2267 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2268 if (NSString *rename = [value objectForKey:@"Rename"]) {
2273 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2277 - (NSString *) simpleSection {
2278 if (NSString *section = [self section])
2279 return Simplify(section);
2284 - (NSString *) longSection {
2285 return LocalizeSection([self section]);
2288 - (NSString *) shortSection {
2289 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2292 - (NSString *) uri {
2295 pkgIndexFile *index;
2296 pkgCache::PkgFileIterator file(file_.File());
2297 if (![database_ list].FindIndex(file, index))
2299 return [NSString stringWithUTF8String:iterator_->Path];
2300 //return [NSString stringWithUTF8String:file.Site()];
2301 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2305 - (Address *) maintainer {
2308 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2309 const std::string &maintainer(parser->Maintainer());
2310 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2314 return version_.end() ? 0 : version_->InstalledSize;
2317 - (NSString *) longDescription {
2320 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2321 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2323 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2324 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2325 if ([lines count] < 2)
2328 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2329 for (size_t i(1), e([lines count]); i != e; ++i) {
2330 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2331 [trimmed addObject:trim];
2334 return [trimmed componentsJoinedByString:@"\n"];
2337 - (NSString *) shortDescription {
2342 _profile(Package$index)
2343 CFStringRef name((CFStringRef) [self name]);
2344 if (CFStringGetLength(name) == 0)
2346 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2347 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2349 return toupper(character);
2353 - (NSMutableDictionary *) metadata {
2358 if (subscribed_ && lastSeen_ != nil)
2363 - (BOOL) subscribed {
2368 NSDictionary *metadata([self metadata]);
2369 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2370 return [ignored boolValue];
2375 - (NSString *) latest {
2379 - (NSString *) installed {
2383 - (BOOL) uninstalled {
2384 return installed_.empty();
2388 return !version_.end();
2391 - (BOOL) upgradableAndEssential:(BOOL)essential {
2392 _profile(Package$upgradableAndEssential)
2393 pkgCache::VerIterator current(iterator_.CurrentVer());
2395 return essential && essential_ && visible_;
2397 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2401 - (BOOL) essential {
2406 return [database_ cache][iterator_].InstBroken();
2409 - (BOOL) unfiltered {
2410 NSString *section([self section]);
2411 return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
2419 unsigned char current(iterator_->CurrentState);
2420 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2423 - (BOOL) halfConfigured {
2424 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2427 - (BOOL) halfInstalled {
2428 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2432 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2433 return state.Mode != pkgDepCache::ModeKeep;
2436 - (NSString *) mode {
2437 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2439 switch (state.Mode) {
2440 case pkgDepCache::ModeDelete:
2441 if ((state.iFlags & pkgDepCache::Purge) != 0)
2445 case pkgDepCache::ModeKeep:
2446 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2447 return @"REINSTALL";
2448 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2452 case pkgDepCache::ModeInstall:
2453 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2454 return @"REINSTALL";
2455 else*/ switch (state.Status) {
2457 return @"DOWNGRADE";
2463 return @"NEW_INSTALL";
2474 - (NSString *) name {
2475 return name_.empty() ? id_ : name_;
2478 - (UIImage *) icon {
2479 NSString *section = [self simpleSection];
2483 if ([static_cast<id>(icon_) hasPrefix:@"file:///"])
2484 // XXX: correct escaping
2485 icon = [UIImage imageAtPath:[static_cast<id>(icon_) substringFromIndex:7]];
2486 if (icon == nil) if (section != nil)
2487 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2488 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2489 if ([dicon hasPrefix:@"file:///"])
2490 // XXX: correct escaping
2491 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2493 icon = [UIImage applicationImageNamed:@"unknown.png"];
2497 - (NSString *) homepage {
2501 - (NSString *) depiction {
2502 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2505 - (Address *) sponsor {
2506 if (sponsor$_ == nil) {
2507 if (sponsor_.empty())
2509 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2513 - (Address *) author {
2514 if (author$_ == nil) {
2515 if (author_.empty())
2517 author$_ = [[Address addressWithString:author_] retain];
2521 - (NSString *) support {
2522 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2525 - (NSArray *) files {
2526 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2527 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2530 fin.open([path UTF8String]);
2535 while (std::getline(fin, line))
2536 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2541 - (NSArray *) relationships {
2542 return relationships_;
2545 - (NSArray *) warnings {
2546 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2547 const char *name(iterator_.Name());
2549 size_t length(strlen(name));
2550 if (length < 2) invalid:
2551 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2552 else for (size_t i(0); i != length; ++i)
2554 /* XXX: technically this is not allowed */
2555 (name[i] < 'A' || name[i] > 'Z') &&
2556 (name[i] < 'a' || name[i] > 'z') &&
2557 (name[i] < '0' || name[i] > '9') &&
2558 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2561 if (strcmp(name, "cydia") != 0) {
2564 bool _private = false;
2567 bool repository = [[self section] isEqualToString:@"Repositories"];
2569 if (NSArray *files = [self files])
2570 for (NSString *file in files)
2571 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2573 else if (!user && [file isEqualToString:@"/User"])
2575 else if (!_private && [file isEqualToString:@"/private"])
2577 else if (!stash && [file isEqualToString:@"/var/stash"])
2580 /* XXX: this is not sensitive enough. only some folders are valid. */
2581 if (cydia && !repository)
2582 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2584 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2586 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2588 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2591 return [warnings count] == 0 ? nil : warnings;
2594 - (NSArray *) applications {
2595 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2597 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2599 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2600 if (NSArray *files = [self files])
2601 for (NSString *file in files)
2602 if (application_r(file)) {
2603 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2604 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2605 if ([id isEqualToString:me])
2608 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2610 display = application_r[1];
2612 NSString *bundle([file stringByDeletingLastPathComponent]);
2613 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2614 if (icon == nil || [icon length] == 0)
2616 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2618 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2619 [applications addObject:application];
2621 [application addObject:id];
2622 [application addObject:display];
2623 [application addObject:url];
2626 return [applications count] == 0 ? nil : applications;
2629 - (Source *) source {
2631 @synchronized (database_) {
2632 if ([database_ era] != era_ || file_.end())
2635 source_ = [database_ getSource:file_.File()];
2647 - (NSString *) role {
2651 - (BOOL) matches:(NSString *)text {
2657 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2658 if (range.location != NSNotFound)
2661 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2662 if (range.location != NSNotFound)
2665 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2666 if (range.location != NSNotFound)
2672 - (bool) hasSupportingRole {
2675 if ([role_ isEqualToString:@"enduser"])
2677 if ([Role_ isEqualToString:@"User"])
2679 if ([role_ isEqualToString:@"hacker"])
2681 if ([Role_ isEqualToString:@"Hacker"])
2683 if ([role_ isEqualToString:@"developer"])
2685 if ([Role_ isEqualToString:@"Developer"])
2690 - (BOOL) hasTag:(NSString *)tag {
2691 return tags_ == nil ? NO : [tags_ containsObject:tag];
2694 - (NSString *) primaryPurpose {
2695 for (NSString *tag in tags_)
2696 if ([tag hasPrefix:@"purpose::"])
2697 return [tag substringFromIndex:9];
2701 - (NSArray *) purposes {
2702 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2703 for (NSString *tag in tags_)
2704 if ([tag hasPrefix:@"purpose::"])
2705 [purposes addObject:[tag substringFromIndex:9]];
2706 return [purposes count] == 0 ? nil : purposes;
2709 - (bool) isCommercial {
2710 return [self hasTag:@"cydia::commercial"];
2713 - (CYString &) cyname {
2714 return name_.empty() ? id_ : name_;
2717 - (uint32_t) compareBySection:(NSArray *)sections {
2718 NSString *section([self section]);
2719 for (size_t i(0), e([sections count]); i != e; ++i) {
2720 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2724 return _not(uint32_t);
2727 - (uint32_t) compareForChanges {
2732 uint32_t timestamp : 30;
2733 uint32_t ignored : 1;
2734 uint32_t upgradable : 1;
2738 bool upgradable([self upgradableAndEssential:YES]);
2739 value.bits.upgradable = upgradable ? 1 : 0;
2742 value.bits.timestamp = 0;
2743 value.bits.ignored = [self ignored] ? 0 : 1;
2744 value.bits.upgradable = 1;
2746 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2747 value.bits.ignored = 0;
2748 value.bits.upgradable = 0;
2751 return _not(uint32_t) - value.key;
2755 pkgProblemResolver *resolver = [database_ resolver];
2756 resolver->Clear(iterator_);
2757 resolver->Protect(iterator_);
2761 pkgProblemResolver *resolver = [database_ resolver];
2762 resolver->Clear(iterator_);
2763 resolver->Protect(iterator_);
2764 pkgCacheFile &cache([database_ cache]);
2765 cache->MarkInstall(iterator_, false);
2766 pkgDepCache::StateCache &state((*cache)[iterator_]);
2767 if (!state.Install())
2768 cache->SetReInstall(iterator_, true);
2772 pkgProblemResolver *resolver = [database_ resolver];
2773 resolver->Clear(iterator_);
2774 resolver->Protect(iterator_);
2775 resolver->Remove(iterator_);
2776 [database_ cache]->MarkDelete(iterator_, true);
2779 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2780 _profile(Package$isUnfilteredAndSearchedForBy)
2783 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2784 value &= [self unfiltered];
2787 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2788 value &= [self matches:search];
2795 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2796 if ([search length] == 0)
2799 _profile(Package$isUnfilteredAndSelectedForBy)
2802 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2803 value &= [self unfiltered];
2806 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2807 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2814 - (bool) isInstalledAndVisible:(NSNumber *)number {
2815 return (![number boolValue] || [self visible]) && ![self uninstalled];
2818 - (bool) isVisibleInSection:(NSString *)name {
2819 NSString *section = [self section];
2824 section == nil && [name length] == 0 ||
2825 [name isEqualToString:section]
2829 - (bool) isVisibleInSource:(Source *)source {
2830 return [self source] == source && [self visible];
2835 /* Section Class {{{ */
2836 @interface Section : NSObject {
2841 NSString *localized_;
2844 - (NSComparisonResult) compareByLocalized:(Section *)section;
2845 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2846 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2847 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2848 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2849 - (NSString *) name;
2856 - (void) addToCount;
2858 - (void) setCount:(size_t)count;
2859 - (NSString *) localized;
2863 @implementation Section
2867 if (localized_ != nil)
2868 [localized_ release];
2872 - (NSComparisonResult) compareByLocalized:(Section *)section {
2873 NSString *lhs(localized_);
2874 NSString *rhs([section localized]);
2876 /*if ([lhs length] != 0 && [rhs length] != 0) {
2877 unichar lhc = [lhs characterAtIndex:0];
2878 unichar rhc = [rhs characterAtIndex:0];
2880 if (isalpha(lhc) && !isalpha(rhc))
2881 return NSOrderedAscending;
2882 else if (!isalpha(lhc) && isalpha(rhc))
2883 return NSOrderedDescending;
2886 return [lhs compare:rhs options:LaxCompareOptions_];
2889 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2890 if ((self = [self initWithName:name localize:NO]) != nil) {
2891 if (localized != nil)
2892 localized_ = [localized retain];
2896 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2897 return [self initWithName:name row:0 localize:localize];
2900 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2901 if ((self = [super init]) != nil) {
2902 name_ = [name retain];
2906 localized_ = [LocalizeSection(name_) retain];
2910 /* XXX: localize the index thingees */
2911 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2912 if ((self = [super init]) != nil) {
2913 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2919 - (NSString *) name {
2939 - (void) addToCount {
2943 - (void) setCount:(size_t)count {
2947 - (NSString *) localized {
2954 static NSString *Colon_;
2955 static NSString *Error_;
2956 static NSString *Warning_;
2958 /* Database Implementation {{{ */
2959 @implementation Database
2961 + (Database *) sharedInstance {
2962 static Database *instance;
2963 if (instance == nil)
2964 instance = [[Database alloc] init];
2974 NSRecycleZone(zone_);
2975 // XXX: malloc_destroy_zone(zone_);
2976 apr_pool_destroy(pool_);
2980 - (void) _readCydia:(NSNumber *)fd { _pooled
2981 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2982 std::istream is(&ib);
2985 static Pcre finish_r("^finish:([^:]*)$");
2987 while (std::getline(is, line)) {
2988 const char *data(line.c_str());
2989 size_t size = line.size();
2990 lprintf("C:%s\n", data);
2992 if (finish_r(data, size)) {
2993 NSString *finish = finish_r[1];
2994 int index = [Finishes_ indexOfObject:finish];
2995 if (index != INT_MAX && index > Finish_)
3003 - (void) _readStatus:(NSNumber *)fd { _pooled
3004 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3005 std::istream is(&ib);
3008 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3009 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3011 while (std::getline(is, line)) {
3012 const char *data(line.c_str());
3013 size_t size(line.size());
3014 lprintf("S:%s\n", data);
3016 if (conffile_r(data, size)) {
3017 [delegate_ setConfigurationData:conffile_r[1]];
3018 } else if (strncmp(data, "status: ", 8) == 0) {
3019 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3020 [delegate_ setProgressTitle:string];
3021 } else if (pmstatus_r(data, size)) {
3022 std::string type([pmstatus_r[1] UTF8String]);
3023 NSString *id = pmstatus_r[2];
3025 float percent([pmstatus_r[3] floatValue]);
3026 [delegate_ setProgressPercent:(percent / 100)];
3028 NSString *string = pmstatus_r[4];
3030 if (type == "pmerror")
3031 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3032 withObject:[NSArray arrayWithObjects:string, id, nil]
3035 else if (type == "pmstatus") {
3036 [delegate_ setProgressTitle:string];
3037 } else if (type == "pmconffile")
3038 [delegate_ setConfigurationData:string];
3040 lprintf("E:unknown pmstatus\n");
3042 lprintf("E:unknown status\n");
3048 - (void) _readOutput:(NSNumber *)fd { _pooled
3049 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3050 std::istream is(&ib);
3053 while (std::getline(is, line)) {
3054 lprintf("O:%s\n", line.c_str());
3055 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3065 - (Package *) packageWithName:(NSString *)name {
3066 @synchronized ([Database class]) {
3067 if (static_cast<pkgDepCache *>(cache_) == NULL)
3069 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3070 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3074 if ((self = [super init]) != nil) {
3081 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3082 apr_pool_create(&pool_, NULL);
3084 packages_ = [[NSMutableArray alloc] init];
3088 _assert(pipe(fds) != -1);
3091 _config->Set("APT::Keep-Fds::", cydiafd_);
3092 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3095 detachNewThreadSelector:@selector(_readCydia:)
3097 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3100 _assert(pipe(fds) != -1);
3104 detachNewThreadSelector:@selector(_readStatus:)
3106 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3109 _assert(pipe(fds) != -1);
3110 _assert(dup2(fds[0], 0) != -1);
3111 _assert(close(fds[0]) != -1);
3113 input_ = fdopen(fds[1], "a");
3115 _assert(pipe(fds) != -1);
3116 _assert(dup2(fds[1], 1) != -1);
3117 _assert(close(fds[1]) != -1);
3120 detachNewThreadSelector:@selector(_readOutput:)
3122 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3127 - (pkgCacheFile &) cache {
3131 - (pkgDepCache::Policy *) policy {
3135 - (pkgRecords *) records {
3139 - (pkgProblemResolver *) resolver {
3143 - (pkgAcquire &) fetcher {
3147 - (pkgSourceList &) list {
3151 - (NSArray *) packages {
3155 - (NSArray *) sources {
3156 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3157 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3158 [sources addObject:i->second];
3162 - (NSArray *) issues {
3163 if (cache_->BrokenCount() == 0)
3166 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3168 for (Package *package in packages_) {
3169 if (![package broken])
3171 pkgCache::PkgIterator pkg([package iterator]);
3173 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3174 [entry addObject:[package name]];
3175 [issues addObject:entry];
3177 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3181 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3182 pkgCache::DepIterator start;
3183 pkgCache::DepIterator end;
3184 dep.GlobOr(start, end); // ++dep
3186 if (!cache_->IsImportantDep(end))
3188 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3191 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3192 [entry addObject:failure];
3193 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3195 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3196 if (Package *package = [self packageWithName:name])
3197 name = [package name];
3198 [failure addObject:name];
3200 pkgCache::PkgIterator target(start.TargetPkg());
3201 if (target->ProvidesList != 0)
3202 [failure addObject:@"?"];
3204 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3206 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3207 else if (!cache_[target].CandidateVerIter(cache_).end())
3208 [failure addObject:@"-"];
3209 else if (target->ProvidesList == 0)
3210 [failure addObject:@"!"];
3212 [failure addObject:@"%"];
3216 if (start.TargetVer() != 0)
3217 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3228 - (bool) popErrorWithTitle:(NSString *)title {
3230 std::string message;
3232 while (!_error->empty()) {
3234 bool warning(!_error->PopMessage(error));
3238 size_t size(error.size());
3239 if (size == 0 || error[size - 1] != '\n')
3241 error.resize(size - 1);
3243 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3245 if (!message.empty())
3250 if (fatal && !message.empty())
3251 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3256 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3257 return [self popErrorWithTitle:title] || !success;
3260 - (void) reloadData { _pooled
3261 @synchronized ([Database class]) {
3262 @synchronized (self) {
3266 [packages_ removeAllObjects];
3292 apr_pool_clear(pool_);
3293 NSRecycleZone(zone_);
3295 int chk(creat("/tmp/cydia.chk", 0644));
3299 NSString *title(UCLocalize("DATABASE"));
3302 if (!cache_.Open(progress_, true)) { pop:
3304 bool warning(!_error->PopMessage(error));
3305 lprintf("cache_.Open():[%s]\n", error.c_str());
3307 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3308 [delegate_ repairWithSelector:@selector(configure)];
3309 else if (error == "The package lists or status file could not be parsed or opened.")
3310 [delegate_ repairWithSelector:@selector(update)];
3311 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3312 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3313 // else if (error == "The list of sources could not be read.")
3315 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3324 unlink("/tmp/cydia.chk");
3326 now_ = [[NSDate date] retain];
3328 policy_ = new pkgDepCache::Policy();
3329 records_ = new pkgRecords(cache_);
3330 resolver_ = new pkgProblemResolver(cache_);
3331 fetcher_ = new pkgAcquire(&status_);
3334 list_ = new pkgSourceList();
3335 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3338 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3339 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3343 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3346 if (cache_->BrokenCount() != 0) {
3347 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3350 if (cache_->BrokenCount() != 0) {
3351 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3355 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3361 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3362 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3363 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3364 // XXX: this could be more intelligent
3365 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3366 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3368 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3375 /*std::vector<Package *> packages;
3376 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3377 [packages_ release];
3382 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3383 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3384 //packages.push_back(package);
3385 [packages_ addObject:package];
3389 /*if (packages.empty())
3390 packages_ = [[NSArray alloc] init];
3392 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3395 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3396 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3397 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3405 /*if (!packages.empty())
3406 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3407 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3409 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3411 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3413 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3419 - (void) configure {
3420 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3421 system([dpkg UTF8String]);
3425 // XXX: I don't remember this condition
3430 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3432 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3434 if ([self popErrorWithTitle:title])
3438 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3441 public pkgArchiveCleaner
3444 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3449 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3456 fetcher_->Shutdown();
3458 pkgRecords records(cache_);
3460 lock_ = new FileFd();
3461 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3463 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3465 if ([self popErrorWithTitle:title])
3469 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3472 manager_ = (_system->CreatePM(cache_));
3473 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3480 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3482 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3484 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3486 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3487 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3490 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3495 bool failed = false;
3496 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3497 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3499 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3502 std::string uri = (*item)->DescURI();
3503 std::string error = (*item)->ErrorText;
3505 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3508 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3509 withObject:[NSArray arrayWithObjects:
3510 [NSString stringWithUTF8String:error.c_str()],
3522 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3524 if (_error->PendingError()) {
3529 if (result == pkgPackageManager::Failed) {
3534 if (result != pkgPackageManager::Completed) {
3539 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3541 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3543 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3544 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3547 if (![before isEqualToArray:after])
3552 NSString *title(UCLocalize("UPGRADE"));
3553 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3559 [self updateWithStatus:status_];
3562 - (void) setVisible {
3563 for (Package *package in packages_)
3564 [package setVisible];
3567 - (void) updateWithStatus:(Status &)status {
3568 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3569 NSString *title(UCLocalize("REFRESHING_DATA"));
3572 if (!list.ReadMainList())
3573 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3576 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3577 if ([self popErrorWithTitle:title])
3580 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3581 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3582 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3584 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3588 - (void) setDelegate:(id)delegate {
3589 delegate_ = delegate;
3590 status_.setDelegate(delegate);
3591 progress_.setDelegate(delegate);
3594 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3595 SourceMap::const_iterator i(sources_.find(file->ID));
3596 return i == sources_.end() ? nil : i->second;
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)
3608 pkgCache::PkgIterator package(dep.TargetPkg());
3611 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3619 /* Web Scripting {{{ */
3620 @interface CydiaObject : NSObject {
3625 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3628 @implementation CydiaObject
3631 [indirect_ release];
3635 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3636 if ((self = [super init]) != nil) {
3637 indirect_ = [indirect retain];
3641 - (void) setDelegate:(id)delegate {
3642 delegate_ = delegate;
3645 + (NSArray *) _attributeKeys {
3646 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3649 - (NSArray *) attributeKeys {
3650 return [[self class] _attributeKeys];
3653 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3654 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3657 - (NSString *) device {
3658 return [[UIDevice currentDevice] uniqueIdentifier];
3661 #if 0 // XXX: implement!
3662 - (NSString *) mac {
3663 if (![indirect_ promptForSensitive:@"Mac Address"])
3667 - (NSString *) serial {
3668 if (![indirect_ promptForSensitive:@"Serial #"])
3672 - (NSString *) firewire {
3673 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3677 - (NSString *) imei {
3678 if (![indirect_ promptForSensitive:@"IMEI"])
3683 + (NSString *) webScriptNameForSelector:(SEL)selector {
3684 if (selector == @selector(close))
3686 else if (selector == @selector(getInstalledPackages))
3687 return @"getInstalledPackages";
3688 else if (selector == @selector(getPackageById:))
3689 return @"getPackageById";
3690 else if (selector == @selector(installPackages:))
3691 return @"installPackages";
3692 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3693 return @"setButtonImage";
3694 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3695 return @"setButtonTitle";
3696 else if (selector == @selector(setPopupHook:))
3697 return @"setPopupHook";
3698 else if (selector == @selector(setSpecial:))
3699 return @"setSpecial";
3700 else if (selector == @selector(setToken:))
3702 else if (selector == @selector(setViewportWidth:))
3703 return @"setViewportWidth";
3704 else if (selector == @selector(supports:))
3706 else if (selector == @selector(stringWithFormat:arguments:))
3708 else if (selector == @selector(localizedStringForKey:value:table:))
3710 else if (selector == @selector(du:))
3712 else if (selector == @selector(statfs:))
3718 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3719 return [self webScriptNameForSelector:selector] == nil;
3722 - (BOOL) supports:(NSString *)feature {
3723 return [feature isEqualToString:@"window.open"];
3726 - (NSArray *) getInstalledPackages {
3727 NSArray *packages([[Database sharedInstance] packages]);
3728 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3729 for (Package *package in packages)
3730 if ([package installed] != nil)
3731 [installed addObject:package];
3735 - (Package *) getPackageById:(NSString *)id {
3736 Package *package([[Database sharedInstance] packageWithName:id]);
3741 - (NSArray *) statfs:(NSString *)path {
3744 if (path == nil || statfs([path UTF8String], &stat) == -1)
3747 return [NSArray arrayWithObjects:
3748 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3749 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3750 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3754 - (NSNumber *) du:(NSString *)path {
3755 NSNumber *value(nil);
3758 _assert(pipe(fds) != -1);
3760 pid_t pid(ExecFork());
3762 _assert(dup2(fds[1], 1) != -1);
3763 _assert(close(fds[0]) != -1);
3764 _assert(close(fds[1]) != -1);
3765 /* XXX: this should probably not use du */
3766 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3771 _assert(close(fds[1]) != -1);
3773 if (FILE *du = fdopen(fds[0], "r")) {
3775 while (fgets(line, sizeof(line), du) != NULL) {
3776 size_t length(strlen(line));
3777 while (length != 0 && line[length - 1] == '\n')
3778 line[--length] = '\0';
3779 if (char *tab = strchr(line, '\t')) {
3781 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3786 } else _assert(close(fds[0]));
3790 if (waitpid(pid, &status, 0) == -1)
3793 else _assert(false);
3802 - (void) installPackages:(NSArray *)packages {
3803 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3806 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3807 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3810 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3811 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3814 - (void) setSpecial:(id)function {
3815 [indirect_ setSpecial:function];
3818 - (void) setToken:(NSString *)token {
3821 Token_ = [token retain];
3823 [Metadata_ setObject:Token_ forKey:@"Token"];
3827 - (void) setPopupHook:(id)function {
3828 [indirect_ setPopupHook:function];
3831 - (void) setViewportWidth:(float)width {
3832 [indirect_ setViewportWidth:width];
3835 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3836 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3837 unsigned count([arguments count]);
3839 for (unsigned i(0); i != count; ++i)
3840 values[i] = [arguments objectAtIndex:i];
3841 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3844 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3845 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3847 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3849 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3855 /* Cydia Browser Controller {{{ */
3856 @interface CYBrowserController : BrowserController {
3857 CydiaObject *cydia_;
3862 @implementation CYBrowserController
3869 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3872 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3873 [super webView:view didClearWindowObject:window forFrame:frame];
3875 WebDataSource *source([frame dataSource]);
3876 NSURLResponse *response([source response]);
3877 NSURL *url([response URL]);
3878 NSString *scheme([url scheme]);
3880 NSHTTPURLResponse *http;
3881 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3882 http = (NSHTTPURLResponse *) response;
3886 NSDictionary *headers([http allHeaderFields]);
3887 NSString *host([url host]);
3888 [self setHeaders:headers forHost:host];
3891 [host isEqualToString:@"cydia.saurik.com"] ||
3892 [host hasSuffix:@".cydia.saurik.com"] ||
3893 [scheme isEqualToString:@"file"]
3895 [window setValue:cydia_ forKey:@"cydia"];
3898 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3899 if (System_ != NULL)
3900 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3901 if (Machine_ != NULL)
3902 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3904 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3906 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3909 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3910 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3911 [self _setMoreHeaders:copy];
3915 - (void) setDelegate:(id)delegate {
3916 [super setDelegate:delegate];
3917 [cydia_ setDelegate:delegate];
3921 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3922 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3924 WebView *webview([[webview_ _documentView] webView]);
3926 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3928 NSString *application = package == nil ? @"Cydia" : [NSString
3929 stringWithFormat:@"Cydia/%@",
3934 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3936 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3937 if (Product_ != nil)
3938 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3940 [webview setApplicationNameForUserAgent:application];
3947 /* Confirmation {{{ */
3948 @protocol ConfirmationControllerDelegate
3949 - (void) cancelAndClear:(bool)clear;
3950 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3954 @interface ConfirmationController : CYBrowserController {
3955 _transient Database *database_;
3956 UIAlertView *essential_;
3963 - (id) initWithDatabase:(Database *)database;
3967 @implementation ConfirmationController
3974 if (essential_ != nil)
3975 [essential_ release];
3979 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3980 NSString *context([alert context]);
3982 if ([context isEqualToString:@"remove"]) {
3983 if (button == [alert cancelButtonIndex]) {
3984 [self dismissModalViewControllerAnimated:YES];
3985 } else if (button == [alert firstOtherButtonIndex]) {
3988 [delegate_ confirmWithNavigationController:[self navigationController]];
3991 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3992 } else if ([context isEqualToString:@"unable"]) {
3993 [self dismissModalViewControllerAnimated:YES];
3994 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3996 [super alertView:alert clickedButtonAtIndex:button];
4000 - (void) _doContinue {
4001 [self dismissModalViewControllerAnimated:YES];
4002 [delegate_ cancelAndClear:NO];
4005 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4006 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4010 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4011 [super webView:view didClearWindowObject:window forFrame:frame];
4012 [window setValue:changes_ forKey:@"changes"];
4013 [window setValue:issues_ forKey:@"issues"];
4014 [window setValue:sizes_ forKey:@"sizes"];
4015 [window setValue:self forKey:@"queue"];
4018 - (id) initWithDatabase:(Database *)database {
4019 if ((self = [super init]) != nil) {
4020 database_ = database;
4022 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4024 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4025 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4026 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4027 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4028 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4032 pkgDepCache::Policy *policy([database_ policy]);
4034 pkgCacheFile &cache([database_ cache]);
4035 NSArray *packages = [database_ packages];
4036 for (Package *package in packages) {
4037 pkgCache::PkgIterator iterator = [package iterator];
4038 pkgDepCache::StateCache &state(cache[iterator]);
4040 NSString *name([package name]);
4042 if (state.NewInstall())
4043 [installing addObject:name];
4044 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4045 [reinstalling addObject:name];
4046 else if (state.Upgrade())
4047 [upgrading addObject:name];
4048 else if (state.Downgrade())
4049 [downgrading addObject:name];
4050 else if (state.Delete()) {
4051 if ([package essential])
4053 [removing addObject:name];
4056 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4057 substrate_ |= DepSubstrate(iterator.CurrentVer());
4062 else if (Advanced_) {
4063 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4065 essential_ = [[UIAlertView alloc]
4066 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4067 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4069 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4070 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4073 [essential_ setContext:@"remove"];
4075 essential_ = [[UIAlertView alloc]
4076 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4077 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4079 cancelButtonTitle:UCLocalize("OKAY")
4080 otherButtonTitles:nil
4083 [essential_ setContext:@"unable"];
4086 changes_ = [[NSArray alloc] initWithObjects:
4094 issues_ = [database_ issues];
4096 issues_ = [issues_ retain];
4098 sizes_ = [[NSArray alloc] initWithObjects:
4099 SizeString([database_ fetcher].FetchNeeded()),
4100 SizeString([database_ fetcher].PartialPresent()),
4103 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4105 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
4106 initWithTitle:UCLocalize("CANCEL")
4107 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4108 style:UIBarButtonItemStylePlain
4110 action:@selector(cancelButtonClicked)
4112 [[self navigationItem] setLeftBarButtonItem:leftItem];
4117 - (void) applyRightButton {
4118 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
4119 initWithTitle:UCLocalize("CONFIRM")
4120 style:UIBarButtonItemStylePlain
4122 action:@selector(confirmButtonClicked)
4124 #if !AlwaysReload && !IgnoreInstall
4125 if (issues_ == nil && ![self isLoading]) [[self navigationItem] setRightBarButtonItem:rightItem];
4126 else [super applyRightButton];
4128 [[self navigationItem] setRightBarButtonItem:nil];
4130 [rightItem release];
4133 - (void) cancelButtonClicked {
4134 [self dismissModalViewControllerAnimated:YES];
4135 [delegate_ cancelAndClear:YES];
4139 - (void) confirmButtonClicked {
4143 if (essential_ != nil)
4148 [delegate_ confirmWithNavigationController:[self navigationController]];
4156 /* Progress Data {{{ */
4157 @interface ProgressData : NSObject {
4163 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4170 @implementation ProgressData
4172 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4173 if ((self = [super init]) != nil) {
4174 selector_ = selector;
4194 /* Progress Controller {{{ */
4195 @interface ProgressController : CYViewController <
4196 ConfigurationDelegate,
4199 _transient Database *database_;
4200 UIProgressBar *progress_;
4201 UITextView *output_;
4202 UITextLabel *status_;
4203 UIPushButton *close_;
4205 SHA1SumValue springlist_;
4206 SHA1SumValue notifyconf_;
4210 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4212 - (void) _retachThread;
4213 - (void) _detachNewThreadData:(ProgressData *)data;
4214 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4220 @protocol ProgressControllerDelegate
4221 - (void) progressControllerIsComplete:(ProgressController *)sender;
4224 @implementation ProgressController
4227 [database_ setDelegate:nil];
4228 [progress_ release];
4237 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4238 if ((self = [super init]) != nil) {
4239 database_ = database;
4240 [database_ setDelegate:self];
4241 delegate_ = delegate;
4243 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4245 progress_ = [[UIProgressBar alloc] init];
4246 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4247 [progress_ setStyle:0];
4249 status_ = [[UITextLabel alloc] init];
4250 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4251 [status_ setColor:[UIColor whiteColor]];
4252 [status_ setBackgroundColor:[UIColor clearColor]];
4253 [status_ setCentersHorizontally:YES];
4254 //[status_ setFont:font];
4256 output_ = [[UITextView alloc] init];
4258 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4259 //[output_ setTextFont:@"Courier New"];
4260 [output_ setFont:[[output_ font] fontWithSize:12]];
4261 [output_ setTextColor:[UIColor whiteColor]];
4262 [output_ setBackgroundColor:[UIColor clearColor]];
4263 [output_ setMarginTop:0];
4264 [output_ setAllowsRubberBanding:YES];
4265 [output_ setEditable:NO];
4266 [[self view] addSubview:output_];
4268 close_ = [[UIPushButton alloc] init];
4269 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4270 [close_ setAutosizesToFit:NO];
4271 [close_ setDrawsShadow:YES];
4272 [close_ setStretchBackground:YES];
4273 [close_ setEnabled:YES];
4274 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4275 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4276 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4277 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4281 - (void) positionViews {
4282 CGRect bounds = [[self view] bounds];
4283 CGSize prgsize = [UIProgressBar defaultSize];
4286 (bounds.size.width - prgsize.width) / 2,
4287 bounds.size.height - prgsize.height - 64
4290 float closewidth = bounds.size.width - 20;
4291 if (closewidth > 300) closewidth = 300;
4293 [progress_ setFrame:prgrect];
4294 [status_ setFrame:CGRectMake(
4296 bounds.size.height - prgsize.height - 94,
4297 bounds.size.width - 20,
4300 [output_ setFrame:CGRectMake(
4303 bounds.size.width - 20,
4304 bounds.size.height - 106
4306 [close_ setFrame:CGRectMake(
4307 (bounds.size.width - closewidth) / 2,
4308 bounds.size.height - prgsize.height - 94,
4314 - (void) viewWillAppear:(BOOL)animated {
4315 [super viewDidAppear:animated];
4316 [[self navigationItem] setHidesBackButton:YES];
4317 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4319 [self positionViews];
4322 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4323 [self positionViews];
4326 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4327 NSString *context([alert context]);
4329 if ([context isEqualToString:@"conffile"]) {
4330 FILE *input = [database_ input];
4331 if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
4332 else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
4337 - (void) closeButtonPushed {
4340 UpdateExternalStatus(0);
4344 [self dismissModalViewControllerAnimated:YES];
4348 [delegate_ terminateWithSuccess];
4349 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4350 [delegate_ suspendWithAnimation:YES];
4352 [delegate_ suspend];*/
4356 system("launchctl stop com.apple.SpringBoard");
4360 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4369 - (void) _retachThread {
4370 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4372 [[self view] addSubview:close_];
4373 [progress_ removeFromSuperview];
4374 [status_ removeFromSuperview];
4376 [database_ popErrorWithTitle:title_];
4377 [delegate_ progressControllerIsComplete:self];
4381 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4384 MMap mmap(file, MMap::ReadOnly);
4386 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4387 if (!(notifyconf_ == sha1.Result()))
4394 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4397 MMap mmap(file, MMap::ReadOnly);
4399 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4400 if (!(springlist_ == sha1.Result()))
4406 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4407 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4408 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4409 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4410 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4413 system("su -c /usr/bin/uicache mobile");
4415 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4417 [delegate_ setStatusBarShowsProgress:NO];
4420 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4421 [[data target] performSelector:[data selector] withObject:[data object]];
4424 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4427 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4428 UpdateExternalStatus(1);
4435 title_ = [title retain];
4437 [[self navigationItem] setTitle:title_];
4439 [status_ setText:nil];
4440 [output_ setText:@""];
4441 [progress_ setProgress:0];
4443 [close_ removeFromSuperview];
4444 [[self view] addSubview:progress_];
4445 [[self view] addSubview:status_];
4447 [delegate_ setStatusBarShowsProgress:YES];
4452 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4455 MMap mmap(file, MMap::ReadOnly);
4457 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4458 notifyconf_ = sha1.Result();
4464 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4467 MMap mmap(file, MMap::ReadOnly);
4469 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4470 springlist_ = sha1.Result();
4475 detachNewThreadSelector:@selector(_detachNewThreadData:)
4477 withObject:[[ProgressData alloc]
4478 initWithSelector:selector
4485 - (void) repairWithSelector:(SEL)selector {
4487 detachNewThreadSelector:selector
4490 title:UCLocalize("REPAIRING")
4494 - (void) setConfigurationData:(NSString *)data {
4496 performSelectorOnMainThread:@selector(_setConfigurationData:)
4502 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4503 CYActionSheet *sheet([[[CYActionSheet alloc]
4505 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4506 defaultButtonIndex:0
4509 [sheet setMessage:error];
4510 [sheet yieldToPopupAlertAnimated:YES];
4514 - (void) setProgressTitle:(NSString *)title {
4516 performSelectorOnMainThread:@selector(_setProgressTitle:)
4522 - (void) setProgressPercent:(float)percent {
4524 performSelectorOnMainThread:@selector(_setProgressPercent:)
4525 withObject:[NSNumber numberWithFloat:percent]
4530 - (void) startProgress {
4533 - (void) addProgressOutput:(NSString *)output {
4535 performSelectorOnMainThread:@selector(_addProgressOutput:)
4541 - (bool) isCancelling:(size_t)received {
4545 - (void) _setConfigurationData:(NSString *)data {
4546 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4548 if (!conffile_r(data)) {
4549 lprintf("E:invalid conffile\n");
4553 NSString *ofile = conffile_r[1];
4554 //NSString *nfile = conffile_r[2];
4556 UIAlertView *alert = [[[UIAlertView alloc]
4557 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4558 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4560 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4561 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4562 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4566 [alert setContext:@"conffile"];
4570 - (void) _setProgressTitle:(NSString *)title {
4571 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4572 for (size_t i(0), e([words count]); i != e; ++i) {
4573 NSString *word([words objectAtIndex:i]);
4574 if (Package *package = [database_ packageWithName:word])
4575 [words replaceObjectAtIndex:i withObject:[package name]];
4578 [status_ setText:[words componentsJoinedByString:@" "]];
4581 - (void) _setProgressPercent:(NSNumber *)percent {
4582 [progress_ setProgress:[percent floatValue]];
4585 - (void) _addProgressOutput:(NSString *)output {
4586 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4587 CGSize size = [output_ contentSize];
4588 CGRect rect = {{0, size.height}, {size.width, 0}};
4589 [output_ scrollRectToVisible:rect animated:YES];
4592 - (BOOL) isRunning {
4599 /* Cell Content View {{{ */
4600 @protocol ContentDelegate
4601 - (void) drawContentRect:(CGRect)rect;
4604 @interface ContentView : UIView {
4605 _transient id<ContentDelegate> delegate_;
4610 @implementation ContentView
4611 - (id) initWithFrame:(CGRect)frame {
4612 if ((self = [super initWithFrame:frame]) != nil) {
4613 /* Fix landscape stretching. */
4614 [self setNeedsDisplayOnBoundsChange:YES];
4618 - (void) setDelegate:(id<ContentDelegate>)delegate {
4619 delegate_ = delegate;
4622 - (void) drawRect:(CGRect)rect {
4623 [super drawRect:rect];
4624 [delegate_ drawContentRect:rect];
4628 /* Package Cell {{{ */
4629 @interface PackageCell : UITableViewCell <
4634 NSString *description_;
4640 ContentView *content_;
4646 - (PackageCell *) init;
4647 - (void) setPackage:(Package *)package;
4649 + (int) heightForPackage:(Package *)package;
4650 - (void) drawContentRect:(CGRect)rect;
4654 @implementation PackageCell
4656 - (void) clearPackage {
4667 if (description_ != nil) {
4668 [description_ release];
4672 if (source_ != nil) {
4677 if (badge_ != nil) {
4682 if (placard_ != nil) {
4692 [self clearPackage];
4699 return faded_ ? [self selectionPercent] : fade_;
4702 - (PackageCell *) init {
4703 CGRect frame(CGRectMake(0, 0, 320, 74));
4704 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4705 UIView *content([self contentView]);
4706 CGRect bounds([content bounds]);
4708 content_ = [[ContentView alloc] initWithFrame:bounds];
4709 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4710 [content addSubview:content_];
4712 [content_ setDelegate:self];
4713 [content_ setOpaque:YES];
4714 if ([self respondsToSelector:@selector(selectionPercent)])
4719 - (void) _setBackgroundColor {
4721 if (NSString *mode = [package_ mode]) {
4722 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4723 color = remove ? RemovingColor_ : InstallingColor_;
4725 color = [UIColor whiteColor];
4727 [content_ setBackgroundColor:color];
4728 [self setNeedsDisplay];
4731 - (void) setPackage:(Package *)package {
4732 [self clearPackage];
4735 Source *source = [package source];
4737 icon_ = [[package icon] retain];
4738 name_ = [[package name] retain];
4741 description_ = [package longDescription];
4742 if (description_ == nil)
4743 description_ = [package shortDescription];
4744 if (description_ != nil)
4745 description_ = [description_ retain];
4747 commercial_ = [package isCommercial];
4749 package_ = [package retain];
4751 NSString *label = nil;
4752 bool trusted = false;
4754 if (source != nil) {
4755 label = [source label];
4756 trusted = [source trusted];
4757 } else if ([[package id] isEqualToString:@"firmware"])
4758 label = UCLocalize("APPLE");
4760 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4762 NSString *from(label);
4764 NSString *section = [package simpleSection];
4765 if (section != nil && ![section isEqualToString:label]) {
4766 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4767 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4770 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4771 source_ = [from retain];
4773 if (NSString *purpose = [package primaryPurpose])
4774 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4775 badge_ = [badge_ retain];
4777 if ([package installed] != nil)
4778 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4779 placard_ = [placard_ retain];
4781 [self _setBackgroundColor];
4782 [content_ setNeedsDisplay];
4785 - (void) drawContentRect:(CGRect)rect {
4786 bool selected([self isSelected]);
4787 float width([self bounds].size.width);
4790 CGContextRef context(UIGraphicsGetCurrentContext());
4791 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4792 CGContextFillRect(context, rect);
4797 rect.size = [icon_ size];
4799 rect.size.width /= 2;
4800 rect.size.height /= 2;
4802 rect.origin.x = 25 - rect.size.width / 2;
4803 rect.origin.y = 25 - rect.size.height / 2;
4805 [icon_ drawInRect:rect];
4808 if (badge_ != nil) {
4809 CGSize size = [badge_ size];
4811 [badge_ drawAtPoint:CGPointMake(
4812 36 - size.width / 2,
4813 36 - size.height / 2
4821 UISetColor(commercial_ ? Purple_ : Black_);
4822 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4823 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4826 UISetColor(commercial_ ? Purplish_ : Gray_);
4827 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4829 if (placard_ != nil)
4830 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4833 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4834 //[self _setBackgroundColor];
4835 [super setSelected:selected animated:fade];
4836 [content_ setNeedsDisplay];
4839 + (int) heightForPackage:(Package *)package {
4845 /* Section Cell {{{ */
4846 @interface SectionCell : UITableViewCell <
4854 ContentView *content_;
4859 - (void) setSection:(Section *)section editing:(BOOL)editing;
4863 @implementation SectionCell
4865 - (void) clearSection {
4866 if (basic_ != nil) {
4871 if (section_ != nil) {
4881 if (count_ != nil) {
4888 [self clearSection];
4896 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4897 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4898 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4899 switch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4900 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4902 UIView *content([self contentView]);
4903 CGRect bounds([content bounds]);
4905 content_ = [[ContentView alloc] initWithFrame:bounds];
4906 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4907 [content addSubview:content_];
4908 [content_ setBackgroundColor:[UIColor whiteColor]];
4910 [content_ setDelegate:self];
4914 - (void) onSwitch:(id)sender {
4915 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4916 if (metadata == nil) {
4917 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4918 [Sections_ setObject:metadata forKey:basic_];
4922 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4925 - (void) setSection:(Section *)section editing:(BOOL)editing {
4926 if (editing != editing_) {
4928 [switch_ removeFromSuperview];
4930 [self addSubview:switch_];
4934 [self clearSection];
4936 if (section == nil) {
4937 name_ = [UCLocalize("ALL_PACKAGES") retain];
4940 basic_ = [section name];
4942 basic_ = [basic_ retain];
4944 section_ = [section localized];
4945 if (section_ != nil)
4946 section_ = [section_ retain];
4948 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4949 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4952 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4955 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4956 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
4958 [content_ setNeedsDisplay];
4961 - (void) setFrame:(CGRect)frame {
4962 [super setFrame:frame];
4964 CGRect rect([switch_ frame]);
4965 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4968 - (void) drawContentRect:(CGRect)rect {
4969 BOOL selected = [self isSelected];
4971 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4979 float width(rect.size.width);
4983 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4985 CGSize size = [count_ sizeWithFont:Font14_];
4989 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4995 /* File Table {{{ */
4996 @interface FileTable : CYViewController <
4997 UITableViewDataSource,
5000 _transient Database *database_;
5003 NSMutableArray *files_;
5007 - (id) initWithDatabase:(Database *)database;
5008 - (void) setPackage:(Package *)package;
5012 @implementation FileTable
5015 if (package_ != nil)
5024 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5025 return files_ == nil ? 0 : [files_ count];
5028 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5032 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5033 static NSString *reuseIdentifier = @"Cell";
5035 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5037 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5038 [cell setFont:[UIFont systemFontOfSize:16]];
5040 [cell setText:[files_ objectAtIndex:indexPath.row]];
5041 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5046 - (id) initWithDatabase:(Database *)database {
5047 if ((self = [super init]) != nil) {
5048 database_ = database;
5050 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5052 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5054 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5055 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5056 [list_ setRowHeight:24.0f];
5057 [[self view] addSubview:list_];
5059 [list_ setDataSource:self];
5060 [list_ setDelegate:self];
5064 - (void) setPackage:(Package *)package {
5065 if (package_ != nil) {
5066 [package_ autorelease];
5075 [files_ removeAllObjects];
5077 if (package != nil) {
5078 package_ = [package retain];
5079 name_ = [[package id] retain];
5081 if (NSArray *files = [package files])
5082 [files_ addObjectsFromArray:files];
5084 if ([files_ count] != 0) {
5085 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5086 [files_ removeObjectAtIndex:0];
5087 [files_ sortUsingSelector:@selector(compareByPath:)];
5089 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5090 [stack addObject:@"/"];
5092 for (int i(0), e([files_ count]); i != e; ++i) {
5093 NSString *file = [files_ objectAtIndex:i];
5094 while (![file hasPrefix:[stack lastObject]])
5095 [stack removeLastObject];
5096 NSString *directory = [stack lastObject];
5097 [stack addObject:[file stringByAppendingString:@"/"]];
5098 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5099 ([stack count] - 2) * 3, "",
5100 [file substringFromIndex:[directory length]]
5109 - (void) reloadData {
5110 [self setPackage:[database_ packageWithName:name_]];
5115 /* Package Controller {{{ */
5116 @interface PackageController : CYBrowserController <
5117 UIActionSheetDelegate
5119 _transient Database *database_;
5123 NSMutableArray *buttons_;
5124 UIBarButtonItem *button_;
5127 - (id) initWithDatabase:(Database *)database;
5128 - (void) setPackage:(Package *)package;
5132 @implementation PackageController
5135 if (package_ != nil)
5149 if ([self retainCount] == 1)
5150 [delegate_ setPackageController:self];
5154 /* XXX: this is not safe at all... localization of /fail/ */
5155 - (void) _clickButtonWithName:(NSString *)name {
5156 if ([name isEqualToString:UCLocalize("CLEAR")])
5157 [delegate_ clearPackage:package_];
5158 else if ([name isEqualToString:UCLocalize("INSTALL")])
5159 [delegate_ installPackage:package_];
5160 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5161 [delegate_ installPackage:package_];
5162 else if ([name isEqualToString:UCLocalize("REMOVE")])
5163 [delegate_ removePackage:package_];
5164 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5165 [delegate_ installPackage:package_];
5166 else _assert(false);
5169 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5170 NSString *context([sheet context]);
5172 if ([context isEqualToString:@"modify"]) {
5173 if (button != [sheet cancelButtonIndex]) {
5174 NSString *buttonName = [buttons_ objectAtIndex:button];
5175 [self _clickButtonWithName:buttonName];
5178 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5182 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5183 [super webView:view didClearWindowObject:window forFrame:frame];
5184 [window setValue:package_ forKey:@"package"];
5187 - (bool) _allowJavaScriptPanel {
5192 - (void) _customButtonClicked {
5193 int count([buttons_ count]);
5198 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5200 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5201 [buttons addObjectsFromArray:buttons_];
5203 UIActionSheet *sheet = [[[UIActionSheet alloc]
5206 cancelButtonTitle:nil
5207 destructiveButtonTitle:nil
5208 otherButtonTitles:nil
5211 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5213 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5214 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5216 [sheet setContext:@"modify"];
5218 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5222 // We don't want to allow non-commercial packages to do custom things to the install button,
5223 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5224 - (void) customButtonClicked {
5226 [super customButtonClicked];
5228 [self _customButtonClicked];
5231 - (void) reloadButtonClicked {
5232 // Don't reload a package view by clicking the button.
5235 - (void) applyLoadingTitle {
5236 // Don't show "Loading" as the title. Ever.
5239 - (UIBarButtonItem *) rightButton {
5244 - (id) initWithDatabase:(Database *)database {
5245 if ((self = [super init]) != nil) {
5246 database_ = database;
5247 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5248 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5252 - (void) setPackage:(Package *)package {
5253 if (package_ != nil) {
5254 [package_ autorelease];
5263 [buttons_ removeAllObjects];
5265 if (package != nil) {
5268 package_ = [package retain];
5269 name_ = [[package id] retain];
5270 commercial_ = [package isCommercial];
5272 if ([package_ mode] != nil)
5273 [buttons_ addObject:UCLocalize("CLEAR")];
5274 if ([package_ source] == nil);
5275 else if ([package_ upgradableAndEssential:NO])
5276 [buttons_ addObject:UCLocalize("UPGRADE")];
5277 else if ([package_ uninstalled])
5278 [buttons_ addObject:UCLocalize("INSTALL")];
5280 [buttons_ addObject:UCLocalize("REINSTALL")];
5281 if (![package_ uninstalled])
5282 [buttons_ addObject:UCLocalize("REMOVE")];
5289 switch ([buttons_ count]) {
5290 case 0: title = nil; break;
5291 case 1: title = [buttons_ objectAtIndex:0]; break;
5292 default: title = UCLocalize("MODIFY"); break;
5295 button_ = [[UIBarButtonItem alloc]
5297 style:UIBarButtonItemStylePlain
5299 action:@selector(customButtonClicked)
5303 - (bool) isLoading {
5304 return commercial_ ? [super isLoading] : false;
5307 - (void) reloadData {
5308 [self setPackage:[database_ packageWithName:name_]];
5313 /* Package Table {{{ */
5314 @interface PackageTable : UIView <
5315 UITableViewDataSource,
5318 _transient Database *database_;
5319 NSMutableArray *packages_;
5320 NSMutableArray *sections_;
5322 NSMutableArray *index_;
5323 NSMutableDictionary *indices_;
5329 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5331 - (void) setDelegate:(id)delegate;
5333 - (void) reloadData;
5334 - (void) resetCursor;
5336 - (UITableView *) list;
5338 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5340 - (void) deselectWithAnimation:(BOOL)animated;
5344 @implementation PackageTable
5347 [packages_ release];
5348 [sections_ release];
5356 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5357 NSInteger count([sections_ count]);
5358 return count == 0 ? 1 : count;
5361 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5362 if ([sections_ count] == 0)
5364 return [[sections_ objectAtIndex:section] name];
5367 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5368 if ([sections_ count] == 0)
5370 return [[sections_ objectAtIndex:section] count];
5373 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5374 Section *section([sections_ objectAtIndex:[path section]]);
5375 NSInteger row([path row]);
5376 Package *package([packages_ objectAtIndex:([section row] + row)]);
5380 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5381 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5383 cell = [[[PackageCell alloc] init] autorelease];
5384 [cell setPackage:[self packageAtIndexPath:path]];
5388 - (void) deselectWithAnimation:(BOOL)animated {
5389 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5392 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5393 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5396 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5397 Package *package([self packageAtIndexPath:path]);
5398 package = [database_ packageWithName:[package id]];
5399 [target_ performSelector:action_ withObject:package];
5403 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5404 return [packages_ count] > 20 ? index_ : nil;
5407 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5411 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5412 if ((self = [super initWithFrame:frame]) != nil) {
5413 database_ = database;
5418 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5419 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5421 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5422 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5424 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5425 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5426 [list_ setRowHeight:73.0f];
5427 [self addSubview:list_];
5429 [list_ setDataSource:self];
5430 [list_ setDelegate:self];
5434 - (void) setDelegate:(id)delegate {
5435 delegate_ = delegate;
5438 - (bool) hasPackage:(Package *)package {
5442 - (void) reloadData {
5443 NSArray *packages = [database_ packages];
5445 [packages_ removeAllObjects];
5446 [sections_ removeAllObjects];
5448 _profile(PackageTable$reloadData$Filter)
5449 for (Package *package in packages)
5450 if ([self hasPackage:package])
5451 [packages_ addObject:package];
5454 [index_ removeAllObjects];
5455 [indices_ removeAllObjects];
5457 Section *section = nil;
5459 _profile(PackageTable$reloadData$Section)
5460 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5464 _profile(PackageTable$reloadData$Section$Package)
5465 package = [packages_ objectAtIndex:offset];
5466 index = [package index];
5469 if (section == nil || [section index] != index) {
5470 _profile(PackageTable$reloadData$Section$Allocate)
5471 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5474 [index_ addObject:[section name]];
5475 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5477 _profile(PackageTable$reloadData$Section$Add)
5478 [sections_ addObject:section];
5482 [section addToCount];
5486 _profile(PackageTable$reloadData$List)
5491 - (void) resetCursor {
5492 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5495 - (UITableView *) list {
5499 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5500 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5505 /* Filtered Package Table {{{ */
5506 @interface FilteredPackageTable : PackageTable {
5512 - (void) setObject:(id)object;
5513 - (void) setObject:(id)object forFilter:(SEL)filter;
5515 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5519 @implementation FilteredPackageTable
5527 - (void) setFilter:(SEL)filter {
5530 /* XXX: this is an unsafe optimization of doomy hell */
5531 Method method(class_getInstanceMethod([Package class], filter));
5532 _assert(method != NULL);
5533 imp_ = method_getImplementation(method);
5534 _assert(imp_ != NULL);
5537 - (void) setObject:(id)object {
5543 object_ = [object retain];
5546 - (void) setObject:(id)object forFilter:(SEL)filter {
5547 [self setFilter:filter];
5548 [self setObject:object];
5551 - (bool) hasPackage:(Package *)package {
5552 _profile(FilteredPackageTable$hasPackage)
5553 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5557 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5558 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5559 [self setFilter:filter];
5560 object_ = [object retain];
5568 /* Filtered Package Controller {{{ */
5569 @interface FilteredPackageController : CYViewController {
5570 _transient Database *database_;
5571 FilteredPackageTable *packages_;
5575 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5579 @implementation FilteredPackageController
5582 [packages_ release];
5588 - (void) viewDidAppear:(BOOL)animated {
5589 [super viewDidAppear:animated];
5590 [packages_ deselectWithAnimation:animated];
5593 - (void) didSelectPackage:(Package *)package {
5594 PackageController *view([delegate_ packageController]);
5595 [view setPackage:package];
5596 [view setDelegate:delegate_];
5597 [[self navigationController] pushViewController:view animated:YES];
5600 - (NSString *) title { return title_; }
5602 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5603 if ((self = [super init]) != nil) {
5604 database_ = database;
5605 title_ = [title copy];
5606 [[self navigationItem] setTitle:title_];
5608 packages_ = [[FilteredPackageTable alloc]
5609 initWithFrame:[[self view] bounds]
5612 action:@selector(didSelectPackage:)
5617 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5618 [[self view] addSubview:packages_];
5622 - (void) reloadData {
5623 [packages_ reloadData];
5626 - (void) setDelegate:(id)delegate {
5627 [super setDelegate:delegate];
5628 [packages_ setDelegate:delegate];
5635 /* Add Source Controller {{{ */
5636 @interface AddSourceController : CYViewController {
5637 _transient Database *database_;
5640 - (id) initWithDatabase:(Database *)database;
5644 @implementation AddSourceController
5646 - (id) initWithDatabase:(Database *)database {
5647 if ((self = [super init]) != nil) {
5648 database_ = database;
5654 /* Source Cell {{{ */
5655 @interface SourceCell : UITableViewCell <
5660 NSString *description_;
5662 ContentView *content_;
5665 - (void) setSource:(Source *)source;
5669 @implementation SourceCell
5671 - (void) clearSource {
5674 [description_ release];
5683 - (void) setSource:(Source *)source {
5687 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5689 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5690 icon_ = [icon_ retain];
5692 origin_ = [[source name] retain];
5693 label_ = [[source uri] retain];
5694 description_ = [[source description] retain];
5696 [content_ setNeedsDisplay];
5705 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5706 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5707 UIView *content([self contentView]);
5708 CGRect bounds([content bounds]);
5710 content_ = [[ContentView alloc] initWithFrame:bounds];
5711 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5712 [content_ setBackgroundColor:[UIColor whiteColor]];
5713 [content addSubview:content_];
5715 [content_ setDelegate:self];
5716 [content_ setOpaque:YES];
5720 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5721 [super setSelected:selected animated:animated];
5722 [content_ setNeedsDisplay];
5725 - (void) drawContentRect:(CGRect)rect {
5726 bool selected([self isSelected]);
5727 float width(rect.size.width);
5730 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5737 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5741 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5745 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5750 /* Source Table {{{ */
5751 @interface SourceTable : CYViewController <
5752 UITableViewDataSource,
5755 _transient Database *database_;
5757 NSMutableArray *sources_;
5761 UIProgressHUD *hud_;
5764 //NSURLConnection *installer_;
5765 NSURLConnection *trivial_;
5766 NSURLConnection *trivial_bz2_;
5767 NSURLConnection *trivial_gz_;
5768 //NSURLConnection *automatic_;
5773 - (id) initWithDatabase:(Database *)database;
5775 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5779 @implementation SourceTable
5781 - (void) _deallocConnection:(NSURLConnection *)connection {
5782 if (connection != nil) {
5783 [connection cancel];
5784 //[connection setDelegate:nil];
5785 [connection release];
5797 //[self _deallocConnection:installer_];
5798 [self _deallocConnection:trivial_];
5799 [self _deallocConnection:trivial_gz_];
5800 [self _deallocConnection:trivial_bz2_];
5801 //[self _deallocConnection:automatic_];
5808 - (void) viewDidAppear:(BOOL)animated {
5809 [super viewDidAppear:animated];
5810 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5813 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5814 return offset_ == 0 ? 1 : 2;
5817 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5818 switch (section + (offset_ == 0 ? 1 : 0)) {
5819 case 0: return UCLocalize("ENTERED_BY_USER");
5820 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5826 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5827 int count = [sources_ count];
5829 case 0: return (offset_ == 0 ? count : offset_);
5830 case 1: return count - offset_;
5836 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5838 switch (indexPath.section) {
5839 case 0: idx = indexPath.row; break;
5840 case 1: idx = indexPath.row + offset_; break;
5844 return [sources_ objectAtIndex:idx];
5847 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5848 Source *source = [self sourceAtIndexPath:indexPath];
5849 return [source description] == nil ? 56 : 73;
5852 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5853 static NSString *cellIdentifier = @"SourceCell";
5855 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5856 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5857 [cell setSource:[self sourceAtIndexPath:indexPath]];
5862 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5863 return UITableViewCellAccessoryDisclosureIndicator;
5866 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5867 Source *source = [self sourceAtIndexPath:indexPath];
5869 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5870 initWithDatabase:database_
5871 title:[source label]
5872 filter:@selector(isVisibleInSource:)
5876 [packages setDelegate:delegate_];
5878 [[self navigationController] pushViewController:packages animated:YES];
5881 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5882 Source *source = [self sourceAtIndexPath:indexPath];
5883 return [source record] != nil;
5886 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5887 Source *source = [self sourceAtIndexPath:indexPath];
5888 [Sources_ removeObjectForKey:[source key]];
5889 [delegate_ syncData];
5893 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5896 @"./", @"Distribution",
5897 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5899 [delegate_ syncData];
5902 - (NSString *) getWarning {
5903 NSString *href(href_);
5904 NSRange colon([href rangeOfString:@"://"]);
5905 if (colon.location != NSNotFound)
5906 href = [href substringFromIndex:(colon.location + 3)];
5907 href = [href stringByAddingPercentEscapes];
5908 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5909 href = [href stringByCachingURLWithCurrentCDN];
5911 NSURL *url([NSURL URLWithString:href]);
5913 NSStringEncoding encoding;
5914 NSError *error(nil);
5916 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5917 return [warning length] == 0 ? nil : warning;
5921 - (void) _endConnection:(NSURLConnection *)connection {
5922 NSURLConnection **field = NULL;
5923 if (connection == trivial_)
5925 else if (connection == trivial_bz2_)
5926 field = &trivial_bz2_;
5927 else if (connection == trivial_gz_)
5928 field = &trivial_gz_;
5929 _assert(field != NULL);
5930 [connection release];
5935 trivial_bz2_ == nil &&
5941 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5944 UIAlertView *alert = [[[UIAlertView alloc]
5945 initWithTitle:UCLocalize("SOURCE_WARNING")
5948 cancelButtonTitle:UCLocalize("CANCEL")
5949 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5952 [alert setContext:@"warning"];
5953 [alert setNumberOfRows:1];
5957 } else if (error_ != nil) {
5958 UIAlertView *alert = [[[UIAlertView alloc]
5959 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5960 message:[error_ localizedDescription]
5962 cancelButtonTitle:UCLocalize("OK")
5963 otherButtonTitles:nil
5966 [alert setContext:@"urlerror"];
5969 UIAlertView *alert = [[[UIAlertView alloc]
5970 initWithTitle:UCLocalize("NOT_REPOSITORY")
5971 message:UCLocalize("NOT_REPOSITORY_EX")
5973 cancelButtonTitle:UCLocalize("OK")
5974 otherButtonTitles:nil
5977 [alert setContext:@"trivial"];
5981 [delegate_ setStatusBarShowsProgress:NO];
5982 [delegate_ removeProgressHUD:hud_];
5992 if (error_ != nil) {
5999 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6000 switch ([response statusCode]) {
6006 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6007 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6009 error_ = [error retain];
6010 [self _endConnection:connection];
6013 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6014 [self _endConnection:connection];
6017 - (NSString *) title { return UCLocalize("SOURCES"); }
6019 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6020 NSMutableURLRequest *request = [NSMutableURLRequest
6021 requestWithURL:[NSURL URLWithString:href]
6022 cachePolicy:NSURLRequestUseProtocolCachePolicy
6023 timeoutInterval:120.0
6026 [request setHTTPMethod:method];
6028 if (Machine_ != NULL)
6029 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6030 if (UniqueID_ != nil)
6031 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6033 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6035 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6038 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6039 NSString *context([alert context]);
6041 if ([context isEqualToString:@"source"]) {
6044 NSString *href = [[alert textField] text];
6046 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6048 if (![href hasSuffix:@"/"])
6049 href_ = [href stringByAppendingString:@"/"];
6052 href_ = [href_ retain];
6054 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6055 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6056 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6057 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6061 hud_ = [[delegate_ addProgressHUD] retain];
6062 [hud_ setText:UCLocalize("VERIFYING_URL")];
6071 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6072 } else if ([context isEqualToString:@"trivial"])
6073 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6074 else if ([context isEqualToString:@"urlerror"])
6075 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6076 else if ([context isEqualToString:@"warning"]) {
6091 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6095 - (id) initWithDatabase:(Database *)database {
6096 if ((self = [super init]) != nil) {
6097 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6098 [self updateButtonsForEditingStatus:NO animated:NO];
6100 database_ = database;
6101 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6103 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6104 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6105 [[self view] addSubview:list_];
6107 [list_ setDataSource:self];
6108 [list_ setDelegate:self];
6114 - (void) reloadData {
6116 if (!list.ReadMainList())
6119 [sources_ removeAllObjects];
6120 [sources_ addObjectsFromArray:[database_ sources]];
6122 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6125 int count([sources_ count]);
6127 for (int i = 0; i != count; i++) {
6128 if ([[sources_ objectAtIndex:i] record] == nil) break;
6132 [list_ setEditing:NO];
6133 [self updateButtonsForEditingStatus:NO animated:NO];
6137 - (void) addButtonClicked {
6138 /*[book_ pushPage:[[[AddSourceController alloc]
6143 UIAlertView *alert = [[[UIAlertView alloc]
6144 initWithTitle:UCLocalize("ENTER_APT_URL")
6147 cancelButtonTitle:UCLocalize("CANCEL")
6148 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6151 [alert setContext:@"source"];
6152 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6154 [alert setNumberOfRows:1];
6155 [alert addTextFieldWithValue:@"http://" label:@""];
6157 UITextInputTraits *traits = [[alert textField] textInputTraits];
6158 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6159 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6160 [traits setKeyboardType:UIKeyboardTypeURL];
6161 // XXX: UIReturnKeyDone
6162 [traits setReturnKeyType:UIReturnKeyNext];
6167 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6168 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
6169 initWithTitle:UCLocalize("ADD")
6170 style:UIBarButtonItemStylePlain
6172 action:@selector(addButtonClicked)
6174 [[self navigationItem] setLeftBarButtonItem:editing ? leftItem : [[self navigationItem] backBarButtonItem] animated:animated];
6177 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6178 initWithTitle:editing ? UCLocalize("DONE") : UCLocalize("EDIT")
6179 style:editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6181 action:@selector(editButtonClicked)
6183 [[self navigationItem] setRightBarButtonItem:rightItem animated:animated];
6184 [rightItem release];
6186 if (IsWildcat_ && !editing) {
6187 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6188 initWithTitle:UCLocalize("SETTINGS")
6189 style:UIBarButtonItemStylePlain
6191 action:@selector(settingsButtonClicked)
6193 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6194 [settingsItem release];
6198 - (void) settingsButtonClicked {
6199 [delegate_ showSettings];
6202 - (void) editButtonClicked {
6203 [list_ setEditing:![list_ isEditing] animated:YES];
6205 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6211 /* Installed Controller {{{ */
6212 @interface InstalledController : FilteredPackageController {
6216 - (id) initWithDatabase:(Database *)database;
6218 - (void) updateRoleButton;
6219 - (void) queueStatusDidChange;
6223 @implementation InstalledController
6229 - (NSString *) title { return UCLocalize("INSTALLED"); }
6231 - (id) initWithDatabase:(Database *)database {
6232 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6233 [self updateRoleButton];
6234 [self queueStatusDidChange];
6239 - (void) queueButtonClicked {
6244 - (void) queueStatusDidChange {
6247 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6248 initWithTitle:UCLocalize("QUEUE")
6249 style:UIBarButtonItemStyleDone
6251 action:@selector(queueButtonClicked)
6253 if (Queuing_) [[self navigationItem] setLeftBarButtonItem:queueItem];
6254 else [[self navigationItem] setLeftBarButtonItem:nil];
6255 [queueItem release];
6260 - (void) reloadData {
6261 [packages_ reloadData];
6264 - (void) updateRoleButton {
6265 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6266 initWithTitle:expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")
6267 style:expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6269 action:@selector(roleButtonClicked)
6271 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) [[self navigationItem] setRightBarButtonItem:rightItem];
6272 [rightItem release];
6275 - (void) roleButtonClicked {
6276 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6277 [packages_ reloadData];
6280 [self updateRoleButton];
6283 - (void) setDelegate:(id)delegate {
6284 [super setDelegate:delegate];
6285 [packages_ setDelegate:delegate];
6291 /* Home Controller {{{ */
6292 @interface HomeController : CYBrowserController {
6297 @implementation HomeController
6299 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6300 [super _setMoreHeaders:request];
6303 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6304 if (UniqueID_ != nil)
6305 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6308 - (void) aboutButtonClicked {
6309 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6311 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6312 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6313 [alert setCancelButtonIndex:0];
6316 @"Copyright (C) 2008-2010\n"
6317 "Jay Freeman (saurik)\n"
6318 "saurik@saurik.com\n"
6319 "http://www.saurik.com/"
6325 - (void) viewWillAppear:(BOOL)animated {
6326 [super viewWillAppear:animated];
6327 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6330 - (void) viewWillDisappear:(BOOL)animated {
6331 [super viewWillDisappear:animated];
6332 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6336 if ((self = [super init]) != nil) {
6337 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6338 initWithTitle:UCLocalize("ABOUT")
6339 style:UIBarButtonItemStylePlain
6341 action:@selector(aboutButtonClicked)
6348 /* Manage Controller {{{ */
6349 @interface ManageController : CYBrowserController {
6352 - (void) queueStatusDidChange;
6355 @implementation ManageController
6358 if ((self = [super init]) != nil) {
6359 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6361 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6362 initWithTitle:UCLocalize("SETTINGS")
6363 style:UIBarButtonItemStylePlain
6365 action:@selector(settingsButtonClicked)
6367 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6368 [settingsItem release];
6370 [self queueStatusDidChange];
6374 - (void) settingsButtonClicked {
6375 [delegate_ showSettings];
6379 - (void) queueButtonClicked {
6383 - (void) applyLoadingTitle {
6384 // No "Loading" title.
6387 - (void) applyRightButton {
6392 - (void) queueStatusDidChange {
6394 if (!IsWildcat_ && Queuing_) {
6395 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6396 initWithTitle:UCLocalize("QUEUE")
6397 style:UIBarButtonItemStyleDone
6399 action:@selector(queueButtonClicked)
6401 [[self navigationItem] setRightBarButtonItem:queueItem];
6403 [queueItem release];
6405 [[self navigationItem] setRightBarButtonItem:nil];
6410 - (bool) isLoading {
6417 /* Refresh Bar {{{ */
6418 @interface RefreshBar : UINavigationBar {
6419 UIProgressIndicator *indicator_;
6420 UITextLabel *prompt_;
6421 UIProgressBar *progress_;
6422 UINavigationButton *cancel_;
6427 @implementation RefreshBar
6429 - (void) positionViews {
6430 CGRect frame = [cancel_ frame];
6431 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6432 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6433 [cancel_ setFrame:frame];
6435 CGSize prgsize = {75, 100};
6437 [self frame].size.width - prgsize.width - 10,
6438 ([self frame].size.height - prgsize.height) / 2
6440 [progress_ setFrame:prgrect];
6442 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6443 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6444 CGRect indrect = {{indoffset, indoffset}, indsize};
6445 [indicator_ setFrame:indrect];
6447 CGSize prmsize = {215, indsize.height + 4};
6449 indoffset * 2 + indsize.width,
6450 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6452 [prompt_ setFrame:prmrect];
6455 - (void)setFrame:(CGRect)frame {
6456 [super setFrame:frame];
6458 [self positionViews];
6461 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6462 if ((self = [super initWithFrame:frame])) {
6463 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6465 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6466 [self setBarStyle:UIBarStyleBlack];
6468 UIBarStyle barstyle([self _barStyle:NO]);
6469 bool ugly(barstyle == UIBarStyleDefault);
6471 UIProgressIndicatorStyle style = ugly ?
6472 UIProgressIndicatorStyleMediumBrown :
6473 UIProgressIndicatorStyleMediumWhite;
6475 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6476 [indicator_ setStyle:style];
6477 [indicator_ startAnimation];
6478 [self addSubview:indicator_];
6480 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6481 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6482 [prompt_ setBackgroundColor:[UIColor clearColor]];
6483 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6484 [self addSubview:prompt_];
6486 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6487 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6488 [progress_ setStyle:0];
6489 [self addSubview:progress_];
6491 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6492 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6493 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6494 [cancel_ setBarStyle:barstyle];
6496 [self positionViews];
6501 [cancel_ removeFromSuperview];
6505 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6506 [progress_ setProgress:0];
6507 [self addSubview:cancel_];
6511 [cancel_ removeFromSuperview];
6514 - (void) setPrompt:(NSString *)prompt {
6515 [prompt_ setText:prompt];
6518 - (void) setProgress:(float)progress {
6519 [progress_ setProgress:progress];
6525 @class CYNavigationController;
6527 /* Cydia Tab Bar Controller {{{ */
6528 @interface CYTabBarController : UITabBarController {
6529 Database *database_;
6534 @implementation CYTabBarController
6536 /* XXX: some logic should probably go here related to
6537 freeing the view controllers on tab change */
6539 - (void) reloadData {
6540 size_t count([[self viewControllers] count]);
6541 for (size_t i(0); i != count; ++i) {
6542 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6547 - (id) initWithDatabase:(Database *)database {
6548 if ((self = [super init]) != nil) {
6549 database_ = database;
6556 /* Cydia Navigation Controller {{{ */
6557 @interface CYNavigationController : UINavigationController {
6558 _transient Database *database_;
6559 id<UINavigationControllerDelegate> delegate_;
6562 - (id) initWithDatabase:(Database *)database;
6563 - (void) reloadData;
6568 @implementation CYNavigationController
6570 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6571 // Inherit autorotation settings for modal parents.
6572 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6573 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6575 return [super shouldAutorotateToInterfaceOrientation:orientation];
6583 - (void) reloadData {
6584 size_t count([[self viewControllers] count]);
6585 for (size_t i(0); i != count; ++i) {
6586 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6591 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6592 delegate_ = delegate;
6595 - (id) initWithDatabase:(Database *)database {
6596 if ((self = [super init]) != nil) {
6597 database_ = database;
6603 /* Cydia:// Protocol {{{ */
6604 @interface CydiaURLProtocol : NSURLProtocol {
6609 @implementation CydiaURLProtocol
6611 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6612 NSURL *url([request URL]);
6615 NSString *scheme([[url scheme] lowercaseString]);
6616 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6621 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6625 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6626 id<NSURLProtocolClient> client([self client]);
6628 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6630 NSData *data(UIImagePNGRepresentation(icon));
6632 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6633 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6634 [client URLProtocol:self didLoadData:data];
6635 [client URLProtocolDidFinishLoading:self];
6639 - (void) startLoading {
6640 id<NSURLProtocolClient> client([self client]);
6641 NSURLRequest *request([self request]);
6643 NSURL *url([request URL]);
6644 NSString *href([url absoluteString]);
6646 NSString *path([href substringFromIndex:8]);
6647 NSRange slash([path rangeOfString:@"/"]);
6650 if (slash.location == NSNotFound) {
6654 command = [path substringToIndex:slash.location];
6655 path = [path substringFromIndex:(slash.location + 1)];
6658 Database *database([Database sharedInstance]);
6660 if ([command isEqualToString:@"package-icon"]) {
6663 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6664 Package *package([database packageWithName:path]);
6667 UIImage *icon([package icon]);
6668 [self _returnPNGWithImage:icon forRequest:request];
6669 } else if ([command isEqualToString:@"source-icon"]) {
6672 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6673 NSString *source(Simplify(path));
6674 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6676 icon = [UIImage applicationImageNamed:@"unknown.png"];
6677 [self _returnPNGWithImage:icon forRequest:request];
6678 } else if ([command isEqualToString:@"uikit-image"]) {
6681 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6682 UIImage *icon(_UIImageWithName(path));
6683 [self _returnPNGWithImage:icon forRequest:request];
6684 } else if ([command isEqualToString:@"section-icon"]) {
6687 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6688 NSString *section(Simplify(path));
6689 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6691 icon = [UIImage applicationImageNamed:@"unknown.png"];
6692 [self _returnPNGWithImage:icon forRequest:request];
6694 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6698 - (void) stopLoading {
6704 /* Sections Controller {{{ */
6705 @interface SectionsController : CYViewController <
6706 UITableViewDataSource,
6709 _transient Database *database_;
6710 NSMutableArray *sections_;
6711 NSMutableArray *filtered_;
6717 - (id) initWithDatabase:(Database *)database;
6718 - (void) reloadData;
6721 - (void) editButtonClicked;
6725 @implementation SectionsController
6728 [list_ setDataSource:nil];
6729 [list_ setDelegate:nil];
6731 [sections_ release];
6732 [filtered_ release];
6734 [accessory_ release];
6738 - (void) viewDidAppear:(BOOL)animated {
6739 [super viewDidAppear:animated];
6740 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6743 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6744 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6748 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6749 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6752 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6756 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6757 static NSString *reuseIdentifier = @"SectionCell";
6759 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6760 if (cell == nil) cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6761 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6766 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6770 Section *section = [self sectionAtIndexPath:indexPath];
6771 NSString *name = [section name];
6774 if ([indexPath row] == 0) {
6777 title = UCLocalize("ALL_PACKAGES");
6780 name = [NSString stringWithString:name];
6781 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6784 title = UCLocalize("NO_SECTION");
6788 FilteredPackageController *table = [[[FilteredPackageController alloc]
6789 initWithDatabase:database_
6791 filter:@selector(isVisibleInSection:)
6795 [table setDelegate:delegate_];
6797 [[self navigationController] pushViewController:table animated:YES];
6800 - (NSString *) title { return UCLocalize("SECTIONS"); }
6802 - (id) initWithDatabase:(Database *)database {
6803 if ((self = [super init]) != nil) {
6804 database_ = database;
6806 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6808 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6809 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6811 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6812 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6813 [list_ setRowHeight:45.0f];
6814 [[self view] addSubview:list_];
6816 [list_ setDataSource:self];
6817 [list_ setDelegate:self];
6823 - (void) reloadData {
6824 NSArray *packages = [database_ packages];
6826 [sections_ removeAllObjects];
6827 [filtered_ removeAllObjects];
6830 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6831 SectionMap sections;
6832 sections.resize(64);
6834 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6838 for (Package *package in packages) {
6839 NSString *name([package section]);
6840 NSString *key(name == nil ? @"" : name);
6845 _profile(SectionsView$reloadData$Section)
6846 section = §ions[key];
6847 if (*section == nil) {
6848 _profile(SectionsView$reloadData$Section$Allocate)
6849 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6854 [*section addToCount];
6856 _profile(SectionsView$reloadData$Filter)
6857 if (![package valid] || ![package visible])
6861 [*section addToRow];
6865 _profile(SectionsView$reloadData$Section)
6866 section = [sections objectForKey:key];
6867 if (section == nil) {
6868 _profile(SectionsView$reloadData$Section$Allocate)
6869 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6870 [sections setObject:section forKey:key];
6875 [section addToCount];
6877 _profile(SectionsView$reloadData$Filter)
6878 if (![package valid] || ![package visible])
6888 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6889 [sections_ addObject:i->second];
6891 [sections_ addObjectsFromArray:[sections allValues]];
6894 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6896 for (Section *section in sections_) {
6897 size_t count([section row]);
6901 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6902 [section setCount:count];
6903 [filtered_ addObject:section];
6906 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6907 initWithTitle:[sections_ count] == 0 ? nil : UCLocalize("EDIT")
6908 style:UIBarButtonItemStylePlain
6910 action:@selector(editButtonClicked)
6912 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] != nil];
6913 [rightItem release];
6919 - (void) resetView {
6921 [self editButtonClicked];
6924 - (void) editButtonClicked {
6925 if ((editing_ = !editing_))
6928 [delegate_ updateData];
6930 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6931 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6932 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6935 - (UIView *) accessoryView {
6941 /* Changes Controller {{{ */
6942 @interface ChangesController : CYViewController <
6943 UITableViewDataSource,
6946 _transient Database *database_;
6947 NSMutableArray *packages_;
6948 NSMutableArray *sections_;
6951 BOOL hasSentFirstLoad_;
6954 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6955 - (void) reloadData;
6959 @implementation ChangesController
6962 [list_ setDelegate:nil];
6963 [list_ setDataSource:nil];
6965 [packages_ release];
6966 [sections_ release];
6971 - (void) viewDidAppear:(BOOL)animated {
6972 [super viewDidAppear:animated];
6973 if (!hasSentFirstLoad_) {
6974 hasSentFirstLoad_ = YES;
6975 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6977 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6981 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6982 NSInteger count([sections_ count]);
6983 return count == 0 ? 1 : count;
6986 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6987 if ([sections_ count] == 0)
6989 return [[sections_ objectAtIndex:section] name];
6992 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6993 if ([sections_ count] == 0)
6995 return [[sections_ objectAtIndex:section] count];
6998 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6999 Section *section([sections_ objectAtIndex:[path section]]);
7000 NSInteger row([path row]);
7001 return [packages_ objectAtIndex:([section row] + row)];
7004 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7005 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7007 cell = [[[PackageCell alloc] init] autorelease];
7008 [cell setPackage:[self packageAtIndexPath:path]];
7012 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7013 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7016 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7017 Package *package([self packageAtIndexPath:path]);
7018 PackageController *view([delegate_ packageController]);
7019 [view setDelegate:delegate_];
7020 [view setPackage:package];
7021 [[self navigationController] pushViewController:view animated:YES];
7025 - (void) refreshButtonClicked {
7026 [delegate_ beginUpdate];
7027 [[self navigationItem] setLeftBarButtonItem:nil];
7030 - (void) upgradeButtonClicked {
7031 [delegate_ distUpgrade];
7034 - (NSString *) title { return UCLocalize("CHANGES"); }
7036 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7037 if ((self = [super init]) != nil) {
7038 database_ = database;
7039 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7041 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
7042 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7044 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7045 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7046 [list_ setRowHeight:73.0f];
7047 [[self view] addSubview:list_];
7049 [list_ setDataSource:self];
7050 [list_ setDelegate:self];
7052 delegate_ = delegate;
7056 - (void) _reloadPackages:(NSArray *)packages {
7058 for (Package *package in packages)
7060 [package uninstalled] && [package valid] && [package visible] ||
7061 [package upgradableAndEssential:YES]
7063 [packages_ addObject:package];
7066 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7070 - (void) reloadData {
7071 NSArray *packages = [database_ packages];
7073 [packages_ removeAllObjects];
7074 [sections_ removeAllObjects];
7076 UIProgressHUD *hud([delegate_ addProgressHUD]);
7078 [hud setText:@"Loading Changes"];
7079 NSLog(@"HUD:%@::%@", delegate_, hud);
7080 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7081 [delegate_ removeProgressHUD:hud];
7083 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7084 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7085 Section *section = nil;
7089 bool unseens = false;
7091 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7093 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7094 Package *package = [packages_ objectAtIndex:offset];
7096 BOOL uae = [package upgradableAndEssential:YES];
7102 _profile(ChangesController$reloadData$Remember)
7103 seen = [package seen];
7106 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7111 name = UCLocalize("UNKNOWN");
7113 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7117 _profile(ChangesController$reloadData$Allocate)
7118 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7119 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7120 [sections_ addObject:section];
7124 [section addToCount];
7125 } else if ([package ignored])
7126 [ignored addToCount];
7129 [upgradable addToCount];
7134 CFRelease(formatter);
7137 Section *last = [sections_ lastObject];
7138 size_t count = [last count];
7139 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7140 [sections_ removeLastObject];
7143 if ([ignored count] != 0)
7144 [sections_ insertObject:ignored atIndex:0];
7146 [sections_ insertObject:upgradable atIndex:0];
7150 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7151 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7152 style:UIBarButtonItemStylePlain
7154 action:@selector(upgradeButtonClicked)
7156 if (upgrades_ > 0) [[self navigationItem] setRightBarButtonItem:rightItem];
7157 [rightItem release];
7159 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
7160 initWithTitle:UCLocalize("REFRESH")
7161 style:UIBarButtonItemStylePlain
7163 action:@selector(refreshButtonClicked)
7165 if (![delegate_ updating]) [[self navigationItem] setLeftBarButtonItem:leftItem];
7171 /* Search Controller {{{ */
7172 @interface SearchController : FilteredPackageController <
7175 UISearchBar *search_;
7178 - (id) initWithDatabase:(Database *)database;
7179 - (void) reloadData;
7183 @implementation SearchController
7190 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7191 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7192 [search_ resignFirstResponder];
7196 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7197 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7201 - (NSString *) title { return nil; }
7203 - (id) initWithDatabase:(Database *)database {
7204 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7207 - (void)viewDidAppear:(BOOL)animated {
7208 [super viewDidAppear:animated];
7210 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7211 [search_ layoutSubviews];
7212 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7213 UITextField *textField = [search_ searchField];
7214 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7215 [search_ setDelegate:self];
7216 [textField setEnablesReturnKeyAutomatically:NO];
7217 [[self navigationItem] setTitleView:textField];
7221 - (void) _reloadData {
7224 - (void) reloadData {
7225 _profile(SearchController$reloadData)
7226 [packages_ reloadData];
7229 [packages_ resetCursor];
7232 - (void) didSelectPackage:(Package *)package {
7233 [search_ resignFirstResponder];
7234 [super didSelectPackage:package];
7239 /* Settings Controller {{{ */
7240 @interface SettingsController : CYViewController <
7241 UITableViewDataSource,
7244 _transient Database *database_;
7247 UITableView *table_;
7248 id subscribedSwitch_;
7250 UITableViewCell *subscribedCell_;
7251 UITableViewCell *ignoredCell_;
7254 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7258 @implementation SettingsController
7262 if (package_ != nil)
7265 [subscribedSwitch_ release];
7266 [ignoredSwitch_ release];
7267 [subscribedCell_ release];
7268 [ignoredCell_ release];
7273 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7274 if (package_ == nil)
7280 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7281 if (package_ == nil)
7287 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7288 return UCLocalize("SHOW_ALL_CHANGES_EX");
7291 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7292 if (package_ == nil)
7295 NSMutableDictionary *metadata([package_ metadata]);
7298 if (NSNumber *number = [metadata objectForKey:key])
7299 before = [number boolValue];
7303 if (value != before) {
7304 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7306 [delegate_ updateData];
7310 - (void) onSubscribed:(id)control {
7311 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7314 - (void) onIgnored:(id)control {
7315 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
7318 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7319 if (package_ == nil)
7322 switch ([indexPath row]) {
7323 case 0: return subscribedCell_;
7324 case 1: return ignoredCell_;
7332 - (NSString *) title { return UCLocalize("SETTINGS"); }
7334 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7335 if ((self = [super init])) {
7336 database_ = database;
7337 name_ = [package retain];
7339 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7341 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7342 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7343 [[self view] addSubview:table_];
7345 subscribedSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7346 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7347 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7349 ignoredSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7350 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7351 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7353 subscribedCell_ = [[UITableViewCell alloc] init];
7354 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7355 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7356 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7358 ignoredCell_ = [[UITableViewCell alloc] init];
7359 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7360 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7361 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7363 [table_ setDataSource:self];
7364 [table_ setDelegate:self];
7369 - (void) reloadData {
7370 if (package_ != nil)
7371 [package_ autorelease];
7372 package_ = [database_ packageWithName:name_];
7373 if (package_ != nil) {
7375 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7376 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7379 [table_ reloadData];
7385 /* Signature Controller {{{ */
7386 @interface SignatureController : CYBrowserController {
7387 _transient Database *database_;
7391 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7395 @implementation SignatureController
7402 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7404 [super webView:view didClearWindowObject:window forFrame:frame];
7407 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7408 if ((self = [super init]) != nil) {
7409 database_ = database;
7410 package_ = [package retain];
7415 - (void) reloadData {
7416 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7421 /* Role Controller {{{ */
7422 @interface RoleController : CYViewController <
7423 UITableViewDataSource,
7426 _transient Database *database_;
7428 UITableView *table_;
7429 UISegmentedControl *segment_;
7433 - (void) showDoneButton;
7434 - (void) resizeSegmentedControl;
7438 @implementation RoleController
7442 [container_ release];
7447 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7448 if ((self = [super init])) {
7449 database_ = database;
7450 roledelegate_ = delegate;
7452 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7454 NSArray *items = [NSArray arrayWithObjects:
7456 UCLocalize("HACKER"),
7457 UCLocalize("DEVELOPER"),
7459 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7460 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7461 [container_ addSubview:segment_];
7464 if ([Role_ isEqualToString:@"User"]) index = 0;
7465 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7466 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7468 [segment_ setSelectedSegmentIndex:index];
7469 [self showDoneButton];
7472 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7473 [self resizeSegmentedControl];
7475 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7476 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7477 [table_ setDelegate:self];
7478 [table_ setDataSource:self];
7479 [[self view] addSubview:table_];
7480 [table_ reloadData];
7484 - (void) resizeSegmentedControl {
7485 CGFloat width = [[self view] frame].size.width;
7486 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7489 - (void) viewWillAppear:(BOOL)animated {
7490 [super viewWillAppear:animated];
7492 [self resizeSegmentedControl];
7495 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7496 [self resizeSegmentedControl];
7499 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7500 [self resizeSegmentedControl];
7504 NSString *role(nil);
7506 switch ([segment_ selectedSegmentIndex]) {
7507 case 0: role = @"User"; break;
7508 case 1: role = @"Hacker"; break;
7509 case 2: role = @"Developer"; break;
7514 if (![role isEqualToString:Role_]) {
7515 bool rolling(Role_ == nil);
7518 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7522 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7527 [roledelegate_ loadData];
7529 [roledelegate_ updateData];
7533 - (void) segmentChanged:(UISegmentedControl *)control {
7534 [self showDoneButton];
7537 - (void) doneButtonClicked {
7539 [[self navigationController] dismissModalViewControllerAnimated:YES];
7542 - (void) showDoneButton {
7543 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7544 initWithTitle:UCLocalize("DONE")
7545 style:UIBarButtonItemStyleDone
7547 action:@selector(doneButtonClicked)
7549 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] == nil];
7550 [rightItem release];
7553 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7554 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7558 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7562 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7563 return nil; // This method is required by the protocol.
7566 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7568 return UCLocalize("ROLE_EX");
7570 return [NSString stringWithFormat:
7571 @"%@: %@\n%@: %@\n%@: %@",
7572 UCLocalize("USER"), UCLocalize("USER_EX"),
7573 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7574 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7579 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7580 if (section == 3) return 44.0f;
7584 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7585 if (section == 3) return container_;
7592 /* Cydia Container {{{ */
7593 @interface CYContainer : UIViewController <ProgressDelegate> {
7594 _transient Database *database_;
7595 RefreshBar *refreshbar_;
7600 UITabBarController *root_;
7603 - (void) setTabBarController:(UITabBarController *)controller;
7605 - (void) dropBar:(BOOL)animated;
7606 - (void) beginUpdate;
7607 - (void) raiseBar:(BOOL)animated;
7612 @implementation CYContainer
7614 - (BOOL) _reallyWantsFullScreenLayout {
7618 // NOTE: UIWindow only sends the top controller these messages,
7619 // So we have to forward them on.
7621 - (void) viewDidAppear:(BOOL)animated {
7622 [super viewDidAppear:animated];
7623 [root_ viewDidAppear:animated];
7626 - (void) viewWillAppear:(BOOL)animated {
7627 [super viewWillAppear:animated];
7628 [root_ viewWillAppear:animated];
7631 - (void) viewDidDisappear:(BOOL)animated {
7632 [super viewDidDisappear:animated];
7633 [root_ viewDidDisappear:animated];
7636 - (void) viewWillDisappear:(BOOL)animated {
7637 [super viewWillDisappear:animated];
7638 [root_ viewWillDisappear:animated];
7641 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7642 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7645 - (void) setTabBarController:(UITabBarController *)controller {
7647 [[self view] addSubview:[root_ view]];
7650 - (void) setUpdate:(NSDate *)date {
7654 - (void) beginUpdate {
7656 [refreshbar_ start];
7661 detachNewThreadSelector:@selector(performUpdate)
7667 - (void) performUpdate { _pooled
7669 status.setDelegate(self);
7670 [database_ updateWithStatus:status];
7673 performSelectorOnMainThread:@selector(completeUpdate)
7679 - (void) completeUpdate {
7682 [self raiseBar:YES];
7684 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7687 - (void) cancelUpdate {
7688 [refreshbar_ cancel];
7689 [self completeUpdate];
7692 - (void) cancelPressed {
7693 [self cancelUpdate];
7700 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7701 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7704 - (void) startProgress {
7707 - (void) setProgressTitle:(NSString *)title {
7709 performSelectorOnMainThread:@selector(_setProgressTitle:)
7715 - (bool) isCancelling:(size_t)received {
7719 - (void) setProgressPercent:(float)percent {
7721 performSelectorOnMainThread:@selector(_setProgressPercent:)
7722 withObject:[NSNumber numberWithFloat:percent]
7727 - (void) addProgressOutput:(NSString *)output {
7729 performSelectorOnMainThread:@selector(_addProgressOutput:)
7735 - (void) _setProgressTitle:(NSString *)title {
7736 [refreshbar_ setPrompt:title];
7739 - (void) _setProgressPercent:(NSNumber *)percent {
7740 [refreshbar_ setProgress:[percent floatValue]];
7743 - (void) _addProgressOutput:(NSString *)output {
7746 - (void) setUpdateDelegate:(id)delegate {
7747 updatedelegate_ = delegate;
7750 - (CGFloat) statusBarHeight {
7751 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7752 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7754 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7758 - (void) dropBar:(BOOL)animated {
7759 if (dropped_) return;
7762 [[self view] addSubview:refreshbar_];
7764 CGFloat sboffset = [self statusBarHeight];
7766 CGRect barframe = [refreshbar_ frame];
7767 barframe.origin.y = sboffset;
7768 [refreshbar_ setFrame:barframe];
7770 if (animated) [UIView beginAnimations:nil context:NULL];
7771 CGRect viewframe = [[root_ view] frame];
7772 viewframe.origin.y += barframe.size.height + sboffset;
7773 viewframe.size.height -= barframe.size.height + sboffset;
7774 [[root_ view] setFrame:viewframe];
7775 if (animated) [UIView commitAnimations];
7777 // Ensure bar has the proper width for our view, it might have changed
7778 barframe.size.width = viewframe.size.width;
7779 [refreshbar_ setFrame:barframe];
7781 // XXX: fix Apple's layout bug
7782 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7785 - (void) raiseBar:(BOOL)animated {
7786 if (!dropped_) return;
7789 [refreshbar_ removeFromSuperview];
7791 CGFloat sboffset = [self statusBarHeight];
7793 if (animated) [UIView beginAnimations:nil context:NULL];
7794 CGRect barframe = [refreshbar_ frame];
7795 CGRect viewframe = [[root_ view] frame];
7796 viewframe.origin.y -= barframe.size.height + sboffset;
7797 viewframe.size.height += barframe.size.height + sboffset;
7798 [[root_ view] setFrame:viewframe];
7799 if (animated) [UIView commitAnimations];
7801 // XXX: fix Apple's layout bug
7802 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7805 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7806 // XXX: fix Apple's layout bug
7807 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7810 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7816 // XXX: fix Apple's layout bug
7817 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7820 - (void) statusBarFrameChanged:(NSNotification *)notification {
7828 [refreshbar_ release];
7829 [[NSNotificationCenter defaultCenter] removeObserver:self];
7833 - (id) initWithDatabase:(Database *)database {
7834 if ((self = [super init]) != nil) {
7835 database_ = database;
7837 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7838 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7840 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7857 @interface Cydia : UIApplication <
7858 ConfirmationControllerDelegate,
7859 ProgressControllerDelegate,
7861 UINavigationControllerDelegate
7864 CYContainer *container_;
7868 NSMutableArray *essential_;
7869 NSMutableArray *broken_;
7871 Database *database_;
7875 UIKeyboard *keyboard_;
7876 UIProgressHUD *hud_;
7878 SectionsController *sections_;
7879 ChangesController *changes_;
7880 ManageController *manage_;
7881 SearchController *search_;
7882 SourceTable *sources_;
7883 InstalledController *installed_;
7889 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7890 - (void) setPage:(CYViewController *)page;
7895 static _finline void _setHomePage(Cydia *self) {
7896 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7899 @implementation Cydia
7901 - (void) beginUpdate {
7902 [container_ beginUpdate];
7906 return [container_ updating];
7909 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7914 if ([broken_ count] != 0) {
7915 int count = [broken_ count];
7917 UIAlertView *alert = [[[UIAlertView alloc]
7918 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7919 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7921 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7922 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
7925 [alert setContext:@"fixhalf"];
7927 } else if (!Ignored_ && [essential_ count] != 0) {
7928 int count = [essential_ count];
7930 UIAlertView *alert = [[[UIAlertView alloc]
7931 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7932 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
7934 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
7935 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
7938 [alert setContext:@"upgrade"];
7943 - (void) _saveConfig {
7946 NSString *error(nil);
7947 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7949 NSError *error(nil);
7950 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7951 NSLog(@"failure to save metadata data: %@", error);
7954 NSLog(@"failure to serialize metadata: %@", error);
7962 - (void) _updateData {
7965 /* XXX: this is just stupid */
7966 if (tag_ != 1 && sections_ != nil)
7967 [sections_ reloadData];
7968 if (tag_ != 2 && changes_ != nil)
7969 [changes_ reloadData];
7970 if (tag_ != 4 && search_ != nil)
7971 [search_ reloadData];
7973 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
7976 - (int)indexOfTabWithTag:(int)tag {
7978 for (UINavigationController *controller in [tabbar_ viewControllers]) {
7979 if ([[controller tabBarItem] tag] == tag) return i;
7986 - (void) _refreshIfPossible {
7987 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
7989 SCNetworkReachabilityFlags flags; {
7990 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
7991 SCNetworkReachabilityGetFlags(reachability, &flags);
7992 CFRelease(reachability);
7995 // XXX: this elaborate mess is what Apple is using to determine this? :(
7996 // XXX: do we care if the user has to intervene? maybe that's ok?
7998 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
7999 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8000 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8001 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8002 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8003 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8007 if (loaded_ || ManualRefresh || !reachable) loaded:
8008 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8012 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8014 if (update != nil) {
8015 NSTimeInterval interval([update timeIntervalSinceNow]);
8016 if (interval <= 0 && interval > -(15*60))
8020 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8026 - (void) refreshIfPossible {
8027 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8030 - (void) _reloadData {
8031 UIProgressHUD *hud([self addProgressHUD]);
8032 [hud setText:(loaded_ ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
8034 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8037 [self removeProgressHUD:hud];
8041 [essential_ removeAllObjects];
8042 [broken_ removeAllObjects];
8044 NSArray *packages([database_ packages]);
8045 for (Package *package in packages) {
8047 [broken_ addObject:package];
8048 if ([package upgradableAndEssential:NO]) {
8049 if ([package essential])
8050 [essential_ addObject:package];
8056 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8057 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:badge];
8058 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:YES];
8060 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8061 [self setApplicationBadge:badge];
8063 [self setApplicationBadgeString:badge];
8065 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:nil];
8066 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:NO];
8068 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8069 [self removeApplicationBadge];
8070 else // XXX: maybe use setApplicationBadgeString also?
8071 [self setApplicationIconBadgeNumber:0];
8076 [self refreshIfPossible];
8079 - (void) updateData {
8080 [database_ setVisible];
8089 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8090 _assert(file != NULL);
8092 for (NSString *key in [Sources_ allKeys]) {
8093 NSDictionary *source([Sources_ objectForKey:key]);
8095 fprintf(file, "%s %s %s\n",
8096 [[source objectForKey:@"Type"] UTF8String],
8097 [[source objectForKey:@"URI"] UTF8String],
8098 [[source objectForKey:@"Distribution"] UTF8String]
8106 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8107 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8108 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8109 [container_ presentModalViewController:navigation animated:YES];
8112 detachNewThreadSelector:@selector(update_)
8115 title:UCLocalize("UPDATING_SOURCES")
8119 - (void) reloadData {
8120 @synchronized (self) {
8126 pkgProblemResolver *resolver = [database_ resolver];
8128 resolver->InstallProtect();
8129 if (!resolver->Resolve(true))
8133 - (CGRect) popUpBounds {
8134 return [[tabbar_ view] bounds];
8138 if (![database_ prepare])
8141 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8142 [page setDelegate:self];
8143 CYNavigationController *confirm_ = [[CYNavigationController alloc] initWithRootViewController:page];
8144 [confirm_ setDelegate:self];
8146 if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8147 [container_ presentModalViewController:confirm_ animated:YES];
8153 @synchronized (self) {
8158 - (void) clearPackage:(Package *)package {
8159 @synchronized (self) {
8166 - (void) installPackages:(NSArray *)packages {
8167 @synchronized (self) {
8168 for (Package *package in packages)
8175 - (void) installPackage:(Package *)package {
8176 @synchronized (self) {
8183 - (void) removePackage:(Package *)package {
8184 @synchronized (self) {
8191 - (void) distUpgrade {
8192 @synchronized (self) {
8193 if (![database_ upgrade])
8200 @synchronized (self) {
8205 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8206 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8208 if (navigation != nil) {
8209 [navigation pushViewController:progress animated:YES];
8211 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8212 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8213 [container_ presentModalViewController:navigation animated:YES];
8217 detachNewThreadSelector:@selector(perform)
8220 title:UCLocalize("RUNNING")
8224 - (void) progressControllerIsComplete:(ProgressController *)progress {
8228 - (void) setPage:(CYViewController *)page {
8229 [page setDelegate:self];
8231 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8232 [navController setViewControllers:[NSArray arrayWithObject:page]];
8233 for (CYNavigationController *page in [tabbar_ viewControllers]) {
8234 if (page != navController) [page setViewControllers:nil];
8238 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8239 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8240 [browser loadURL:url];
8244 - (SectionsController *) sectionsController {
8245 if (sections_ == nil)
8246 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8250 - (ChangesController *) changesController {
8251 if (changes_ == nil)
8252 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8256 - (ManageController *) manageController {
8257 if (manage_ == nil) {
8258 manage_ = (ManageController *) [[self
8259 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8260 withClass:[ManageController class]
8262 if (!IsWildcat_) queueDelegate_ = manage_;
8267 - (SearchController *) searchController {
8269 search_ = [[SearchController alloc] initWithDatabase:database_];
8273 - (SourceTable *) sourcesController {
8274 if (sources_ == nil)
8275 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8279 - (InstalledController *) installedController {
8280 if (installed_ == nil) {
8281 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8282 if (IsWildcat_) queueDelegate_ = installed_;
8287 - (void) tabBarController:(id)tabBarController didSelectViewController:(UIViewController *)viewController {
8288 int tag = [[viewController tabBarItem] tag];
8290 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8292 } else if (tag_ == 1) {
8293 [[self sectionsController] resetView];
8297 case kCydiaTag: _setHomePage(self); break;
8299 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8300 case kChangesTag: [self setPage:[self changesController]]; break;
8301 case kManageTag: [self setPage:[self manageController]]; break;
8302 case kInstalledTag: [self setPage:[self installedController]]; break;
8303 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8304 case kSearchTag: [self setPage:[self searchController]]; break;
8312 - (void) showSettings {
8313 RoleController *role = [[RoleController alloc] initWithDatabase:database_ delegate:self];
8314 CYNavigationController *nav = [[CYNavigationController alloc] initWithRootViewController:role];
8315 if (IsWildcat_) [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8316 [container_ presentModalViewController:nav animated:YES];
8319 - (void) setPackageController:(PackageController *)view {
8321 [view setPackage:nil];
8325 - (PackageController *) _packageController {
8326 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8329 - (PackageController *) packageController {
8330 return [self _packageController];
8333 // Returns the navigation controller for the queuing badge.
8334 - (id) queueBadgeController {
8335 int index = [self indexOfTabWithTag:kManageTag];
8336 if (index == -1) index = [self indexOfTabWithTag:kInstalledTag];
8338 return [[tabbar_ viewControllers] objectAtIndex:index];
8341 - (void) cancelAndClear:(bool)clear {
8342 @synchronized (self) {
8345 pkgCacheFile &cache([database_ cache]);
8346 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
8347 // Unmark method taken from Synaptic Package Manager.
8348 // Thanks for being sane, unlike Aptitude.
8349 if (!cache[iterator].Keep()) {
8350 cache->MarkKeep(iterator, false);
8351 cache->SetReInstall(iterator, false);
8357 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
8361 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8364 // Show the changes in the current view.
8365 [(CYNavigationController *) [tabbar_ selectedViewController] reloadData];
8366 [queueDelegate_ queueStatusDidChange];
8370 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8371 NSString *context([alert context]);
8373 if ([context isEqualToString:@"fixhalf"]) {
8374 if (button == [alert firstOtherButtonIndex]) {
8375 @synchronized (self) {
8376 for (Package *broken in broken_) {
8379 NSString *id = [broken id];
8380 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8381 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8382 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8383 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8389 } else if (button == [alert cancelButtonIndex]) {
8390 [broken_ removeAllObjects];
8394 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8395 } else if ([context isEqualToString:@"upgrade"]) {
8396 if (button == [alert firstOtherButtonIndex]) {
8397 @synchronized (self) {
8398 for (Package *essential in essential_)
8399 [essential install];
8404 } else if (button == [alert firstOtherButtonIndex] + 1) {
8406 } else if (button == [alert cancelButtonIndex]) {
8410 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8414 - (void) system:(NSString *)command { _pooled
8415 system([command UTF8String]);
8418 - (void) applicationWillSuspend {
8420 [super applicationWillSuspend];
8423 - (void) applicationSuspend:(__GSEvent *)event {
8424 // FIXME: This needs to be fixed, but we no longer have a progress_.
8425 // What's the best solution?
8426 if (hud_ == nil)// && ![progress_ isRunning])
8427 [super applicationSuspend:event];
8430 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8432 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8435 - (void) _setSuspended:(BOOL)value {
8437 [super _setSuspended:value];
8440 - (UIProgressHUD *) addProgressHUD {
8441 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8442 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8444 [window_ setUserInteractionEnabled:NO];
8446 [[container_ view] addSubview:hud];
8450 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8452 [hud removeFromSuperview];
8453 [window_ setUserInteractionEnabled:YES];
8456 - (CYViewController *) pageForPackage:(NSString *)name {
8457 if (Package *package = [database_ packageWithName:name]) {
8458 PackageController *view([self packageController]);
8459 [view setPackage:package];
8462 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8463 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8464 return [self _pageForURL:url withClass:[CYBrowserController class]];
8468 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8472 NSString *href([url absoluteString]);
8473 if ([href hasPrefix:@"apptapp://package/"])
8474 return [self pageForPackage:[href substringFromIndex:18]];
8476 NSString *scheme([[url scheme] lowercaseString]);
8477 if (![scheme isEqualToString:@"cydia"])
8479 NSString *path([url absoluteString]);
8480 if ([path length] < 8)
8482 path = [path substringFromIndex:8];
8483 if (![path hasPrefix:@"/"])
8484 path = [@"/" stringByAppendingString:path];
8486 if ([path isEqualToString:@"/add-source"])
8487 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8488 else if ([path isEqualToString:@"/storage"])
8489 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8490 else if ([path isEqualToString:@"/sources"])
8491 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8492 else if ([path isEqualToString:@"/packages"])
8493 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8494 else if ([path hasPrefix:@"/url/"])
8495 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8496 else if ([path hasPrefix:@"/launch/"])
8497 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8498 else if ([path hasPrefix:@"/package-settings/"])
8499 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8500 else if ([path hasPrefix:@"/package-signature/"])
8501 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8502 else if ([path hasPrefix:@"/package/"])
8503 return [self pageForPackage:[path substringFromIndex:9]];
8504 else if ([path hasPrefix:@"/files/"]) {
8505 NSString *name = [path substringFromIndex:7];
8507 if (Package *package = [database_ packageWithName:name]) {
8508 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8509 [files setPackage:package];
8517 - (void) applicationOpenURL:(NSURL *)url {
8518 [super applicationOpenURL:url];
8520 if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
8521 [self setPage:page];
8523 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8527 - (void) applicationWillResignActive:(UIApplication *)application {
8528 // Stop refreshing if you get a phone call or lock the device.
8529 if ([container_ updating]) [container_ cancelUpdate];
8531 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8532 [super applicationWillResignActive:application];
8535 - (void) applicationDidFinishLaunching:(id)unused {
8536 [CYBrowserController _initialize];
8538 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8540 Font12_ = [[UIFont systemFontOfSize:12] retain];
8541 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8542 Font14_ = [[UIFont systemFontOfSize:14] retain];
8543 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8544 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8548 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8549 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8551 UIScreen *screen([UIScreen mainScreen]);
8553 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8554 [window_ orderFront:self];
8555 [window_ makeKey:self];
8556 [window_ setHidden:NO];
8558 database_ = [Database sharedInstance];
8560 NSMutableArray *items([NSMutableArray arrayWithObjects:
8561 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8562 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8563 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8564 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8568 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8569 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8571 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8574 NSMutableArray *controllers([NSMutableArray array]);
8576 for (UITabBarItem *item in items) {
8577 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8578 [controller setTabBarItem:item];
8579 [controllers addObject:controller];
8582 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8583 [tabbar_ setViewControllers:controllers];
8584 [tabbar_ setDelegate:self];
8585 [tabbar_ setSelectedIndex:0];
8587 container_ = [[CYContainer alloc] initWithDatabase:database_];
8588 [container_ setUpdateDelegate:self];
8589 [container_ setTabBarController:tabbar_];
8590 [window_ addSubview:[container_ view]];
8593 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8594 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8595 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8596 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8597 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8598 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8599 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8600 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8601 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8604 [self setIdleTimerDisabled:YES];
8606 hud_ = [self addProgressHUD];
8607 [hud_ setText:@"Reorganizing:\n\nWill Automatically\nClose When Done"];
8608 [self setStatusBarShowsProgress:YES];
8610 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8612 [self setStatusBarShowsProgress:NO];
8613 [self removeProgressHUD:hud_];
8616 if (ExecFork() == 0) {
8617 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8618 perror("launchctl stop");
8624 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8629 [self showSettings];
8633 [UIKeyboard initImplementationNow];
8642 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8643 if (item != nil && IsWildcat_) {
8644 [sheet showFromBarButtonItem:item animated:YES];
8646 [sheet showInView:window_];
8653 id Alloc_(id self, SEL selector) {
8654 id object = alloc_(self, selector);
8655 lprintf("[%s]A-%p\n", self->isa->name, object);
8660 id Dealloc_(id self, SEL selector) {
8661 id object = dealloc_(self, selector);
8662 lprintf("[%s]D-%p\n", self->isa->name, object);
8666 Class $WebDefaultUIKitDelegate;
8668 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8669 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8670 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8671 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8674 static NSNumber *shouldPlayKeyboardSounds;
8678 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8680 case 1104: // Keyboard Button Clicked
8681 case 1105: // Keyboard Delete Repeated
8682 if (shouldPlayKeyboardSounds == nil) {
8683 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8684 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8687 if (![shouldPlayKeyboardSounds boolValue])
8691 _UIHardware$_playSystemSound$(self, _cmd, sound);
8695 int main(int argc, char *argv[]) { _pooled
8698 if (Class $UIDevice = objc_getClass("UIDevice")) {
8699 UIDevice *device([$UIDevice currentDevice]);
8700 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8704 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8706 /* Library Hacks {{{ */
8707 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8709 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8710 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8711 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8712 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8713 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8716 $UIHardware = objc_getClass("UIHardware");
8717 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8718 if (UIHardware$_playSystemSound$ != NULL) {
8719 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8720 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8723 /* Set Locale {{{ */
8724 Locale_ = CFLocaleCopyCurrent();
8725 Languages_ = [NSLocale preferredLanguages];
8726 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8727 //NSLog(@"%@", [Languages_ description]);
8730 if (Languages_ == nil || [Languages_ count] == 0)
8731 // XXX: consider just setting to C and then falling through?
8734 lang = [[Languages_ objectAtIndex:0] UTF8String];
8735 setenv("LANG", lang, true);
8738 //std::setlocale(LC_ALL, lang);
8739 NSLog(@"Setting Language: %s", lang);
8742 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8744 /* Parse Arguments {{{ */
8745 bool substrate(false);
8751 for (int argi(1); argi != argc; ++argi)
8752 if (strcmp(argv[argi], "--") == 0) {
8754 argv[argi] = argv[0];
8760 for (int argi(1); argi != arge; ++argi)
8761 if (strcmp(args[argi], "--substrate") == 0)
8764 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8768 App_ = [[NSBundle mainBundle] bundlePath];
8769 Home_ = NSHomeDirectory();
8775 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8776 alloc_ = alloc->method_imp;
8777 alloc->method_imp = (IMP) &Alloc_;*/
8779 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8780 dealloc_ = dealloc->method_imp;
8781 dealloc->method_imp = (IMP) &Dealloc_;*/
8783 /* System Information {{{ */
8787 size = sizeof(maxproc);
8788 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8789 perror("sysctlbyname(\"kern.maxproc\", ?)");
8790 else if (maxproc < 64) {
8792 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8793 perror("sysctlbyname(\"kern.maxproc\", #)");
8796 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8797 char *osversion = new char[size];
8798 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8799 perror("sysctlbyname(\"kern.osversion\", ?)");
8801 System_ = [NSString stringWithUTF8String:osversion];
8803 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8804 char *machine = new char[size];
8805 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8806 perror("sysctlbyname(\"hw.machine\", ?)");
8810 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8811 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8812 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8813 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8817 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8818 NSData *data((NSData *) ecid);
8819 size_t length([data length]);
8820 uint8_t bytes[length];
8821 [data getBytes:bytes];
8822 char string[length * 2 + 1];
8823 for (size_t i(0); i != length; ++i)
8824 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8825 ChipID_ = [NSString stringWithUTF8String:string];
8829 IOObjectRelease(service);
8833 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8835 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8836 Build_ = [system objectForKey:@"ProductBuildVersion"];
8837 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8838 Product_ = [info objectForKey:@"SafariProductVersion"];
8839 Safari_ = [info objectForKey:@"CFBundleVersion"];
8842 /* Load Database {{{ */
8844 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8846 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8849 if (Metadata_ == NULL)
8850 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8852 Settings_ = [Metadata_ objectForKey:@"Settings"];
8854 Packages_ = [Metadata_ objectForKey:@"Packages"];
8855 Sections_ = [Metadata_ objectForKey:@"Sections"];
8856 Sources_ = [Metadata_ objectForKey:@"Sources"];
8858 Token_ = [Metadata_ objectForKey:@"Token"];
8861 if (Settings_ != nil)
8862 Role_ = [Settings_ objectForKey:@"Role"];
8864 if (Packages_ == nil) {
8865 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8866 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8869 if (Sections_ == nil) {
8870 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8871 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8874 if (Sources_ == nil) {
8875 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8876 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8880 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8882 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
8883 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
8884 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8885 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8886 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8887 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8889 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
8891 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8892 unlink("/tmp/.cydia.fw");
8894 } else if (access("/User", F_OK) != 0 || version < 2) {
8897 system("/usr/libexec/cydia/firmware.sh");
8901 _assert([[NSFileManager defaultManager]
8902 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8903 withIntermediateDirectories:YES
8908 if (access("/tmp/cydia.chk", F_OK) == 0) {
8909 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8910 _assert(errno == ENOENT);
8911 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8912 _assert(errno == ENOENT);
8915 /* APT Initialization {{{ */
8916 _assert(pkgInitConfig(*_config));
8917 _assert(pkgInitSystem(*_config, _system));
8920 _config->Set("APT::Acquire::Translation", lang);
8921 _config->Set("Acquire::http::Timeout", 15);
8922 _config->Set("Acquire::http::MaxParallel", 3);
8924 /* Color Choices {{{ */
8925 space_ = CGColorSpaceCreateDeviceRGB();
8927 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8928 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8929 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8930 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8931 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8932 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8933 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8934 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8935 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8937 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8938 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8940 /* UIKit Configuration {{{ */
8941 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8942 if ($GSFontSetUseLegacyFontMetrics != NULL)
8943 $GSFontSetUseLegacyFontMetrics(YES);
8945 // XXX: I have a feeling this was important
8946 //UIKeyboardDisableAutomaticAppearance();
8949 Colon_ = UCLocalize("COLON_DELIMITED");
8950 Error_ = UCLocalize("ERROR");
8951 Warning_ = UCLocalize("WARNING");
8954 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
8956 CGColorSpaceRelease(space_);