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 #define CYPoolStart() \
201 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
203 #define CYPoolEnd() \
207 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
209 void NSLogPoint(const char *fix, const CGPoint &point) {
210 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
213 void NSLogRect(const char *fix, const CGRect &rect) {
214 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
217 static _finline NSString *CydiaURL(NSString *path) {
219 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
220 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
221 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
222 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
223 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
224 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
227 static _finline void UpdateExternalStatus(uint64_t newStatus) {
229 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
230 notify_set_state(notify_token, newStatus);
231 notify_cancel(notify_token);
233 notify_post("com.saurik.Cydia.status");
236 /* [NSObject yieldToSelector:(withObject:)] {{{*/
237 @interface NSObject (Cydia)
238 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
239 - (id) yieldToSelector:(SEL)selector;
242 @implementation NSObject (Cydia)
247 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
248 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
249 id object([[context objectAtIndex:1] nonretainedObjectValue]);
250 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
252 /* XXX: deal with exceptions */
253 id value([self performSelector:selector withObject:object]);
255 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
256 [context removeAllObjects];
257 if ([signature methodReturnLength] != 0 && value != nil)
258 [context addObject:value];
263 performSelectorOnMainThread:@selector(doNothing)
269 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
270 /*return [self performSelector:selector withObject:object];*/
272 volatile bool stopped(false);
274 NSMutableArray *context([NSMutableArray arrayWithObjects:
275 [NSValue valueWithPointer:selector],
276 [NSValue valueWithNonretainedObject:object],
277 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
280 NSThread *thread([[[NSThread alloc]
282 selector:@selector(_yieldToContext:)
288 NSRunLoop *loop([NSRunLoop currentRunLoop]);
289 NSDate *future([NSDate distantFuture]);
291 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
293 return [context count] == 0 ? nil : [context objectAtIndex:0];
296 - (id) yieldToSelector:(SEL)selector {
297 return [self yieldToSelector:selector withObject:nil];
303 /* Cydia Action Sheet {{{ */
304 @interface CYActionSheet : UIAlertView {
308 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
311 @implementation CYActionSheet
313 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
314 if ((self = [super init])) {
315 [self setTitle:title];
316 [self setDelegate:self];
317 for (NSString *button in buttons) [self addButtonWithTitle:button];
318 [self setCancelButtonIndex:index];
322 - (void) _updateFrameForDisplay {
323 [super _updateFrameForDisplay];
324 if ([self cancelButtonIndex] == -1) {
325 NSArray *buttons = [self buttons];
326 if ([buttons count]) {
327 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
328 for (UIThreePartButton *button in buttons)
329 [button setBackground:background forState:0];
334 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
335 button_ = buttonIndex + 1;
339 [self dismissWithClickedButtonIndex:-1 animated:YES];
342 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
343 [self setRunsModal:YES];
352 /* NSForcedOrderingSearch doesn't work on the iPhone */
353 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
354 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
355 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
357 /* Information Dictionaries {{{ */
358 @interface NSMutableArray (Cydia)
359 - (void) addInfoDictionary:(NSDictionary *)info;
362 @implementation NSMutableArray (Cydia)
364 - (void) addInfoDictionary:(NSDictionary *)info {
365 [self addObject:info];
370 @interface NSMutableDictionary (Cydia)
371 - (void) addInfoDictionary:(NSDictionary *)info;
374 @implementation NSMutableDictionary (Cydia)
376 - (void) addInfoDictionary:(NSDictionary *)info {
377 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
383 #define lprintf(args...) fprintf(stderr, args)
386 #define TraceLogging (1 && !ForRelease)
387 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
388 #define ProfileTimes (0 && !ForRelease)
389 #define ForSaurik (0 && !ForRelease)
390 #define LogBrowser (0 && !ForRelease)
391 #define TrackResize (0 && !ForRelease)
392 #define ManualRefresh (1 && !ForRelease)
393 #define ShowInternals (0 && !ForRelease)
394 #define IgnoreInstall (0 && !ForRelease)
395 #define AlwaysReload (0 && !ForRelease)
399 #define _trace(args...)
404 #define _profile(name) {
407 #define PrintTimes() do {} while (false)
411 typedef uint32_t (*SKRadixFunction)(id, void *);
413 @interface NSMutableArray (Radix)
414 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
422 @implementation NSMutableArray (Radix)
424 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
425 size_t count([self count]);
426 struct RadixItem_ *swap(new RadixItem_[count * 2]);
428 for (size_t i(0); i != count; ++i) {
429 RadixItem_ &item(swap[i]);
432 id object([self objectAtIndex:i]);
433 item.key = function(object, argument);
436 struct RadixItem_ *lhs(swap), *rhs(swap + count);
438 static const size_t width = 32;
439 static const size_t bits = 11;
440 static const size_t slots = 1 << bits;
441 static const size_t passes = (width + (bits - 1)) / bits;
443 size_t *hist(new size_t[slots]);
445 for (size_t pass(0); pass != passes; ++pass) {
446 memset(hist, 0, sizeof(size_t) * slots);
448 for (size_t i(0); i != count; ++i) {
449 uint32_t key(lhs[i].key);
451 key &= _not(uint32_t) >> width - bits;
456 for (size_t i(0); i != slots; ++i) {
457 size_t local(offset);
462 for (size_t i(0); i != count; ++i) {
463 uint32_t key(lhs[i].key);
465 key &= _not(uint32_t) >> width - bits;
466 rhs[hist[key]++] = lhs[i];
469 RadixItem_ *tmp(lhs);
476 const void **values(new const void *[count]);
477 for (size_t i(0); i != count; ++i)
478 values[i] = [self objectAtIndex:lhs[i].index];
479 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
487 /* Insertion Sort {{{ */
489 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
490 const char *ptr = (const char *)list;
492 CFIndex half = count / 2;
493 const char *probe = ptr + elementSize * half;
494 CFComparisonResult cr = comparator(element, probe, context);
495 if (0 == cr) return (probe - (const char *)list) / elementSize;
496 ptr = (cr < 0) ? ptr : probe + elementSize;
497 count = (cr < 0) ? half : (half + (count & 1) - 1);
499 return (ptr - (const char *)list) / elementSize;
502 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
503 const char *ptr = (const char *)list;
505 CFIndex half = count / 2;
506 const char *probe = ptr + elementSize * half;
507 CFComparisonResult cr = comparator(element, probe, context);
508 if (0 == cr) return (probe - (const char *)list) / elementSize;
509 ptr = (cr < 0) ? ptr : probe + elementSize;
510 count = (cr < 0) ? half : (half + (count & 1) - 1);
512 return (ptr - (const char *)list) / elementSize;
515 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
516 if (range.length == 0)
518 const void **values(new const void *[range.length]);
519 CFArrayGetValues(array, range, values);
521 #if HistogramInsertionSort > 0
522 uint32_t total(0), *offsets(new uint32_t[range.length]);
525 for (CFIndex index(1); index != range.length; ++index) {
526 const void *value(values[index]);
527 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
528 CFIndex correct(index);
529 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
530 #if HistogramInsertionSort > 1
531 NSLog(@"%@ < %@", value, values[correct - 1]);
536 if (correct != index) {
537 size_t offset(index - correct);
538 #if HistogramInsertionSort
542 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
544 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
545 values[correct] = value;
549 CFArrayReplaceValues(array, range, values, range.length);
552 #if HistogramInsertionSort > 0
553 for (CFIndex index(0); index != range.length; ++index)
554 if (offsets[index] != 0)
555 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
556 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
563 /* Apple Bug Fixes {{{ */
564 @implementation UIWebDocumentView (Cydia)
566 - (void) _setScrollerOffset:(CGPoint)offset {
567 UIScroller *scroller([self _scroller]);
569 CGSize size([scroller contentSize]);
570 CGSize bounds([scroller bounds].size);
573 max.x = size.width - bounds.width;
574 max.y = size.height - bounds.height;
582 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
583 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
585 [scroller setOffset:offset];
591 @implementation WebScriptObject (NSFastEnumeration)
593 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
594 size_t length([self count] - state->state);
597 else if (length > count)
599 for (size_t i(0); i != length; ++i)
600 objects[i] = [self objectAtIndex:state->state++];
601 state->itemsPtr = objects;
602 state->mutationsPtr = (unsigned long *) self;
608 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
609 size_t length([self length] - state->state);
612 else if (length > count)
614 for (size_t i(0); i != length; ++i)
615 objects[i] = [self item:state->state++];
616 state->itemsPtr = objects;
617 state->mutationsPtr = (unsigned long *) self;
621 /* Cydia NSString Additions {{{ */
622 @interface NSString (Cydia)
623 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
624 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
625 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
626 - (NSComparisonResult) compareByPath:(NSString *)other;
627 - (NSString *) stringByCachingURLWithCurrentCDN;
628 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
631 @implementation NSString (Cydia)
633 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
634 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
637 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
638 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
639 memcpy(data, bytes, length);
640 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
643 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
644 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
647 - (NSComparisonResult) compareByPath:(NSString *)other {
648 NSString *prefix = [self commonPrefixWithString:other options:0];
649 size_t length = [prefix length];
651 NSRange lrange = NSMakeRange(length, [self length] - length);
652 NSRange rrange = NSMakeRange(length, [other length] - length);
654 lrange = [self rangeOfString:@"/" options:0 range:lrange];
655 rrange = [other rangeOfString:@"/" options:0 range:rrange];
657 NSComparisonResult value;
659 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
660 value = NSOrderedSame;
661 else if (lrange.location == NSNotFound)
662 value = NSOrderedAscending;
663 else if (rrange.location == NSNotFound)
664 value = NSOrderedDescending;
666 value = NSOrderedSame;
668 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
669 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
670 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
671 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
673 NSComparisonResult result = [lpath compare:rpath];
674 return result == NSOrderedSame ? value : result;
677 - (NSString *) stringByCachingURLWithCurrentCDN {
679 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
680 withString:@"://cache.cydia.saurik.com/"
684 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
685 return [(id)CFURLCreateStringByAddingPercentEscapes(
690 kCFStringEncodingUTF8
697 /* C++ NSString Wrapper Cache {{{ */
698 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
699 return size == 0 ? NULL :
700 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
701 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
704 static _finline CFStringRef CYStringCreate(const char *data) {
705 return CYStringCreate(data, strlen(data));
714 _finline void clear_() {
715 if (cache_ != NULL) {
722 _finline bool empty() const {
726 _finline size_t size() const {
730 _finline char *data() const {
734 _finline void clear() {
739 _finline CYString() :
746 _finline ~CYString() {
750 void operator =(const CYString &rhs) {
754 if (rhs.cache_ == nil)
757 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
760 void set(apr_pool_t *pool, const char *data, size_t size) {
766 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
767 memcpy(temp, data, size);
774 _finline void set(apr_pool_t *pool, const char *data) {
775 set(pool, data, data == NULL ? 0 : strlen(data));
778 _finline void set(apr_pool_t *pool, const std::string &rhs) {
779 set(pool, rhs.data(), rhs.size());
782 bool operator ==(const CYString &rhs) const {
783 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
786 _finline operator CFStringRef() {
788 cache_ = CYStringCreate(data_, size_);
792 _finline operator id() {
793 return (NSString *) static_cast<CFStringRef>(*this);
797 /* C++ NSString Algorithm Adapters {{{ */
799 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
802 struct NSStringMapHash :
803 std::unary_function<NSString *, size_t>
805 _finline size_t operator ()(NSString *value) const {
806 return CFStringHashNSString((CFStringRef) value);
810 struct NSStringMapLess :
811 std::binary_function<NSString *, NSString *, bool>
813 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
814 return [lhs compare:rhs] == NSOrderedAscending;
818 struct NSStringMapEqual :
819 std::binary_function<NSString *, NSString *, bool>
821 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
822 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
823 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
824 //[lhs isEqualToString:rhs];
829 /* Perl-Compatible RegEx {{{ */
839 Pcre(const char *regex) :
844 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
847 lprintf("%d:%s\n", offset, error);
851 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
852 matches_ = new int[(capture_ + 1) * 3];
860 NSString *operator [](size_t match) {
861 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
864 bool operator ()(NSString *data) {
865 // XXX: length is for characters, not for bytes
866 return operator ()([data UTF8String], [data length]);
869 bool operator ()(const char *data, size_t size) {
871 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
875 /* Mime Addresses {{{ */
876 @interface Address : NSObject {
882 - (NSString *) address;
884 - (void) setAddress:(NSString *)address;
886 + (Address *) addressWithString:(NSString *)string;
887 - (Address *) initWithString:(NSString *)string;
890 @implementation Address
899 - (NSString *) name {
903 - (NSString *) address {
907 - (void) setAddress:(NSString *)address {
909 [address_ autorelease];
913 address_ = [address retain];
916 + (Address *) addressWithString:(NSString *)string {
917 return [[[Address alloc] initWithString:string] autorelease];
920 + (NSArray *) _attributeKeys {
921 return [NSArray arrayWithObjects:@"address", @"name", nil];
924 - (NSArray *) attributeKeys {
925 return [[self class] _attributeKeys];
928 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
929 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
932 - (Address *) initWithString:(NSString *)string {
933 if ((self = [super init]) != nil) {
934 const char *data = [string UTF8String];
935 size_t size = [string length];
937 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
939 if (address_r(data, size)) {
940 name_ = [address_r[1] retain];
941 address_ = [address_r[2] retain];
943 name_ = [string retain];
951 /* CoreGraphics Primitives {{{ */
962 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
965 Set(space, red, green, blue, alpha);
970 CGColorRelease(color_);
977 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
979 float color[] = {red, green, blue, alpha};
980 color_ = CGColorCreate(space, (CGFloat *) color);
983 operator CGColorRef() {
989 /* Random Global Variables {{{ */
990 static const int PulseInterval_ = 50000;
991 static const int ButtonBarWidth_ = 60;
992 static const int ButtonBarHeight_ = 48;
993 static const float KeyboardTime_ = 0.3f;
996 static NSArray *Finishes_;
998 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
999 #define NotifyConfig_ "/etc/notify.conf"
1001 static bool Queuing_;
1003 static CYColor Blue_;
1004 static CYColor Blueish_;
1005 static CYColor Black_;
1006 static CYColor Off_;
1007 static CYColor White_;
1008 static CYColor Gray_;
1009 static CYColor Green_;
1010 static CYColor Purple_;
1011 static CYColor Purplish_;
1013 static UIColor *InstallingColor_;
1014 static UIColor *RemovingColor_;
1016 static NSString *App_;
1017 static NSString *Home_;
1019 static BOOL Advanced_;
1020 static BOOL Ignored_;
1022 static UIFont *Font12_;
1023 static UIFont *Font12Bold_;
1024 static UIFont *Font14_;
1025 static UIFont *Font18Bold_;
1026 static UIFont *Font22Bold_;
1028 static const char *Machine_ = NULL;
1029 static NSString *System_ = nil;
1030 static NSString *SerialNumber_ = nil;
1031 static NSString *ChipID_ = nil;
1032 static NSString *Token_ = nil;
1033 static NSString *UniqueID_ = nil;
1034 static NSString *PLMN_ = nil;
1035 static NSString *Build_ = nil;
1036 static NSString *Product_ = nil;
1037 static NSString *Safari_ = nil;
1039 static CFLocaleRef Locale_;
1040 static NSArray *Languages_;
1041 static CGColorSpaceRef space_;
1043 static NSDictionary *SectionMap_;
1044 static NSMutableDictionary *Metadata_;
1045 static _transient NSMutableDictionary *Settings_;
1046 static _transient NSString *Role_;
1047 static _transient NSMutableDictionary *Packages_;
1048 static _transient NSMutableDictionary *Sections_;
1049 static _transient NSMutableDictionary *Sources_;
1050 static bool Changed_;
1051 static NSDate *now_;
1053 static bool IsWildcat_;
1056 /* Display Helpers {{{ */
1057 inline float Interpolate(float begin, float end, float fraction) {
1058 return (end - begin) * fraction + begin;
1061 /* XXX: localize this! */
1062 NSString *SizeString(double size) {
1063 bool negative = size < 0;
1068 while (size > 1024) {
1073 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1075 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1078 const char *StripVersion_(const char *version) {
1079 const char *colon(strchr(version, ':'));
1081 version = colon + 1;
1085 CFStringRef StripVersion(const char *version) {
1086 const char *colon(strchr(version, ':'));
1088 version = colon + 1;
1089 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1091 return CYStringCreate(version);
1094 NSString *LocalizeSection(NSString *section) {
1095 static Pcre title_r("^(.*?) \\((.*)\\)$");
1096 if (title_r(section)) {
1097 NSString *parent(title_r[1]);
1098 NSString *child(title_r[2]);
1100 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1101 LocalizeSection(parent),
1102 LocalizeSection(child)
1106 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1109 NSString *Simplify(NSString *title) {
1110 const char *data = [title UTF8String];
1111 size_t size = [title length];
1113 static Pcre square_r("^\\[(.*)\\]$");
1114 if (square_r(data, size))
1115 return Simplify(square_r[1]);
1117 static Pcre paren_r("^\\((.*)\\)$");
1118 if (paren_r(data, size))
1119 return Simplify(paren_r[1]);
1121 static Pcre title_r("^(.*?) \\((.*)\\)$");
1122 if (title_r(data, size))
1123 return Simplify(title_r[1]);
1129 NSString *GetLastUpdate() {
1130 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1133 return UCLocalize("NEVER_OR_UNKNOWN");
1135 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1136 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1138 CFRelease(formatter);
1140 return [(NSString *) formatted autorelease];
1143 bool isSectionVisible(NSString *section) {
1144 NSDictionary *metadata([Sections_ objectForKey:section]);
1145 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1146 return hidden == nil || ![hidden boolValue];
1151 /* Delegate Prototypes {{{ */
1155 @interface NSObject (ProgressDelegate)
1158 @protocol ProgressDelegate
1159 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1160 - (void) setProgressTitle:(NSString *)title;
1161 - (void) setProgressPercent:(float)percent;
1162 - (void) startProgress;
1163 - (void) addProgressOutput:(NSString *)output;
1164 - (bool) isCancelling:(size_t)received;
1167 @protocol ConfigurationDelegate
1168 - (void) repairWithSelector:(SEL)selector;
1169 - (void) setConfigurationData:(NSString *)data;
1172 @class PackageController;
1174 @protocol CydiaDelegate
1175 - (void) setPackageController:(PackageController *)view;
1176 - (void) clearPackage:(Package *)package;
1177 - (void) installPackage:(Package *)package;
1178 - (void) installPackages:(NSArray *)packages;
1179 - (void) removePackage:(Package *)package;
1180 - (void) beginUpdate;
1182 - (void) distUpgrade;
1184 - (void) updateData;
1186 - (void) showSettings;
1187 - (UIProgressHUD *) addProgressHUD;
1188 - (BOOL) hudIsShowing;
1189 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1190 - (CYViewController *) pageForPackage:(NSString *)name;
1191 - (PackageController *) packageController;
1192 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1196 /* Status Delegation {{{ */
1198 public pkgAcquireStatus
1201 _transient NSObject<ProgressDelegate> *delegate_;
1209 void setDelegate(id delegate) {
1210 delegate_ = delegate;
1213 NSObject<ProgressDelegate> *getDelegate() const {
1217 virtual bool MediaChange(std::string media, std::string drive) {
1221 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1224 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1225 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1226 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1229 virtual void Done(pkgAcquire::ItemDesc &item) {
1232 virtual void Fail(pkgAcquire::ItemDesc &item) {
1234 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1235 item.Owner->Status == pkgAcquire::Item::StatDone
1239 std::string &error(item.Owner->ErrorText);
1243 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1244 NSArray *fields([description componentsSeparatedByString:@" "]);
1245 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1247 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1248 withObject:[NSArray arrayWithObjects:
1249 [NSString stringWithUTF8String:error.c_str()],
1256 virtual bool Pulse(pkgAcquire *Owner) {
1257 bool value = pkgAcquireStatus::Pulse(Owner);
1260 double(CurrentBytes + CurrentItems) /
1261 double(TotalBytes + TotalItems)
1264 [delegate_ setProgressPercent:percent];
1265 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1268 virtual void Start() {
1269 [delegate_ startProgress];
1272 virtual void Stop() {
1276 /* Progress Delegation {{{ */
1281 _transient id<ProgressDelegate> delegate_;
1285 virtual void Update() {
1286 /*if (abs(Percent - percent_) > 2)
1287 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1291 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1292 [delegate_ setProgressPercent:(Percent / 100)];*/
1302 void setDelegate(id delegate) {
1303 delegate_ = delegate;
1306 id getDelegate() const {
1310 virtual void Done() {
1312 //[delegate_ setProgressPercent:1];
1317 /* Database Interface {{{ */
1318 typedef std::map< unsigned long, _H<Source> > SourceMap;
1320 @interface Database : NSObject {
1326 pkgCacheFile cache_;
1327 pkgDepCache::Policy *policy_;
1328 pkgRecords *records_;
1329 pkgProblemResolver *resolver_;
1330 pkgAcquire *fetcher_;
1332 SPtr<pkgPackageManager> manager_;
1333 pkgSourceList *list_;
1336 CFMutableArrayRef packages_;
1338 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1347 + (Database *) sharedInstance;
1350 - (void) _readCydia:(NSNumber *)fd;
1351 - (void) _readStatus:(NSNumber *)fd;
1352 - (void) _readOutput:(NSNumber *)fd;
1356 - (Package *) packageWithName:(NSString *)name;
1358 - (pkgCacheFile &) cache;
1359 - (pkgDepCache::Policy *) policy;
1360 - (pkgRecords *) records;
1361 - (pkgProblemResolver *) resolver;
1362 - (pkgAcquire &) fetcher;
1363 - (pkgSourceList &) list;
1364 - (NSArray *) packages;
1365 - (NSArray *) sources;
1366 - (void) reloadData;
1374 - (void) setVisible;
1376 - (void) updateWithStatus:(Status &)status;
1378 - (void) setDelegate:(id)delegate;
1379 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1382 /* Delegate Helpers {{{ */
1383 @implementation NSObject (ProgressDelegate)
1385 - (void) _setProgressErrorPackage:(NSArray *)args {
1386 [self performSelector:@selector(setProgressError:forPackage:)
1387 withObject:[args objectAtIndex:0]
1388 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1392 - (void) _setProgressErrorTitle:(NSArray *)args {
1393 [self performSelector:@selector(setProgressError:withTitle:)
1394 withObject:[args objectAtIndex:0]
1395 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1399 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1400 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1401 withObject:[NSArray arrayWithObjects:error, title, nil]
1406 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1407 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1409 [self performSelector:@selector(setProgressError:withTitle:)
1411 withObject:(package == nil ? id : [package name])
1418 /* Source Class {{{ */
1419 @interface Source : NSObject {
1420 CYString depiction_;
1421 CYString description_;
1427 CYString distribution_;
1432 NSString *authority_;
1434 CYString defaultIcon_;
1436 NSDictionary *record_;
1440 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1442 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1444 - (NSString *) depictionForPackage:(NSString *)package;
1445 - (NSString *) supportForPackage:(NSString *)package;
1447 - (NSDictionary *) record;
1451 - (NSString *) distribution;
1452 - (NSString *) type;
1454 - (NSString *) host;
1456 - (NSString *) name;
1457 - (NSString *) description;
1458 - (NSString *) label;
1459 - (NSString *) origin;
1460 - (NSString *) version;
1462 - (NSString *) defaultIcon;
1466 @implementation Source
1470 distribution_.clear();
1473 description_.clear();
1479 defaultIcon_.clear();
1481 if (record_ != nil) {
1491 if (authority_ != nil) {
1492 [authority_ release];
1502 + (NSArray *) _attributeKeys {
1503 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1506 - (NSArray *) attributeKeys {
1507 return [[self class] _attributeKeys];
1510 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1511 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1514 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1517 trusted_ = index->IsTrusted();
1519 uri_.set(pool, index->GetURI());
1520 distribution_.set(pool, index->GetDist());
1521 type_.set(pool, index->GetType());
1523 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1524 if (dindex != NULL) {
1526 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1529 pkgTagFile tags(&fd);
1531 pkgTagSection section;
1538 {"default-icon", &defaultIcon_},
1539 {"depiction", &depiction_},
1540 {"description", &description_},
1542 {"origin", &origin_},
1543 {"support", &support_},
1544 {"version", &version_},
1547 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1548 const char *start, *end;
1550 if (section.Find(names[i].name_, start, end)) {
1551 CYString &value(*names[i].value_);
1552 value.set(pool, start, end - start);
1558 record_ = [Sources_ objectForKey:[self key]];
1560 record_ = [record_ retain];
1562 NSURL *url([NSURL URLWithString:uri_]);
1566 host_ = [[host_ lowercaseString] retain];
1571 authority_ = [url path];
1573 if (authority_ != nil)
1574 authority_ = [authority_ retain];
1577 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1578 if ((self = [super init]) != nil) {
1579 [self setMetaIndex:index inPool:pool];
1583 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1584 NSDictionary *lhr = [self record];
1585 NSDictionary *rhr = [source record];
1588 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1590 NSString *lhs = [self name];
1591 NSString *rhs = [source name];
1593 if ([lhs length] != 0 && [rhs length] != 0) {
1594 unichar lhc = [lhs characterAtIndex:0];
1595 unichar rhc = [rhs characterAtIndex:0];
1597 if (isalpha(lhc) && !isalpha(rhc))
1598 return NSOrderedAscending;
1599 else if (!isalpha(lhc) && isalpha(rhc))
1600 return NSOrderedDescending;
1603 return [lhs compare:rhs options:LaxCompareOptions_];
1606 - (NSString *) depictionForPackage:(NSString *)package {
1607 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1610 - (NSString *) supportForPackage:(NSString *)package {
1611 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1614 - (NSDictionary *) record {
1622 - (NSString *) uri {
1626 - (NSString *) distribution {
1627 return distribution_;
1630 - (NSString *) type {
1634 - (NSString *) key {
1635 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1638 - (NSString *) host {
1642 - (NSString *) name {
1643 return origin_.empty() ? authority_ : origin_;
1646 - (NSString *) description {
1647 return description_;
1650 - (NSString *) label {
1651 return label_.empty() ? authority_ : label_;
1654 - (NSString *) origin {
1658 - (NSString *) version {
1662 - (NSString *) defaultIcon {
1663 return defaultIcon_;
1668 /* Relationship Class {{{ */
1669 @interface Relationship : NSObject {
1674 - (NSString *) type;
1676 - (NSString *) name;
1680 @implementation Relationship
1688 - (NSString *) type {
1696 - (NSString *) name {
1703 /* Package Class {{{ */
1704 @interface Package : NSObject {
1708 pkgCache::VerIterator version_;
1709 pkgCache::PkgIterator iterator_;
1710 _transient Database *database_;
1711 pkgCache::VerFileIterator file_;
1718 NSString *section$_;
1725 CYString installed_;
1731 CYString depiction_;
1742 NSMutableArray *tags_;
1745 NSArray *relationships_;
1747 NSMutableDictionary *metadata_;
1748 _transient NSDate *firstSeen_;
1749 _transient NSDate *lastSeen_;
1753 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1754 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1756 - (pkgCache::PkgIterator) iterator;
1759 - (NSString *) section;
1760 - (NSString *) simpleSection;
1762 - (NSString *) longSection;
1763 - (NSString *) shortSection;
1767 - (Address *) maintainer;
1769 - (NSString *) longDescription;
1770 - (NSString *) shortDescription;
1773 - (NSMutableDictionary *) metadata;
1775 - (BOOL) subscribed;
1778 - (NSString *) latest;
1779 - (NSString *) installed;
1780 - (BOOL) uninstalled;
1783 - (BOOL) upgradableAndEssential:(BOOL)essential;
1786 - (BOOL) unfiltered;
1790 - (BOOL) halfConfigured;
1791 - (BOOL) halfInstalled;
1793 - (NSString *) mode;
1795 - (void) setVisible;
1798 - (NSString *) name;
1800 - (NSString *) homepage;
1801 - (NSString *) depiction;
1802 - (Address *) author;
1804 - (NSString *) support;
1806 - (NSArray *) files;
1807 - (NSArray *) relationships;
1808 - (NSArray *) warnings;
1809 - (NSArray *) applications;
1811 - (Source *) source;
1812 - (NSString *) role;
1814 - (BOOL) matches:(NSString *)text;
1816 - (bool) hasSupportingRole;
1817 - (BOOL) hasTag:(NSString *)tag;
1818 - (NSString *) primaryPurpose;
1819 - (NSArray *) purposes;
1820 - (bool) isCommercial;
1822 - (CYString &) cyname;
1824 - (uint32_t) compareBySection:(NSArray *)sections;
1826 - (uint32_t) compareForChanges;
1831 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1832 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1833 - (bool) isInstalledAndVisible:(NSNumber *)number;
1834 - (bool) isVisibleInSection:(NSString *)section;
1835 - (bool) isVisibleInSource:(Source *)source;
1839 uint32_t PackageChangesRadix(Package *self, void *) {
1844 uint32_t timestamp : 30;
1845 uint32_t ignored : 1;
1846 uint32_t upgradable : 1;
1850 bool upgradable([self upgradableAndEssential:YES]);
1851 value.bits.upgradable = upgradable ? 1 : 0;
1854 value.bits.timestamp = 0;
1855 value.bits.ignored = [self ignored] ? 0 : 1;
1856 value.bits.upgradable = 1;
1858 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1859 value.bits.ignored = 0;
1860 value.bits.upgradable = 0;
1863 return _not(uint32_t) - value.key;
1866 _finline static void Stifle(uint8_t &value) {
1869 uint32_t PackagePrefixRadix(Package *self, void *context) {
1870 size_t offset(reinterpret_cast<size_t>(context));
1871 CYString &name([self cyname]);
1873 size_t size(name.size());
1876 char *text(name.data());
1879 if (!isdigit(text[0]))
1883 while (size != digits && isdigit(text[digits]))
1893 if (offset == 0 && zeros != 0) {
1894 memset(data, '0', zeros);
1895 memcpy(data + zeros, text, 4 - zeros);
1897 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1898 if (size <= offset - zeros)
1901 text += offset - zeros;
1902 size -= offset - zeros;
1905 memcpy(data, text, 4);
1907 memcpy(data, text, size);
1908 memset(data + size, 0, 4 - size);
1911 for (size_t i(0); i != 4; ++i)
1912 if (isalpha(data[i]))
1920 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1922 /* XXX: ntohl may be more honest */
1923 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1926 CYString &(*PackageName)(Package *self, SEL sel);
1928 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1929 _profile(PackageNameCompare)
1930 CYString &lhi(PackageName(lhs, @selector(cyname)));
1931 CYString &rhi(PackageName(rhs, @selector(cyname)));
1932 CFStringRef lhn(lhi), rhn(rhi);
1935 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1936 else if (rhn == NULL)
1937 return NSOrderedDescending;
1939 _profile(PackageNameCompare$NumbersLast)
1940 if (!lhi.empty() && !rhi.empty()) {
1941 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1942 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1943 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1944 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1945 return lha ? NSOrderedAscending : NSOrderedDescending;
1949 CFIndex length = CFStringGetLength(lhn);
1951 _profile(PackageNameCompare$Compare)
1952 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1957 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1958 return PackageNameCompare(*lhs, *rhs, context);
1961 struct PackageNameOrdering :
1962 std::binary_function<Package *, Package *, bool>
1964 _finline bool operator ()(Package *lhs, Package *rhs) const {
1965 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1969 @implementation Package
1971 - (NSString *) description {
1972 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1982 if (sponsor$_ != nil)
1983 [sponsor$_ release];
1984 if (author$_ != nil)
1991 if (relationships_ != nil)
1992 [relationships_ release];
1993 if (metadata_ != nil)
1994 [metadata_ release];
1999 + (NSString *) webScriptNameForSelector:(SEL)selector {
2000 if (selector == @selector(hasTag:))
2006 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2007 return [self webScriptNameForSelector:selector] == nil;
2010 + (NSArray *) _attributeKeys {
2011 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];
2014 - (NSArray *) attributeKeys {
2015 return [[self class] _attributeKeys];
2018 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2019 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2029 _profile(Package$parse)
2030 pkgRecords::Parser *parser;
2032 _profile(Package$parse$Lookup)
2033 parser = &[database_ records]->Lookup(file_);
2038 _profile(Package$parse$Find)
2044 {"depiction", &depiction_},
2045 {"homepage", &homepage_},
2046 {"website", &website},
2048 {"support", &support_},
2049 {"sponsor", &sponsor_},
2050 {"author", &author_},
2053 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2054 const char *start, *end;
2056 if (parser->Find(names[i].name_, start, end)) {
2057 CYString &value(*names[i].value_);
2058 _profile(Package$parse$Value)
2059 value.set(pool_, start, end - start);
2065 _profile(Package$parse$Tagline)
2066 const char *start, *end;
2067 if (parser->ShortDesc(start, end)) {
2068 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2071 while (stop != start && stop[-1] == '\r')
2073 tagline_.set(pool_, start, stop - start);
2077 _profile(Package$parse$Retain)
2078 if (homepage_.empty())
2079 homepage_ = website;
2080 if (homepage_ == depiction_)
2086 - (void) setVisible {
2087 visible_ = required_ && [self unfiltered];
2090 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2091 if ((self = [super init]) != nil) {
2092 _profile(Package$initWithVersion)
2093 era_ = [database era];
2098 _profile(Package$initWithVersion$ParentPkg)
2099 iterator_ = version.ParentPkg();
2102 database_ = database;
2104 _profile(Package$initWithVersion$Latest)
2105 latest_ = (NSString *) StripVersion(version_.VerStr());
2108 pkgCache::VerIterator current;
2109 _profile(Package$initWithVersion$Versions)
2110 current = iterator_.CurrentVer();
2112 installed_.set(pool_, StripVersion_(current.VerStr()));
2114 if (!version_.end())
2115 file_ = version_.FileList();
2117 pkgCache &cache([database_ cache]);
2118 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2122 _profile(Package$initWithVersion$Name)
2123 id_.set(pool_, iterator_.Name());
2124 name_.set(pool, iterator_.Display());
2127 _profile(Package$initWithVersion$lowercaseString)
2128 char *data(id_.data());
2129 for (size_t i(0), e(id_.size()); i != e; ++i)
2130 // XXX: do not use tolower() as this is not locale-specific? :(
2135 _profile(Package$initWithVersion$Source)
2136 source_ = [database_ getSource:file_.File()];
2145 _profile(Package$initWithVersion$Tags)
2146 pkgCache::TagIterator tag(iterator_.TagList());
2148 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2150 const char *name(tag.Name());
2151 [tags_ addObject:(NSString *)CYStringCreate(name)];
2152 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2153 role_ = (NSString *) CYStringCreate(name + 6);
2154 if (required_ && strncmp(name, "require::", 9) == 0 && (
2159 } while (!tag.end());
2163 bool changed(false);
2165 _profile(Package$initWithVersion$Metadata)
2166 metadata_ = [Packages_ objectForKey:id_];
2168 if (metadata_ == nil) {
2171 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2172 firstSeen_, @"FirstSeen",
2173 latest_, @"LastVersion",
2178 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2179 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2181 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2182 subscribed_ = [subscribed boolValue];
2184 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2186 if (firstSeen_ == nil) {
2187 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2188 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2192 if (version == nil) {
2193 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2195 } else if (![version isEqualToString:latest_]) {
2196 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2198 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2203 metadata_ = [metadata_ retain];
2206 [Packages_ setObject:metadata_ forKey:id_];
2211 _profile(Package$initWithVersion$Section)
2212 section_.set(pool_, iterator_.Section());
2215 _profile(Package$initWithVersion$hasTag)
2216 obsolete_ = [self hasTag:@"cydia::obsolete"];
2217 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2220 _profile(Package$initWithVersion$setVisible)
2226 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2227 pkgCache::VerIterator version;
2229 _profile(Package$packageWithIterator$GetCandidateVer)
2230 version = [database policy]->GetCandidateVer(iterator);
2236 return [[[Package alloc]
2237 initWithVersion:version
2244 - (pkgCache::PkgIterator) iterator {
2248 - (NSString *) section {
2249 if (section$_ == nil) {
2250 if (section_.empty())
2253 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2254 NSString *name(section_);
2257 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2258 if (NSString *rename = [value objectForKey:@"Rename"]) {
2267 - (NSString *) simpleSection {
2268 if (NSString *section = [self section])
2269 return Simplify(section);
2274 - (NSString *) longSection {
2275 return LocalizeSection([self section]);
2278 - (NSString *) shortSection {
2279 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2282 - (NSString *) uri {
2285 pkgIndexFile *index;
2286 pkgCache::PkgFileIterator file(file_.File());
2287 if (![database_ list].FindIndex(file, index))
2289 return [NSString stringWithUTF8String:iterator_->Path];
2290 //return [NSString stringWithUTF8String:file.Site()];
2291 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2295 - (Address *) maintainer {
2298 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2299 const std::string &maintainer(parser->Maintainer());
2300 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2304 return version_.end() ? 0 : version_->InstalledSize;
2307 - (NSString *) longDescription {
2308 @synchronized (database_) {
2309 if ([database_ era] != era_ || file_.end())
2312 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2313 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2315 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2316 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2317 if ([lines count] < 2)
2320 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2321 for (size_t i(1), e([lines count]); i != e; ++i) {
2322 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2323 [trimmed addObject:trim];
2326 return [trimmed componentsJoinedByString:@"\n"];
2329 - (NSString *) shortDescription {
2334 _profile(Package$index)
2335 CFStringRef name((CFStringRef) [self name]);
2336 if (CFStringGetLength(name) == 0)
2338 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2339 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2341 return toupper(character);
2345 - (NSMutableDictionary *) metadata {
2350 if (subscribed_ && lastSeen_ != nil)
2355 - (BOOL) subscribed {
2360 NSDictionary *metadata([self metadata]);
2361 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2362 return [ignored boolValue];
2367 - (NSString *) latest {
2371 - (NSString *) installed {
2375 - (BOOL) uninstalled {
2376 return installed_.empty();
2380 return !version_.end();
2383 - (BOOL) upgradableAndEssential:(BOOL)essential {
2384 _profile(Package$upgradableAndEssential)
2385 pkgCache::VerIterator current(iterator_.CurrentVer());
2387 return essential && essential_ && visible_;
2389 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2393 - (BOOL) essential {
2398 return [database_ cache][iterator_].InstBroken();
2401 - (BOOL) unfiltered {
2402 _profile(Package$unfiltered$obsolete)
2407 _profile(Package$unfiltered$hasSupportingRole)
2408 if (![self hasSupportingRole])
2414 _profile(Package$unfiltered$section)
2415 section = [self section];
2418 _profile(Package$unfiltered$isSectionVisible)
2419 if (section != nil && !isSectionVisible(section))
2431 unsigned char current(iterator_->CurrentState);
2432 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2435 - (BOOL) halfConfigured {
2436 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2439 - (BOOL) halfInstalled {
2440 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2444 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2445 return state.Mode != pkgDepCache::ModeKeep;
2448 - (NSString *) mode {
2449 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2451 switch (state.Mode) {
2452 case pkgDepCache::ModeDelete:
2453 if ((state.iFlags & pkgDepCache::Purge) != 0)
2457 case pkgDepCache::ModeKeep:
2458 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2459 return @"REINSTALL";
2460 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2464 case pkgDepCache::ModeInstall:
2465 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2466 return @"REINSTALL";
2467 else*/ switch (state.Status) {
2469 return @"DOWNGRADE";
2475 return @"NEW_INSTALL";
2486 - (NSString *) name {
2487 return name_.empty() ? id_ : name_;
2490 - (UIImage *) icon {
2491 NSString *section = [self simpleSection];
2495 if ([static_cast<id>(icon_) hasPrefix:@"file:///"])
2496 // XXX: correct escaping
2497 icon = [UIImage imageAtPath:[static_cast<id>(icon_) substringFromIndex:7]];
2498 if (icon == nil) if (section != nil)
2499 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2500 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2501 if ([dicon hasPrefix:@"file:///"])
2502 // XXX: correct escaping
2503 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2505 icon = [UIImage applicationImageNamed:@"unknown.png"];
2509 - (NSString *) homepage {
2513 - (NSString *) depiction {
2514 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2517 - (Address *) sponsor {
2518 if (sponsor$_ == nil) {
2519 if (sponsor_.empty())
2521 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2525 - (Address *) author {
2526 if (author$_ == nil) {
2527 if (author_.empty())
2529 author$_ = [[Address addressWithString:author_] retain];
2533 - (NSString *) support {
2534 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2537 - (NSArray *) files {
2538 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2539 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2542 fin.open([path UTF8String]);
2547 while (std::getline(fin, line))
2548 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2553 - (NSArray *) relationships {
2554 return relationships_;
2557 - (NSArray *) warnings {
2558 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2559 const char *name(iterator_.Name());
2561 size_t length(strlen(name));
2562 if (length < 2) invalid:
2563 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2564 else for (size_t i(0); i != length; ++i)
2566 /* XXX: technically this is not allowed */
2567 (name[i] < 'A' || name[i] > 'Z') &&
2568 (name[i] < 'a' || name[i] > 'z') &&
2569 (name[i] < '0' || name[i] > '9') &&
2570 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2573 if (strcmp(name, "cydia") != 0) {
2576 bool _private = false;
2579 bool repository = [[self section] isEqualToString:@"Repositories"];
2581 if (NSArray *files = [self files])
2582 for (NSString *file in files)
2583 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2585 else if (!user && [file isEqualToString:@"/User"])
2587 else if (!_private && [file isEqualToString:@"/private"])
2589 else if (!stash && [file isEqualToString:@"/var/stash"])
2592 /* XXX: this is not sensitive enough. only some folders are valid. */
2593 if (cydia && !repository)
2594 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2596 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2598 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2600 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2603 return [warnings count] == 0 ? nil : warnings;
2606 - (NSArray *) applications {
2607 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2609 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2611 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2612 if (NSArray *files = [self files])
2613 for (NSString *file in files)
2614 if (application_r(file)) {
2615 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2616 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2617 if ([id isEqualToString:me])
2620 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2622 display = application_r[1];
2624 NSString *bundle([file stringByDeletingLastPathComponent]);
2625 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2626 if (icon == nil || [icon length] == 0)
2628 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2630 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2631 [applications addObject:application];
2633 [application addObject:id];
2634 [application addObject:display];
2635 [application addObject:url];
2638 return [applications count] == 0 ? nil : applications;
2641 - (Source *) source {
2643 @synchronized (database_) {
2644 if ([database_ era] != era_ || file_.end())
2647 source_ = [database_ getSource:file_.File()];
2659 - (NSString *) role {
2663 - (BOOL) matches:(NSString *)text {
2669 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2670 if (range.location != NSNotFound)
2673 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2674 if (range.location != NSNotFound)
2677 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2678 if (range.location != NSNotFound)
2684 - (bool) hasSupportingRole {
2687 if ([role_ isEqualToString:@"enduser"])
2689 if ([Role_ isEqualToString:@"User"])
2691 if ([role_ isEqualToString:@"hacker"])
2693 if ([Role_ isEqualToString:@"Hacker"])
2695 if ([role_ isEqualToString:@"developer"])
2697 if ([Role_ isEqualToString:@"Developer"])
2702 - (BOOL) hasTag:(NSString *)tag {
2703 return tags_ == nil ? NO : [tags_ containsObject:tag];
2706 - (NSString *) primaryPurpose {
2707 for (NSString *tag in tags_)
2708 if ([tag hasPrefix:@"purpose::"])
2709 return [tag substringFromIndex:9];
2713 - (NSArray *) purposes {
2714 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2715 for (NSString *tag in tags_)
2716 if ([tag hasPrefix:@"purpose::"])
2717 [purposes addObject:[tag substringFromIndex:9]];
2718 return [purposes count] == 0 ? nil : purposes;
2721 - (bool) isCommercial {
2722 return [self hasTag:@"cydia::commercial"];
2725 - (CYString &) cyname {
2726 return name_.empty() ? id_ : name_;
2729 - (uint32_t) compareBySection:(NSArray *)sections {
2730 NSString *section([self section]);
2731 for (size_t i(0), e([sections count]); i != e; ++i) {
2732 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2736 return _not(uint32_t);
2739 - (uint32_t) compareForChanges {
2744 uint32_t timestamp : 30;
2745 uint32_t ignored : 1;
2746 uint32_t upgradable : 1;
2750 bool upgradable([self upgradableAndEssential:YES]);
2751 value.bits.upgradable = upgradable ? 1 : 0;
2754 value.bits.timestamp = 0;
2755 value.bits.ignored = [self ignored] ? 0 : 1;
2756 value.bits.upgradable = 1;
2758 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2759 value.bits.ignored = 0;
2760 value.bits.upgradable = 0;
2763 return _not(uint32_t) - value.key;
2767 pkgProblemResolver *resolver = [database_ resolver];
2768 resolver->Clear(iterator_);
2769 resolver->Protect(iterator_);
2773 pkgProblemResolver *resolver = [database_ resolver];
2774 resolver->Clear(iterator_);
2775 resolver->Protect(iterator_);
2776 pkgCacheFile &cache([database_ cache]);
2777 cache->MarkInstall(iterator_, false);
2778 pkgDepCache::StateCache &state((*cache)[iterator_]);
2779 if (!state.Install())
2780 cache->SetReInstall(iterator_, true);
2784 pkgProblemResolver *resolver = [database_ resolver];
2785 resolver->Clear(iterator_);
2786 resolver->Protect(iterator_);
2787 resolver->Remove(iterator_);
2788 [database_ cache]->MarkDelete(iterator_, true);
2791 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2792 _profile(Package$isUnfilteredAndSearchedForBy)
2795 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2796 value &= [self unfiltered];
2799 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2800 value &= [self matches:search];
2807 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2808 if ([search length] == 0)
2811 _profile(Package$isUnfilteredAndSelectedForBy)
2814 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2815 value &= [self unfiltered];
2818 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2819 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2826 - (bool) isInstalledAndVisible:(NSNumber *)number {
2827 return ((![number boolValue] && ![role_ isEqualToString:@"cydia"]) || [self visible]) && ![self uninstalled];
2830 - (bool) isVisibleInSection:(NSString *)name {
2831 NSString *section = [self section];
2836 section == nil && [name length] == 0 ||
2837 [name isEqualToString:section]
2841 - (bool) isVisibleInSource:(Source *)source {
2842 return [self source] == source && [self visible];
2847 /* Section Class {{{ */
2848 @interface Section : NSObject {
2853 NSString *localized_;
2856 - (NSComparisonResult) compareByLocalized:(Section *)section;
2857 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2858 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2859 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2860 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2861 - (NSString *) name;
2868 - (void) addToCount;
2870 - (void) setCount:(size_t)count;
2871 - (NSString *) localized;
2875 @implementation Section
2879 if (localized_ != nil)
2880 [localized_ release];
2884 - (NSComparisonResult) compareByLocalized:(Section *)section {
2885 NSString *lhs(localized_);
2886 NSString *rhs([section localized]);
2888 /*if ([lhs length] != 0 && [rhs length] != 0) {
2889 unichar lhc = [lhs characterAtIndex:0];
2890 unichar rhc = [rhs characterAtIndex:0];
2892 if (isalpha(lhc) && !isalpha(rhc))
2893 return NSOrderedAscending;
2894 else if (!isalpha(lhc) && isalpha(rhc))
2895 return NSOrderedDescending;
2898 return [lhs compare:rhs options:LaxCompareOptions_];
2901 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2902 if ((self = [self initWithName:name localize:NO]) != nil) {
2903 if (localized != nil)
2904 localized_ = [localized retain];
2908 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2909 return [self initWithName:name row:0 localize:localize];
2912 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2913 if ((self = [super init]) != nil) {
2914 name_ = [name retain];
2918 localized_ = [LocalizeSection(name_) retain];
2922 /* XXX: localize the index thingees */
2923 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2924 if ((self = [super init]) != nil) {
2925 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2931 - (NSString *) name {
2951 - (void) addToCount {
2955 - (void) setCount:(size_t)count {
2959 - (NSString *) localized {
2966 static NSString *Colon_;
2967 static NSString *Error_;
2968 static NSString *Warning_;
2970 /* Database Implementation {{{ */
2971 @implementation Database
2973 + (Database *) sharedInstance {
2974 static Database *instance;
2975 if (instance == nil)
2976 instance = [[Database alloc] init];
2986 NSRecycleZone(zone_);
2987 // XXX: malloc_destroy_zone(zone_);
2988 apr_pool_destroy(pool_);
2992 - (void) _readCydia:(NSNumber *)fd { _pooled
2993 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2994 std::istream is(&ib);
2997 static Pcre finish_r("^finish:([^:]*)$");
2999 while (std::getline(is, line)) {
3000 const char *data(line.c_str());
3001 size_t size = line.size();
3002 lprintf("C:%s\n", data);
3004 if (finish_r(data, size)) {
3005 NSString *finish = finish_r[1];
3006 int index = [Finishes_ indexOfObject:finish];
3007 if (index != INT_MAX && index > Finish_)
3015 - (void) _readStatus:(NSNumber *)fd { _pooled
3016 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3017 std::istream is(&ib);
3020 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3021 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3023 while (std::getline(is, line)) {
3024 const char *data(line.c_str());
3025 size_t size(line.size());
3026 lprintf("S:%s\n", data);
3028 if (conffile_r(data, size)) {
3029 [delegate_ setConfigurationData:conffile_r[1]];
3030 } else if (strncmp(data, "status: ", 8) == 0) {
3031 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3032 [delegate_ setProgressTitle:string];
3033 } else if (pmstatus_r(data, size)) {
3034 std::string type([pmstatus_r[1] UTF8String]);
3035 NSString *id = pmstatus_r[2];
3037 float percent([pmstatus_r[3] floatValue]);
3038 [delegate_ setProgressPercent:(percent / 100)];
3040 NSString *string = pmstatus_r[4];
3042 if (type == "pmerror")
3043 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3044 withObject:[NSArray arrayWithObjects:string, id, nil]
3047 else if (type == "pmstatus") {
3048 [delegate_ setProgressTitle:string];
3049 } else if (type == "pmconffile")
3050 [delegate_ setConfigurationData:string];
3052 lprintf("E:unknown pmstatus\n");
3054 lprintf("E:unknown status\n");
3060 - (void) _readOutput:(NSNumber *)fd { _pooled
3061 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3062 std::istream is(&ib);
3065 while (std::getline(is, line)) {
3066 lprintf("O:%s\n", line.c_str());
3067 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3077 - (Package *) packageWithName:(NSString *)name {
3078 @synchronized (self) {
3079 if (static_cast<pkgDepCache *>(cache_) == NULL)
3081 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3082 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3086 if ((self = [super init]) != nil) {
3093 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3094 apr_pool_create(&pool_, NULL);
3096 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
3100 _assert(pipe(fds) != -1);
3103 _config->Set("APT::Keep-Fds::", cydiafd_);
3104 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3107 detachNewThreadSelector:@selector(_readCydia:)
3109 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3112 _assert(pipe(fds) != -1);
3116 detachNewThreadSelector:@selector(_readStatus:)
3118 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3121 _assert(pipe(fds) != -1);
3122 _assert(dup2(fds[0], 0) != -1);
3123 _assert(close(fds[0]) != -1);
3125 input_ = fdopen(fds[1], "a");
3127 _assert(pipe(fds) != -1);
3128 _assert(dup2(fds[1], 1) != -1);
3129 _assert(close(fds[1]) != -1);
3132 detachNewThreadSelector:@selector(_readOutput:)
3134 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3139 - (pkgCacheFile &) cache {
3143 - (pkgDepCache::Policy *) policy {
3147 - (pkgRecords *) records {
3151 - (pkgProblemResolver *) resolver {
3155 - (pkgAcquire &) fetcher {
3159 - (pkgSourceList &) list {
3163 - (NSArray *) packages {
3164 return (NSArray *) packages_;
3167 - (NSArray *) sources {
3168 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3169 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3170 [sources addObject:i->second];
3174 - (NSArray *) issues {
3175 if (cache_->BrokenCount() == 0)
3178 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3180 for (Package *package in [self packages]) {
3181 if (![package broken])
3183 pkgCache::PkgIterator pkg([package iterator]);
3185 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3186 [entry addObject:[package name]];
3187 [issues addObject:entry];
3189 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3193 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3194 pkgCache::DepIterator start;
3195 pkgCache::DepIterator end;
3196 dep.GlobOr(start, end); // ++dep
3198 if (!cache_->IsImportantDep(end))
3200 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3203 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3204 [entry addObject:failure];
3205 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3207 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3208 if (Package *package = [self packageWithName:name])
3209 name = [package name];
3210 [failure addObject:name];
3212 pkgCache::PkgIterator target(start.TargetPkg());
3213 if (target->ProvidesList != 0)
3214 [failure addObject:@"?"];
3216 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3218 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3219 else if (!cache_[target].CandidateVerIter(cache_).end())
3220 [failure addObject:@"-"];
3221 else if (target->ProvidesList == 0)
3222 [failure addObject:@"!"];
3224 [failure addObject:@"%"];
3228 if (start.TargetVer() != 0)
3229 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3240 - (bool) popErrorWithTitle:(NSString *)title {
3242 std::string message;
3244 while (!_error->empty()) {
3246 bool warning(!_error->PopMessage(error));
3250 size_t size(error.size());
3251 if (size == 0 || error[size - 1] != '\n')
3253 error.resize(size - 1);
3255 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3257 if (!message.empty())
3262 if (fatal && !message.empty())
3263 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3268 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3269 return [self popErrorWithTitle:title] || !success;
3272 - (void) reloadData { CYPoolStart() {
3273 @synchronized (self) {
3276 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3277 CFArrayRemoveAllValues(packages_);
3304 apr_pool_clear(pool_);
3305 NSRecycleZone(zone_);
3307 int chk(creat("/tmp/cydia.chk", 0644));
3311 NSString *title(UCLocalize("DATABASE"));
3314 if (!cache_.Open(progress_, true)) { pop:
3316 bool warning(!_error->PopMessage(error));
3317 lprintf("cache_.Open():[%s]\n", error.c_str());
3319 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3320 [delegate_ repairWithSelector:@selector(configure)];
3321 else if (error == "The package lists or status file could not be parsed or opened.")
3322 [delegate_ repairWithSelector:@selector(update)];
3323 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3324 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3325 // else if (error == "The list of sources could not be read.")
3327 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3336 unlink("/tmp/cydia.chk");
3338 now_ = [[NSDate date] retain];
3340 policy_ = new pkgDepCache::Policy();
3341 records_ = new pkgRecords(cache_);
3342 resolver_ = new pkgProblemResolver(cache_);
3343 fetcher_ = new pkgAcquire(&status_);
3346 list_ = new pkgSourceList();
3347 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3350 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3351 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3355 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3358 if (cache_->BrokenCount() != 0) {
3359 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3362 if (cache_->BrokenCount() != 0) {
3363 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3367 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3371 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3372 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3373 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3374 // XXX: this could be more intelligent
3375 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3376 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3378 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3383 /*std::vector<Package *> packages;
3384 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3385 [packages_ release];
3390 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3391 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3392 //packages.push_back(package);
3393 CFArrayAppendValue(packages_, [package retain]);
3397 /*if (packages.empty())
3398 packages_ = [[NSArray alloc] init];
3400 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3403 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3404 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3405 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3413 /*if (!packages.empty())
3414 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3415 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3417 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3419 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3421 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3425 } } CYPoolEnd() _trace(); }
3427 - (void) configure {
3428 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3429 system([dpkg UTF8String]);
3433 // XXX: I don't remember this condition
3438 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3440 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3442 if ([self popErrorWithTitle:title])
3446 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3449 public pkgArchiveCleaner
3452 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3457 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3464 fetcher_->Shutdown();
3466 pkgRecords records(cache_);
3468 lock_ = new FileFd();
3469 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3471 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3473 if ([self popErrorWithTitle:title])
3477 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3480 manager_ = (_system->CreatePM(cache_));
3481 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3488 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3490 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3492 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3494 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3495 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3498 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3503 bool failed = false;
3504 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3505 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3507 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3510 std::string uri = (*item)->DescURI();
3511 std::string error = (*item)->ErrorText;
3513 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3516 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3517 withObject:[NSArray arrayWithObjects:
3518 [NSString stringWithUTF8String:error.c_str()],
3530 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3532 if (_error->PendingError()) {
3537 if (result == pkgPackageManager::Failed) {
3542 if (result != pkgPackageManager::Completed) {
3547 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3549 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3551 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3552 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3555 if (![before isEqualToArray:after])
3560 NSString *title(UCLocalize("UPGRADE"));
3561 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3567 [self updateWithStatus:status_];
3570 - (void) setVisible {
3571 for (Package *package in [self packages])
3572 [package setVisible];
3575 - (void) updateWithStatus:(Status &)status {
3576 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3577 NSString *title(UCLocalize("REFRESHING_DATA"));
3580 if (!list.ReadMainList())
3581 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3584 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3585 if ([self popErrorWithTitle:title])
3588 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3589 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3590 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3592 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3596 - (void) setDelegate:(id)delegate {
3597 delegate_ = delegate;
3598 status_.setDelegate(delegate);
3599 progress_.setDelegate(delegate);
3602 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3603 SourceMap::const_iterator i(sources_.find(file->ID));
3604 return i == sources_.end() ? nil : i->second;
3610 /* Confirmation Controller {{{ */
3611 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3612 if (!iterator.end())
3613 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3614 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3616 pkgCache::PkgIterator package(dep.TargetPkg());
3619 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3627 /* Web Scripting {{{ */
3628 @interface CydiaObject : NSObject {
3633 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3636 @implementation CydiaObject
3639 [indirect_ release];
3643 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3644 if ((self = [super init]) != nil) {
3645 indirect_ = [indirect retain];
3649 - (void) setDelegate:(id)delegate {
3650 delegate_ = delegate;
3653 + (NSArray *) _attributeKeys {
3654 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3657 - (NSArray *) attributeKeys {
3658 return [[self class] _attributeKeys];
3661 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3662 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3665 - (NSString *) device {
3666 return [[UIDevice currentDevice] uniqueIdentifier];
3669 #if 0 // XXX: implement!
3670 - (NSString *) mac {
3671 if (![indirect_ promptForSensitive:@"Mac Address"])
3675 - (NSString *) serial {
3676 if (![indirect_ promptForSensitive:@"Serial #"])
3680 - (NSString *) firewire {
3681 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3685 - (NSString *) imei {
3686 if (![indirect_ promptForSensitive:@"IMEI"])
3691 + (NSString *) webScriptNameForSelector:(SEL)selector {
3692 if (selector == @selector(close))
3694 else if (selector == @selector(getInstalledPackages))
3695 return @"getInstalledPackages";
3696 else if (selector == @selector(getPackageById:))
3697 return @"getPackageById";
3698 else if (selector == @selector(installPackages:))
3699 return @"installPackages";
3700 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3701 return @"setButtonImage";
3702 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3703 return @"setButtonTitle";
3704 else if (selector == @selector(setPopupHook:))
3705 return @"setPopupHook";
3706 else if (selector == @selector(setSpecial:))
3707 return @"setSpecial";
3708 else if (selector == @selector(setToken:))
3710 else if (selector == @selector(setViewportWidth:))
3711 return @"setViewportWidth";
3712 else if (selector == @selector(supports:))
3714 else if (selector == @selector(stringWithFormat:arguments:))
3716 else if (selector == @selector(localizedStringForKey:value:table:))
3718 else if (selector == @selector(du:))
3720 else if (selector == @selector(statfs:))
3726 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3727 return [self webScriptNameForSelector:selector] == nil;
3730 - (BOOL) supports:(NSString *)feature {
3731 return [feature isEqualToString:@"window.open"];
3734 - (NSArray *) getInstalledPackages {
3735 NSArray *packages([[Database sharedInstance] packages]);
3736 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3737 for (Package *package in packages)
3738 if ([package installed] != nil)
3739 [installed addObject:package];
3743 - (Package *) getPackageById:(NSString *)id {
3744 Package *package([[Database sharedInstance] packageWithName:id]);
3749 - (NSArray *) statfs:(NSString *)path {
3752 if (path == nil || statfs([path UTF8String], &stat) == -1)
3755 return [NSArray arrayWithObjects:
3756 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3757 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3758 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3762 - (NSNumber *) du:(NSString *)path {
3763 NSNumber *value(nil);
3766 _assert(pipe(fds) != -1);
3768 pid_t pid(ExecFork());
3770 _assert(dup2(fds[1], 1) != -1);
3771 _assert(close(fds[0]) != -1);
3772 _assert(close(fds[1]) != -1);
3773 /* XXX: this should probably not use du */
3774 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3779 _assert(close(fds[1]) != -1);
3781 if (FILE *du = fdopen(fds[0], "r")) {
3783 while (fgets(line, sizeof(line), du) != NULL) {
3784 size_t length(strlen(line));
3785 while (length != 0 && line[length - 1] == '\n')
3786 line[--length] = '\0';
3787 if (char *tab = strchr(line, '\t')) {
3789 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3794 } else _assert(close(fds[0]));
3798 if (waitpid(pid, &status, 0) == -1)
3801 else _assert(false);
3810 - (void) installPackages:(NSArray *)packages {
3811 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3814 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3815 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3818 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3819 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3822 - (void) setSpecial:(id)function {
3823 [indirect_ setSpecial:function];
3826 - (void) setToken:(NSString *)token {
3829 Token_ = [token retain];
3831 [Metadata_ setObject:Token_ forKey:@"Token"];
3835 - (void) setPopupHook:(id)function {
3836 [indirect_ setPopupHook:function];
3839 - (void) setViewportWidth:(float)width {
3840 [indirect_ setViewportWidth:width];
3843 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3844 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3845 unsigned count([arguments count]);
3847 for (unsigned i(0); i != count; ++i)
3848 values[i] = [arguments objectAtIndex:i];
3849 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3852 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3853 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3855 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3857 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3863 /* Cydia Browser Controller {{{ */
3864 @interface CYBrowserController : BrowserController {
3865 CydiaObject *cydia_;
3870 @implementation CYBrowserController
3877 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3880 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3881 [super webView:view didClearWindowObject:window forFrame:frame];
3883 WebDataSource *source([frame dataSource]);
3884 NSURLResponse *response([source response]);
3885 NSURL *url([response URL]);
3886 NSString *scheme([url scheme]);
3888 NSHTTPURLResponse *http;
3889 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3890 http = (NSHTTPURLResponse *) response;
3894 NSDictionary *headers([http allHeaderFields]);
3895 NSString *host([url host]);
3896 [self setHeaders:headers forHost:host];
3899 [host isEqualToString:@"cydia.saurik.com"] ||
3900 [host hasSuffix:@".cydia.saurik.com"] ||
3901 [scheme isEqualToString:@"file"]
3903 [window setValue:cydia_ forKey:@"cydia"];
3906 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3907 if (System_ != NULL)
3908 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3909 if (Machine_ != NULL)
3910 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3912 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3914 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3917 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3918 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3919 [self _setMoreHeaders:copy];
3923 - (void) setDelegate:(id)delegate {
3924 [super setDelegate:delegate];
3925 [cydia_ setDelegate:delegate];
3929 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3930 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3932 WebView *webview([[webview_ _documentView] webView]);
3934 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3936 NSString *application = package == nil ? @"Cydia" : [NSString
3937 stringWithFormat:@"Cydia/%@",
3942 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3944 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3945 if (Product_ != nil)
3946 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3948 [webview setApplicationNameForUserAgent:application];
3955 /* Confirmation {{{ */
3956 @protocol ConfirmationControllerDelegate
3957 - (void) cancelAndClear:(bool)clear;
3958 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3962 @interface ConfirmationController : CYBrowserController {
3963 _transient Database *database_;
3964 UIAlertView *essential_;
3971 - (id) initWithDatabase:(Database *)database;
3975 @implementation ConfirmationController
3982 if (essential_ != nil)
3983 [essential_ release];
3987 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3988 NSString *context([alert context]);
3990 if ([context isEqualToString:@"remove"]) {
3991 if (button == [alert cancelButtonIndex]) {
3992 [self dismissModalViewControllerAnimated:YES];
3993 } else if (button == [alert firstOtherButtonIndex]) {
3996 [delegate_ confirmWithNavigationController:[self navigationController]];
3999 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4000 } else if ([context isEqualToString:@"unable"]) {
4001 [self dismissModalViewControllerAnimated:YES];
4002 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4004 [super alertView:alert clickedButtonAtIndex:button];
4008 - (void) _doContinue {
4009 [self dismissModalViewControllerAnimated:YES];
4010 [delegate_ cancelAndClear:NO];
4013 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4014 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4018 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4019 [super webView:view didClearWindowObject:window forFrame:frame];
4020 [window setValue:changes_ forKey:@"changes"];
4021 [window setValue:issues_ forKey:@"issues"];
4022 [window setValue:sizes_ forKey:@"sizes"];
4023 [window setValue:self forKey:@"queue"];
4026 - (id) initWithDatabase:(Database *)database {
4027 if ((self = [super init]) != nil) {
4028 database_ = database;
4030 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4032 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4033 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4034 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4035 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4036 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4040 pkgDepCache::Policy *policy([database_ policy]);
4042 pkgCacheFile &cache([database_ cache]);
4043 NSArray *packages = [database_ packages];
4044 for (Package *package in packages) {
4045 pkgCache::PkgIterator iterator = [package iterator];
4046 pkgDepCache::StateCache &state(cache[iterator]);
4048 NSString *name([package name]);
4050 if (state.NewInstall())
4051 [installing addObject:name];
4052 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4053 [reinstalling addObject:name];
4054 else if (state.Upgrade())
4055 [upgrading addObject:name];
4056 else if (state.Downgrade())
4057 [downgrading addObject:name];
4058 else if (state.Delete()) {
4059 if ([package essential])
4061 [removing addObject:name];
4064 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4065 substrate_ |= DepSubstrate(iterator.CurrentVer());
4070 else if (Advanced_) {
4071 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4073 essential_ = [[UIAlertView alloc]
4074 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4075 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4077 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4078 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4081 [essential_ setContext:@"remove"];
4083 essential_ = [[UIAlertView alloc]
4084 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4085 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4087 cancelButtonTitle:UCLocalize("OKAY")
4088 otherButtonTitles:nil
4091 [essential_ setContext:@"unable"];
4094 changes_ = [[NSArray alloc] initWithObjects:
4102 issues_ = [database_ issues];
4104 issues_ = [issues_ retain];
4106 sizes_ = [[NSArray alloc] initWithObjects:
4107 SizeString([database_ fetcher].FetchNeeded()),
4108 SizeString([database_ fetcher].PartialPresent()),
4111 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4113 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
4114 initWithTitle:UCLocalize("CANCEL")
4115 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4116 style:UIBarButtonItemStylePlain
4118 action:@selector(cancelButtonClicked)
4120 [[self navigationItem] setLeftBarButtonItem:leftItem];
4125 - (void) applyRightButton {
4126 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
4127 initWithTitle:UCLocalize("CONFIRM")
4128 style:UIBarButtonItemStylePlain
4130 action:@selector(confirmButtonClicked)
4132 #if !AlwaysReload && !IgnoreInstall
4133 if (issues_ == nil && ![self isLoading]) [[self navigationItem] setRightBarButtonItem:rightItem];
4134 else [super applyRightButton];
4136 [[self navigationItem] setRightBarButtonItem:nil];
4138 [rightItem release];
4141 - (void) cancelButtonClicked {
4142 [self dismissModalViewControllerAnimated:YES];
4143 [delegate_ cancelAndClear:YES];
4147 - (void) confirmButtonClicked {
4151 if (essential_ != nil)
4156 [delegate_ confirmWithNavigationController:[self navigationController]];
4164 /* Progress Data {{{ */
4165 @interface ProgressData : NSObject {
4171 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4178 @implementation ProgressData
4180 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4181 if ((self = [super init]) != nil) {
4182 selector_ = selector;
4202 /* Progress Controller {{{ */
4203 @interface ProgressController : CYViewController <
4204 ConfigurationDelegate,
4207 _transient Database *database_;
4208 UIProgressBar *progress_;
4209 UITextView *output_;
4210 UITextLabel *status_;
4211 UIPushButton *close_;
4213 SHA1SumValue springlist_;
4214 SHA1SumValue notifyconf_;
4218 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4220 - (void) _retachThread;
4221 - (void) _detachNewThreadData:(ProgressData *)data;
4222 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4228 @protocol ProgressControllerDelegate
4229 - (void) progressControllerIsComplete:(ProgressController *)sender;
4232 @implementation ProgressController
4235 [database_ setDelegate:nil];
4236 [progress_ release];
4245 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4246 if ((self = [super init]) != nil) {
4247 database_ = database;
4248 [database_ setDelegate:self];
4249 delegate_ = delegate;
4251 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4253 progress_ = [[UIProgressBar alloc] init];
4254 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4255 [progress_ setStyle:0];
4257 status_ = [[UITextLabel alloc] init];
4258 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4259 [status_ setColor:[UIColor whiteColor]];
4260 [status_ setBackgroundColor:[UIColor clearColor]];
4261 [status_ setCentersHorizontally:YES];
4262 //[status_ setFont:font];
4264 output_ = [[UITextView alloc] init];
4266 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4267 //[output_ setTextFont:@"Courier New"];
4268 [output_ setFont:[[output_ font] fontWithSize:12]];
4269 [output_ setTextColor:[UIColor whiteColor]];
4270 [output_ setBackgroundColor:[UIColor clearColor]];
4271 [output_ setMarginTop:0];
4272 [output_ setAllowsRubberBanding:YES];
4273 [output_ setEditable:NO];
4274 [[self view] addSubview:output_];
4276 close_ = [[UIPushButton alloc] init];
4277 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4278 [close_ setAutosizesToFit:NO];
4279 [close_ setDrawsShadow:YES];
4280 [close_ setStretchBackground:YES];
4281 [close_ setEnabled:YES];
4282 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4283 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4284 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4285 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4289 - (void) positionViews {
4290 CGRect bounds = [[self view] bounds];
4291 CGSize prgsize = [UIProgressBar defaultSize];
4294 (bounds.size.width - prgsize.width) / 2,
4295 bounds.size.height - prgsize.height - 20
4298 float closewidth = bounds.size.width - 20;
4299 if (closewidth > 300) closewidth = 300;
4301 [progress_ setFrame:prgrect];
4302 [status_ setFrame:CGRectMake(
4304 bounds.size.height - prgsize.height - 50,
4305 bounds.size.width - 20,
4308 [output_ setFrame:CGRectMake(
4311 bounds.size.width - 20,
4312 bounds.size.height - 62
4314 [close_ setFrame:CGRectMake(
4315 (bounds.size.width - closewidth) / 2,
4316 bounds.size.height - prgsize.height - 50,
4322 - (void) viewWillAppear:(BOOL)animated {
4323 [super viewDidAppear:animated];
4324 [[self navigationItem] setHidesBackButton:YES];
4325 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4327 [self positionViews];
4330 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4331 [self positionViews];
4334 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4335 NSString *context([alert context]);
4337 if ([context isEqualToString:@"conffile"]) {
4338 FILE *input = [database_ input];
4339 if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
4340 else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
4345 - (void) closeButtonPushed {
4348 UpdateExternalStatus(0);
4352 [self dismissModalViewControllerAnimated:YES];
4356 [delegate_ terminateWithSuccess];
4357 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4358 [delegate_ suspendWithAnimation:YES];
4360 [delegate_ suspend];*/
4364 system("launchctl stop com.apple.SpringBoard");
4368 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4377 - (void) _retachThread {
4378 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4380 [[self view] addSubview:close_];
4381 [progress_ removeFromSuperview];
4382 [status_ removeFromSuperview];
4384 [database_ popErrorWithTitle:title_];
4385 [delegate_ progressControllerIsComplete:self];
4389 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4392 MMap mmap(file, MMap::ReadOnly);
4394 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4395 if (!(notifyconf_ == sha1.Result()))
4402 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4405 MMap mmap(file, MMap::ReadOnly);
4407 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4408 if (!(springlist_ == sha1.Result()))
4414 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4415 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4416 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4417 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4418 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4421 system("su -c /usr/bin/uicache mobile");
4423 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4425 [delegate_ setStatusBarShowsProgress:NO];
4428 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4429 [[data target] performSelector:[data selector] withObject:[data object]];
4432 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4435 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4436 UpdateExternalStatus(1);
4443 title_ = [title retain];
4445 [[self navigationItem] setTitle:title_];
4447 [status_ setText:nil];
4448 [output_ setText:@""];
4449 [progress_ setProgress:0];
4451 [close_ removeFromSuperview];
4452 [[self view] addSubview:progress_];
4453 [[self view] addSubview:status_];
4455 [delegate_ setStatusBarShowsProgress:YES];
4460 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4463 MMap mmap(file, MMap::ReadOnly);
4465 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4466 notifyconf_ = sha1.Result();
4472 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4475 MMap mmap(file, MMap::ReadOnly);
4477 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4478 springlist_ = sha1.Result();
4483 detachNewThreadSelector:@selector(_detachNewThreadData:)
4485 withObject:[[ProgressData alloc]
4486 initWithSelector:selector
4493 - (void) repairWithSelector:(SEL)selector {
4495 detachNewThreadSelector:selector
4498 title:UCLocalize("REPAIRING")
4502 - (void) setConfigurationData:(NSString *)data {
4504 performSelectorOnMainThread:@selector(_setConfigurationData:)
4510 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4511 CYActionSheet *sheet([[[CYActionSheet alloc]
4513 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4514 defaultButtonIndex:0
4517 [sheet setMessage:error];
4518 [sheet yieldToPopupAlertAnimated:YES];
4522 - (void) setProgressTitle:(NSString *)title {
4524 performSelectorOnMainThread:@selector(_setProgressTitle:)
4530 - (void) setProgressPercent:(float)percent {
4532 performSelectorOnMainThread:@selector(_setProgressPercent:)
4533 withObject:[NSNumber numberWithFloat:percent]
4538 - (void) startProgress {
4541 - (void) addProgressOutput:(NSString *)output {
4543 performSelectorOnMainThread:@selector(_addProgressOutput:)
4549 - (bool) isCancelling:(size_t)received {
4553 - (void) _setConfigurationData:(NSString *)data {
4554 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4556 if (!conffile_r(data)) {
4557 lprintf("E:invalid conffile\n");
4561 NSString *ofile = conffile_r[1];
4562 //NSString *nfile = conffile_r[2];
4564 UIAlertView *alert = [[[UIAlertView alloc]
4565 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4566 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4568 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4569 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4570 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4574 [alert setContext:@"conffile"];
4578 - (void) _setProgressTitle:(NSString *)title {
4579 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4580 for (size_t i(0), e([words count]); i != e; ++i) {
4581 NSString *word([words objectAtIndex:i]);
4582 if (Package *package = [database_ packageWithName:word])
4583 [words replaceObjectAtIndex:i withObject:[package name]];
4586 [status_ setText:[words componentsJoinedByString:@" "]];
4589 - (void) _setProgressPercent:(NSNumber *)percent {
4590 [progress_ setProgress:[percent floatValue]];
4593 - (void) _addProgressOutput:(NSString *)output {
4594 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4595 CGSize size = [output_ contentSize];
4596 CGRect rect = {{0, size.height}, {size.width, 0}};
4597 [output_ scrollRectToVisible:rect animated:YES];
4600 - (BOOL) isRunning {
4607 /* Cell Content View {{{ */
4608 @protocol ContentDelegate
4609 - (void) drawContentRect:(CGRect)rect;
4612 @interface ContentView : UIView {
4613 _transient id<ContentDelegate> delegate_;
4618 @implementation ContentView
4619 - (id) initWithFrame:(CGRect)frame {
4620 if ((self = [super initWithFrame:frame]) != nil) {
4621 /* Fix landscape stretching. */
4622 [self setNeedsDisplayOnBoundsChange:YES];
4626 - (void) setDelegate:(id<ContentDelegate>)delegate {
4627 delegate_ = delegate;
4630 - (void) drawRect:(CGRect)rect {
4631 [super drawRect:rect];
4632 [delegate_ drawContentRect:rect];
4636 /* Package Cell {{{ */
4637 @interface PackageCell : UITableViewCell <
4642 NSString *description_;
4648 ContentView *content_;
4654 - (PackageCell *) init;
4655 - (void) setPackage:(Package *)package;
4657 + (int) heightForPackage:(Package *)package;
4658 - (void) drawContentRect:(CGRect)rect;
4662 @implementation PackageCell
4664 - (void) clearPackage {
4675 if (description_ != nil) {
4676 [description_ release];
4680 if (source_ != nil) {
4685 if (badge_ != nil) {
4690 if (placard_ != nil) {
4700 [self clearPackage];
4707 return faded_ ? [self selectionPercent] : fade_;
4710 - (PackageCell *) init {
4711 CGRect frame(CGRectMake(0, 0, 320, 74));
4712 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4713 UIView *content([self contentView]);
4714 CGRect bounds([content bounds]);
4716 content_ = [[ContentView alloc] initWithFrame:bounds];
4717 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4718 [content addSubview:content_];
4720 [content_ setDelegate:self];
4721 [content_ setOpaque:YES];
4722 if ([self respondsToSelector:@selector(selectionPercent)])
4727 - (void) _setBackgroundColor {
4729 if (NSString *mode = [package_ mode]) {
4730 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4731 color = remove ? RemovingColor_ : InstallingColor_;
4733 color = [UIColor whiteColor];
4735 [content_ setBackgroundColor:color];
4736 [self setNeedsDisplay];
4739 - (void) setPackage:(Package *)package {
4740 [self clearPackage];
4743 Source *source = [package source];
4745 icon_ = [[package icon] retain];
4746 name_ = [[package name] retain];
4749 description_ = [package longDescription];
4750 if (description_ == nil)
4751 description_ = [package shortDescription];
4752 if (description_ != nil)
4753 description_ = [description_ retain];
4755 commercial_ = [package isCommercial];
4757 package_ = [package retain];
4759 NSString *label = nil;
4760 bool trusted = false;
4762 if (source != nil) {
4763 label = [source label];
4764 trusted = [source trusted];
4765 } else if ([[package id] isEqualToString:@"firmware"])
4766 label = UCLocalize("APPLE");
4768 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4770 NSString *from(label);
4772 NSString *section = [package simpleSection];
4773 if (section != nil && ![section isEqualToString:label]) {
4774 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4775 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4778 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4779 source_ = [from retain];
4781 if (NSString *purpose = [package primaryPurpose])
4782 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4783 badge_ = [badge_ retain];
4785 if ([package installed] != nil)
4786 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4787 placard_ = [placard_ retain];
4789 [self _setBackgroundColor];
4790 [content_ setNeedsDisplay];
4793 - (void) drawContentRect:(CGRect)rect {
4794 bool selected([self isSelected]);
4795 float width([self bounds].size.width);
4798 CGContextRef context(UIGraphicsGetCurrentContext());
4799 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4800 CGContextFillRect(context, rect);
4805 rect.size = [icon_ size];
4807 rect.size.width /= 2;
4808 rect.size.height /= 2;
4810 rect.origin.x = 25 - rect.size.width / 2;
4811 rect.origin.y = 25 - rect.size.height / 2;
4813 [icon_ drawInRect:rect];
4816 if (badge_ != nil) {
4817 CGSize size = [badge_ size];
4819 [badge_ drawAtPoint:CGPointMake(
4820 36 - size.width / 2,
4821 36 - size.height / 2
4829 UISetColor(commercial_ ? Purple_ : Black_);
4830 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4831 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4834 UISetColor(commercial_ ? Purplish_ : Gray_);
4835 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4837 if (placard_ != nil)
4838 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4841 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4842 //[self _setBackgroundColor];
4843 [super setSelected:selected animated:fade];
4844 [content_ setNeedsDisplay];
4847 + (int) heightForPackage:(Package *)package {
4853 /* Section Cell {{{ */
4854 @interface SectionCell : UITableViewCell <
4862 ContentView *content_;
4867 - (void) setSection:(Section *)section editing:(BOOL)editing;
4871 @implementation SectionCell
4873 - (void) clearSection {
4874 if (basic_ != nil) {
4879 if (section_ != nil) {
4889 if (count_ != nil) {
4896 [self clearSection];
4904 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4905 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4906 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4907 switch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4908 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4910 UIView *content([self contentView]);
4911 CGRect bounds([content bounds]);
4913 content_ = [[ContentView alloc] initWithFrame:bounds];
4914 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4915 [content addSubview:content_];
4916 [content_ setBackgroundColor:[UIColor whiteColor]];
4918 [content_ setDelegate:self];
4922 - (void) onSwitch:(id)sender {
4923 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4924 if (metadata == nil) {
4925 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4926 [Sections_ setObject:metadata forKey:basic_];
4930 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4933 - (void) setSection:(Section *)section editing:(BOOL)editing {
4934 if (editing != editing_) {
4936 [switch_ removeFromSuperview];
4938 [self addSubview:switch_];
4942 [self clearSection];
4944 if (section == nil) {
4945 name_ = [UCLocalize("ALL_PACKAGES") retain];
4948 basic_ = [section name];
4950 basic_ = [basic_ retain];
4952 section_ = [section localized];
4953 if (section_ != nil)
4954 section_ = [section_ retain];
4956 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4957 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4960 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4963 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4964 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
4966 [content_ setNeedsDisplay];
4969 - (void) setFrame:(CGRect)frame {
4970 [super setFrame:frame];
4972 CGRect rect([switch_ frame]);
4973 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4976 - (void) drawContentRect:(CGRect)rect {
4977 BOOL selected = [self isSelected];
4979 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4987 float width(rect.size.width);
4991 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4993 CGSize size = [count_ sizeWithFont:Font14_];
4997 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5003 /* File Table {{{ */
5004 @interface FileTable : CYViewController <
5005 UITableViewDataSource,
5008 _transient Database *database_;
5011 NSMutableArray *files_;
5015 - (id) initWithDatabase:(Database *)database;
5016 - (void) setPackage:(Package *)package;
5020 @implementation FileTable
5023 if (package_ != nil)
5032 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5033 return files_ == nil ? 0 : [files_ count];
5036 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5040 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5041 static NSString *reuseIdentifier = @"Cell";
5043 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5045 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5046 [cell setFont:[UIFont systemFontOfSize:16]];
5048 [cell setText:[files_ objectAtIndex:indexPath.row]];
5049 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5054 - (id) initWithDatabase:(Database *)database {
5055 if ((self = [super init]) != nil) {
5056 database_ = database;
5058 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5060 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5062 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5063 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5064 [list_ setRowHeight:24.0f];
5065 [[self view] addSubview:list_];
5067 [list_ setDataSource:self];
5068 [list_ setDelegate:self];
5072 - (void) setPackage:(Package *)package {
5073 if (package_ != nil) {
5074 [package_ autorelease];
5083 [files_ removeAllObjects];
5085 if (package != nil) {
5086 package_ = [package retain];
5087 name_ = [[package id] retain];
5089 if (NSArray *files = [package files])
5090 [files_ addObjectsFromArray:files];
5092 if ([files_ count] != 0) {
5093 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5094 [files_ removeObjectAtIndex:0];
5095 [files_ sortUsingSelector:@selector(compareByPath:)];
5097 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5098 [stack addObject:@"/"];
5100 for (int i(0), e([files_ count]); i != e; ++i) {
5101 NSString *file = [files_ objectAtIndex:i];
5102 while (![file hasPrefix:[stack lastObject]])
5103 [stack removeLastObject];
5104 NSString *directory = [stack lastObject];
5105 [stack addObject:[file stringByAppendingString:@"/"]];
5106 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5107 ([stack count] - 2) * 3, "",
5108 [file substringFromIndex:[directory length]]
5117 - (void) reloadData {
5118 [self setPackage:[database_ packageWithName:name_]];
5123 /* Package Controller {{{ */
5124 @interface PackageController : CYBrowserController <
5125 UIActionSheetDelegate
5127 _transient Database *database_;
5131 NSMutableArray *buttons_;
5132 UIBarButtonItem *button_;
5135 - (id) initWithDatabase:(Database *)database;
5136 - (void) setPackage:(Package *)package;
5140 @implementation PackageController
5143 if (package_ != nil)
5157 if ([self retainCount] == 1)
5158 [delegate_ setPackageController:self];
5162 /* XXX: this is not safe at all... localization of /fail/ */
5163 - (void) _clickButtonWithName:(NSString *)name {
5164 if ([name isEqualToString:UCLocalize("CLEAR")])
5165 [delegate_ clearPackage:package_];
5166 else if ([name isEqualToString:UCLocalize("INSTALL")])
5167 [delegate_ installPackage:package_];
5168 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5169 [delegate_ installPackage:package_];
5170 else if ([name isEqualToString:UCLocalize("REMOVE")])
5171 [delegate_ removePackage:package_];
5172 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5173 [delegate_ installPackage:package_];
5174 else _assert(false);
5177 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5178 NSString *context([sheet context]);
5180 if ([context isEqualToString:@"modify"]) {
5181 if (button != [sheet cancelButtonIndex]) {
5182 NSString *buttonName = [buttons_ objectAtIndex:button];
5183 [self _clickButtonWithName:buttonName];
5186 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5190 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5191 [super webView:view didClearWindowObject:window forFrame:frame];
5192 [window setValue:package_ forKey:@"package"];
5195 - (bool) _allowJavaScriptPanel {
5200 - (void) _customButtonClicked {
5201 int count([buttons_ count]);
5206 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5208 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5209 [buttons addObjectsFromArray:buttons_];
5211 UIActionSheet *sheet = [[[UIActionSheet alloc]
5214 cancelButtonTitle:nil
5215 destructiveButtonTitle:nil
5216 otherButtonTitles:nil
5219 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5221 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5222 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5224 [sheet setContext:@"modify"];
5226 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5230 // We don't want to allow non-commercial packages to do custom things to the install button,
5231 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5232 - (void) customButtonClicked {
5234 [super customButtonClicked];
5236 [self _customButtonClicked];
5239 - (void) reloadButtonClicked {
5240 // Don't reload a package view by clicking the button.
5243 - (void) applyLoadingTitle {
5244 // Don't show "Loading" as the title. Ever.
5247 - (UIBarButtonItem *) rightButton {
5252 - (id) initWithDatabase:(Database *)database {
5253 if ((self = [super init]) != nil) {
5254 database_ = database;
5255 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5256 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5260 - (void) setPackage:(Package *)package {
5261 if (package_ != nil) {
5262 [package_ autorelease];
5271 [buttons_ removeAllObjects];
5273 if (package != nil) {
5276 package_ = [package retain];
5277 name_ = [[package id] retain];
5278 commercial_ = [package isCommercial];
5280 if ([package_ mode] != nil)
5281 [buttons_ addObject:UCLocalize("CLEAR")];
5282 if ([package_ source] == nil);
5283 else if ([package_ upgradableAndEssential:NO])
5284 [buttons_ addObject:UCLocalize("UPGRADE")];
5285 else if ([package_ uninstalled])
5286 [buttons_ addObject:UCLocalize("INSTALL")];
5288 [buttons_ addObject:UCLocalize("REINSTALL")];
5289 if (![package_ uninstalled])
5290 [buttons_ addObject:UCLocalize("REMOVE")];
5297 switch ([buttons_ count]) {
5298 case 0: title = nil; break;
5299 case 1: title = [buttons_ objectAtIndex:0]; break;
5300 default: title = UCLocalize("MODIFY"); break;
5303 button_ = [[UIBarButtonItem alloc]
5305 style:UIBarButtonItemStylePlain
5307 action:@selector(customButtonClicked)
5311 - (bool) isLoading {
5312 return commercial_ ? [super isLoading] : false;
5315 - (void) reloadData {
5316 [self setPackage:[database_ packageWithName:name_]];
5321 /* Package Table {{{ */
5322 @interface PackageTable : UIView <
5323 UITableViewDataSource,
5326 _transient Database *database_;
5327 NSMutableArray *packages_;
5328 NSMutableArray *sections_;
5330 NSMutableArray *index_;
5331 NSMutableDictionary *indices_;
5337 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5339 - (void) setDelegate:(id)delegate;
5341 - (void) reloadData;
5342 - (void) resetCursor;
5344 - (UITableView *) list;
5346 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5348 - (void) deselectWithAnimation:(BOOL)animated;
5352 @implementation PackageTable
5355 [packages_ release];
5356 [sections_ release];
5364 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5365 NSInteger count([sections_ count]);
5366 return count == 0 ? 1 : count;
5369 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5370 if ([sections_ count] == 0)
5372 return [[sections_ objectAtIndex:section] name];
5375 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5376 if ([sections_ count] == 0)
5378 return [[sections_ objectAtIndex:section] count];
5381 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5382 Section *section([sections_ objectAtIndex:[path section]]);
5383 NSInteger row([path row]);
5384 Package *package([packages_ objectAtIndex:([section row] + row)]);
5388 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5389 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5391 cell = [[[PackageCell alloc] init] autorelease];
5392 [cell setPackage:[self packageAtIndexPath:path]];
5396 - (void) deselectWithAnimation:(BOOL)animated {
5397 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5400 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5401 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5404 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5405 Package *package([self packageAtIndexPath:path]);
5406 package = [database_ packageWithName:[package id]];
5407 [target_ performSelector:action_ withObject:package];
5411 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5412 return [packages_ count] > 20 ? index_ : nil;
5415 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5419 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5420 if ((self = [super initWithFrame:frame]) != nil) {
5421 database_ = database;
5426 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5427 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5429 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5430 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5432 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5433 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5434 [list_ setRowHeight:73.0f];
5435 [self addSubview:list_];
5437 [list_ setDataSource:self];
5438 [list_ setDelegate:self];
5442 - (void) setDelegate:(id)delegate {
5443 delegate_ = delegate;
5446 - (bool) hasPackage:(Package *)package {
5450 - (void) reloadData {
5451 NSArray *packages = [database_ packages];
5453 [packages_ removeAllObjects];
5454 [sections_ removeAllObjects];
5456 _profile(PackageTable$reloadData$Filter)
5457 for (Package *package in packages)
5458 if ([self hasPackage:package])
5459 [packages_ addObject:package];
5462 [index_ removeAllObjects];
5463 [indices_ removeAllObjects];
5465 Section *section = nil;
5467 _profile(PackageTable$reloadData$Section)
5468 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5472 _profile(PackageTable$reloadData$Section$Package)
5473 package = [packages_ objectAtIndex:offset];
5474 index = [package index];
5477 if (section == nil || [section index] != index) {
5478 _profile(PackageTable$reloadData$Section$Allocate)
5479 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5482 [index_ addObject:[section name]];
5483 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5485 _profile(PackageTable$reloadData$Section$Add)
5486 [sections_ addObject:section];
5490 [section addToCount];
5494 _profile(PackageTable$reloadData$List)
5499 - (void) resetCursor {
5500 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5503 - (UITableView *) list {
5507 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5508 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5513 /* Filtered Package Table {{{ */
5514 @interface FilteredPackageTable : PackageTable {
5520 - (void) setObject:(id)object;
5521 - (void) setObject:(id)object forFilter:(SEL)filter;
5523 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5527 @implementation FilteredPackageTable
5535 - (void) setFilter:(SEL)filter {
5538 /* XXX: this is an unsafe optimization of doomy hell */
5539 Method method(class_getInstanceMethod([Package class], filter));
5540 _assert(method != NULL);
5541 imp_ = method_getImplementation(method);
5542 _assert(imp_ != NULL);
5545 - (void) setObject:(id)object {
5551 object_ = [object retain];
5554 - (void) setObject:(id)object forFilter:(SEL)filter {
5555 [self setFilter:filter];
5556 [self setObject:object];
5559 - (bool) hasPackage:(Package *)package {
5560 _profile(FilteredPackageTable$hasPackage)
5561 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5565 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5566 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5567 [self setFilter:filter];
5568 object_ = [object retain];
5576 /* Filtered Package Controller {{{ */
5577 @interface FilteredPackageController : CYViewController {
5578 _transient Database *database_;
5579 FilteredPackageTable *packages_;
5583 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5587 @implementation FilteredPackageController
5590 [packages_ release];
5596 - (void) viewDidAppear:(BOOL)animated {
5597 [super viewDidAppear:animated];
5598 [packages_ deselectWithAnimation:animated];
5601 - (void) didSelectPackage:(Package *)package {
5602 PackageController *view([delegate_ packageController]);
5603 [view setPackage:package];
5604 [view setDelegate:delegate_];
5605 [[self navigationController] pushViewController:view animated:YES];
5608 - (NSString *) title { return title_; }
5610 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5611 if ((self = [super init]) != nil) {
5612 database_ = database;
5613 title_ = [title copy];
5614 [[self navigationItem] setTitle:title_];
5616 packages_ = [[FilteredPackageTable alloc]
5617 initWithFrame:[[self view] bounds]
5620 action:@selector(didSelectPackage:)
5625 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5626 [[self view] addSubview:packages_];
5630 - (void) reloadData {
5631 [packages_ reloadData];
5634 - (void) setDelegate:(id)delegate {
5635 [super setDelegate:delegate];
5636 [packages_ setDelegate:delegate];
5643 /* Add Source Controller {{{ */
5644 @interface AddSourceController : CYViewController {
5645 _transient Database *database_;
5648 - (id) initWithDatabase:(Database *)database;
5652 @implementation AddSourceController
5654 - (id) initWithDatabase:(Database *)database {
5655 if ((self = [super init]) != nil) {
5656 database_ = database;
5662 /* Source Cell {{{ */
5663 @interface SourceCell : UITableViewCell <
5668 NSString *description_;
5670 ContentView *content_;
5673 - (void) setSource:(Source *)source;
5677 @implementation SourceCell
5679 - (void) clearSource {
5682 [description_ release];
5691 - (void) setSource:(Source *)source {
5695 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5697 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5698 icon_ = [icon_ retain];
5700 origin_ = [[source name] retain];
5701 label_ = [[source uri] retain];
5702 description_ = [[source description] retain];
5704 [content_ setNeedsDisplay];
5713 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5714 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5715 UIView *content([self contentView]);
5716 CGRect bounds([content bounds]);
5718 content_ = [[ContentView alloc] initWithFrame:bounds];
5719 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5720 [content_ setBackgroundColor:[UIColor whiteColor]];
5721 [content addSubview:content_];
5723 [content_ setDelegate:self];
5724 [content_ setOpaque:YES];
5728 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5729 [super setSelected:selected animated:animated];
5730 [content_ setNeedsDisplay];
5733 - (void) drawContentRect:(CGRect)rect {
5734 bool selected([self isSelected]);
5735 float width(rect.size.width);
5738 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5745 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5749 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5753 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5758 /* Source Table {{{ */
5759 @interface SourceTable : CYViewController <
5760 UITableViewDataSource,
5763 _transient Database *database_;
5765 NSMutableArray *sources_;
5769 UIProgressHUD *hud_;
5772 //NSURLConnection *installer_;
5773 NSURLConnection *trivial_;
5774 NSURLConnection *trivial_bz2_;
5775 NSURLConnection *trivial_gz_;
5776 //NSURLConnection *automatic_;
5781 - (id) initWithDatabase:(Database *)database;
5783 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5787 @implementation SourceTable
5789 - (void) _deallocConnection:(NSURLConnection *)connection {
5790 if (connection != nil) {
5791 [connection cancel];
5792 //[connection setDelegate:nil];
5793 [connection release];
5805 //[self _deallocConnection:installer_];
5806 [self _deallocConnection:trivial_];
5807 [self _deallocConnection:trivial_gz_];
5808 [self _deallocConnection:trivial_bz2_];
5809 //[self _deallocConnection:automatic_];
5816 - (void) viewDidAppear:(BOOL)animated {
5817 [super viewDidAppear:animated];
5818 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5821 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5822 return offset_ == 0 ? 1 : 2;
5825 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5826 switch (section + (offset_ == 0 ? 1 : 0)) {
5827 case 0: return UCLocalize("ENTERED_BY_USER");
5828 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5834 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5835 int count = [sources_ count];
5837 case 0: return (offset_ == 0 ? count : offset_);
5838 case 1: return count - offset_;
5844 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5846 switch (indexPath.section) {
5847 case 0: idx = indexPath.row; break;
5848 case 1: idx = indexPath.row + offset_; break;
5852 return [sources_ objectAtIndex:idx];
5855 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5856 Source *source = [self sourceAtIndexPath:indexPath];
5857 return [source description] == nil ? 56 : 73;
5860 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5861 static NSString *cellIdentifier = @"SourceCell";
5863 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5864 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5865 [cell setSource:[self sourceAtIndexPath:indexPath]];
5870 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5871 return UITableViewCellAccessoryDisclosureIndicator;
5874 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5875 Source *source = [self sourceAtIndexPath:indexPath];
5877 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5878 initWithDatabase:database_
5879 title:[source label]
5880 filter:@selector(isVisibleInSource:)
5884 [packages setDelegate:delegate_];
5886 [[self navigationController] pushViewController:packages animated:YES];
5889 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5890 Source *source = [self sourceAtIndexPath:indexPath];
5891 return [source record] != nil;
5894 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5895 Source *source = [self sourceAtIndexPath:indexPath];
5896 [Sources_ removeObjectForKey:[source key]];
5897 [delegate_ syncData];
5901 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5904 @"./", @"Distribution",
5905 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5907 [delegate_ syncData];
5910 - (NSString *) getWarning {
5911 NSString *href(href_);
5912 NSRange colon([href rangeOfString:@"://"]);
5913 if (colon.location != NSNotFound)
5914 href = [href substringFromIndex:(colon.location + 3)];
5915 href = [href stringByAddingPercentEscapes];
5916 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5917 href = [href stringByCachingURLWithCurrentCDN];
5919 NSURL *url([NSURL URLWithString:href]);
5921 NSStringEncoding encoding;
5922 NSError *error(nil);
5924 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5925 return [warning length] == 0 ? nil : warning;
5929 - (void) _endConnection:(NSURLConnection *)connection {
5930 NSURLConnection **field = NULL;
5931 if (connection == trivial_)
5933 else if (connection == trivial_bz2_)
5934 field = &trivial_bz2_;
5935 else if (connection == trivial_gz_)
5936 field = &trivial_gz_;
5937 _assert(field != NULL);
5938 [connection release];
5943 trivial_bz2_ == nil &&
5949 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5952 UIAlertView *alert = [[[UIAlertView alloc]
5953 initWithTitle:UCLocalize("SOURCE_WARNING")
5956 cancelButtonTitle:UCLocalize("CANCEL")
5957 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5960 [alert setContext:@"warning"];
5961 [alert setNumberOfRows:1];
5965 } else if (error_ != nil) {
5966 UIAlertView *alert = [[[UIAlertView alloc]
5967 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5968 message:[error_ localizedDescription]
5970 cancelButtonTitle:UCLocalize("OK")
5971 otherButtonTitles:nil
5974 [alert setContext:@"urlerror"];
5977 UIAlertView *alert = [[[UIAlertView alloc]
5978 initWithTitle:UCLocalize("NOT_REPOSITORY")
5979 message:UCLocalize("NOT_REPOSITORY_EX")
5981 cancelButtonTitle:UCLocalize("OK")
5982 otherButtonTitles:nil
5985 [alert setContext:@"trivial"];
5989 [delegate_ setStatusBarShowsProgress:NO];
5990 [delegate_ removeProgressHUD:hud_];
6000 if (error_ != nil) {
6007 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6008 switch ([response statusCode]) {
6014 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6015 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6017 error_ = [error retain];
6018 [self _endConnection:connection];
6021 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6022 [self _endConnection:connection];
6025 - (NSString *) title { return UCLocalize("SOURCES"); }
6027 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6028 NSMutableURLRequest *request = [NSMutableURLRequest
6029 requestWithURL:[NSURL URLWithString:href]
6030 cachePolicy:NSURLRequestUseProtocolCachePolicy
6031 timeoutInterval:120.0
6034 [request setHTTPMethod:method];
6036 if (Machine_ != NULL)
6037 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6038 if (UniqueID_ != nil)
6039 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6041 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6043 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6046 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6047 NSString *context([alert context]);
6049 if ([context isEqualToString:@"source"]) {
6052 NSString *href = [[alert textField] text];
6054 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6056 if (![href hasSuffix:@"/"])
6057 href_ = [href stringByAppendingString:@"/"];
6060 href_ = [href_ retain];
6062 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6063 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6064 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6065 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6069 hud_ = [[delegate_ addProgressHUD] retain];
6070 [hud_ setText:UCLocalize("VERIFYING_URL")];
6079 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6080 } else if ([context isEqualToString:@"trivial"])
6081 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6082 else if ([context isEqualToString:@"urlerror"])
6083 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6084 else if ([context isEqualToString:@"warning"]) {
6099 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6103 - (id) initWithDatabase:(Database *)database {
6104 if ((self = [super init]) != nil) {
6105 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6106 [self updateButtonsForEditingStatus:NO animated:NO];
6108 database_ = database;
6109 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6111 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6112 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6113 [[self view] addSubview:list_];
6115 [list_ setDataSource:self];
6116 [list_ setDelegate:self];
6122 - (void) reloadData {
6124 if (!list.ReadMainList())
6127 [sources_ removeAllObjects];
6128 [sources_ addObjectsFromArray:[database_ sources]];
6130 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6133 int count([sources_ count]);
6135 for (int i = 0; i != count; i++) {
6136 if ([[sources_ objectAtIndex:i] record] == nil) break;
6140 [list_ setEditing:NO];
6141 [self updateButtonsForEditingStatus:NO animated:NO];
6145 - (void) addButtonClicked {
6146 /*[book_ pushPage:[[[AddSourceController alloc]
6151 UIAlertView *alert = [[[UIAlertView alloc]
6152 initWithTitle:UCLocalize("ENTER_APT_URL")
6155 cancelButtonTitle:UCLocalize("CANCEL")
6156 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6159 [alert setContext:@"source"];
6160 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6162 [alert setNumberOfRows:1];
6163 [alert addTextFieldWithValue:@"http://" label:@""];
6165 UITextInputTraits *traits = [[alert textField] textInputTraits];
6166 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6167 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6168 [traits setKeyboardType:UIKeyboardTypeURL];
6169 // XXX: UIReturnKeyDone
6170 [traits setReturnKeyType:UIReturnKeyNext];
6175 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6176 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
6177 initWithTitle:UCLocalize("ADD")
6178 style:UIBarButtonItemStylePlain
6180 action:@selector(addButtonClicked)
6182 [[self navigationItem] setLeftBarButtonItem:editing ? leftItem : [[self navigationItem] backBarButtonItem] animated:animated];
6185 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6186 initWithTitle:editing ? UCLocalize("DONE") : UCLocalize("EDIT")
6187 style:editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6189 action:@selector(editButtonClicked)
6191 [[self navigationItem] setRightBarButtonItem:rightItem animated:animated];
6192 [rightItem release];
6194 if (IsWildcat_ && !editing) {
6195 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6196 initWithTitle:UCLocalize("SETTINGS")
6197 style:UIBarButtonItemStylePlain
6199 action:@selector(settingsButtonClicked)
6201 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6202 [settingsItem release];
6206 - (void) settingsButtonClicked {
6207 [delegate_ showSettings];
6210 - (void) editButtonClicked {
6211 [list_ setEditing:![list_ isEditing] animated:YES];
6213 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6219 /* Installed Controller {{{ */
6220 @interface InstalledController : FilteredPackageController {
6224 - (id) initWithDatabase:(Database *)database;
6226 - (void) updateRoleButton;
6227 - (void) queueStatusDidChange;
6231 @implementation InstalledController
6237 - (NSString *) title { return UCLocalize("INSTALLED"); }
6239 - (id) initWithDatabase:(Database *)database {
6240 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6241 [self updateRoleButton];
6242 [self queueStatusDidChange];
6247 - (void) queueButtonClicked {
6252 - (void) queueStatusDidChange {
6255 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6256 initWithTitle:UCLocalize("QUEUE")
6257 style:UIBarButtonItemStyleDone
6259 action:@selector(queueButtonClicked)
6261 if (Queuing_) [[self navigationItem] setLeftBarButtonItem:queueItem];
6262 else [[self navigationItem] setLeftBarButtonItem:nil];
6263 [queueItem release];
6268 - (void) reloadData {
6269 [packages_ reloadData];
6272 - (void) updateRoleButton {
6273 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6274 initWithTitle:expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")
6275 style:expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6277 action:@selector(roleButtonClicked)
6279 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) [[self navigationItem] setRightBarButtonItem:rightItem];
6280 [rightItem release];
6283 - (void) roleButtonClicked {
6284 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6285 [packages_ reloadData];
6288 [self updateRoleButton];
6291 - (void) setDelegate:(id)delegate {
6292 [super setDelegate:delegate];
6293 [packages_ setDelegate:delegate];
6299 /* Home Controller {{{ */
6300 @interface HomeController : CYBrowserController {
6305 @implementation HomeController
6307 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6308 [super _setMoreHeaders:request];
6311 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6312 if (UniqueID_ != nil)
6313 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6315 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6318 - (void) aboutButtonClicked {
6319 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6321 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6322 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6323 [alert setCancelButtonIndex:0];
6326 @"Copyright (C) 2008-2010\n"
6327 "Jay Freeman (saurik)\n"
6328 "saurik@saurik.com\n"
6329 "http://www.saurik.com/"
6335 - (void) viewWillAppear:(BOOL)animated {
6336 [super viewWillAppear:animated];
6337 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6340 - (void) viewWillDisappear:(BOOL)animated {
6341 [super viewWillDisappear:animated];
6342 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6346 if ((self = [super init]) != nil) {
6347 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6348 initWithTitle:UCLocalize("ABOUT")
6349 style:UIBarButtonItemStylePlain
6351 action:@selector(aboutButtonClicked)
6358 /* Manage Controller {{{ */
6359 @interface ManageController : CYBrowserController {
6362 - (void) queueStatusDidChange;
6365 @implementation ManageController
6368 if ((self = [super init]) != nil) {
6369 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6371 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6372 initWithTitle:UCLocalize("SETTINGS")
6373 style:UIBarButtonItemStylePlain
6375 action:@selector(settingsButtonClicked)
6377 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6378 [settingsItem release];
6380 [self queueStatusDidChange];
6384 - (void) settingsButtonClicked {
6385 [delegate_ showSettings];
6389 - (void) queueButtonClicked {
6393 - (void) applyLoadingTitle {
6394 // No "Loading" title.
6397 - (void) applyRightButton {
6402 - (void) queueStatusDidChange {
6404 if (!IsWildcat_ && Queuing_) {
6405 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6406 initWithTitle:UCLocalize("QUEUE")
6407 style:UIBarButtonItemStyleDone
6409 action:@selector(queueButtonClicked)
6411 [[self navigationItem] setRightBarButtonItem:queueItem];
6413 [queueItem release];
6415 [[self navigationItem] setRightBarButtonItem:nil];
6420 - (bool) isLoading {
6427 /* Refresh Bar {{{ */
6428 @interface RefreshBar : UINavigationBar {
6429 UIProgressIndicator *indicator_;
6430 UITextLabel *prompt_;
6431 UIProgressBar *progress_;
6432 UINavigationButton *cancel_;
6437 @implementation RefreshBar
6439 - (void) positionViews {
6440 CGRect frame = [cancel_ frame];
6441 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6442 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6443 [cancel_ setFrame:frame];
6445 CGSize prgsize = {75, 100};
6447 [self frame].size.width - prgsize.width - 10,
6448 ([self frame].size.height - prgsize.height) / 2
6450 [progress_ setFrame:prgrect];
6452 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6453 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6454 CGRect indrect = {{indoffset, indoffset}, indsize};
6455 [indicator_ setFrame:indrect];
6457 CGSize prmsize = {215, indsize.height + 4};
6459 indoffset * 2 + indsize.width,
6460 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6462 [prompt_ setFrame:prmrect];
6465 - (void)setFrame:(CGRect)frame {
6466 [super setFrame:frame];
6468 [self positionViews];
6471 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6472 if ((self = [super initWithFrame:frame])) {
6473 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6475 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6476 [self setBarStyle:UIBarStyleBlack];
6478 UIBarStyle barstyle([self _barStyle:NO]);
6479 bool ugly(barstyle == UIBarStyleDefault);
6481 UIProgressIndicatorStyle style = ugly ?
6482 UIProgressIndicatorStyleMediumBrown :
6483 UIProgressIndicatorStyleMediumWhite;
6485 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6486 [indicator_ setStyle:style];
6487 [indicator_ startAnimation];
6488 [self addSubview:indicator_];
6490 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6491 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6492 [prompt_ setBackgroundColor:[UIColor clearColor]];
6493 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6494 [self addSubview:prompt_];
6496 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6497 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6498 [progress_ setStyle:0];
6499 [self addSubview:progress_];
6501 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6502 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6503 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6504 [cancel_ setBarStyle:barstyle];
6506 [self positionViews];
6511 [cancel_ removeFromSuperview];
6515 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6516 [progress_ setProgress:0];
6517 [self addSubview:cancel_];
6521 [cancel_ removeFromSuperview];
6524 - (void) setPrompt:(NSString *)prompt {
6525 [prompt_ setText:prompt];
6528 - (void) setProgress:(float)progress {
6529 [progress_ setProgress:progress];
6535 @class CYNavigationController;
6537 /* Cydia Tab Bar Controller {{{ */
6538 @interface CYTabBarController : UITabBarController {
6539 Database *database_;
6544 @implementation CYTabBarController
6546 /* XXX: some logic should probably go here related to
6547 freeing the view controllers on tab change */
6549 - (void) reloadData {
6550 size_t count([[self viewControllers] count]);
6551 for (size_t i(0); i != count; ++i) {
6552 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6557 - (id) initWithDatabase:(Database *)database {
6558 if ((self = [super init]) != nil) {
6559 database_ = database;
6566 /* Cydia Navigation Controller {{{ */
6567 @interface CYNavigationController : UINavigationController {
6568 _transient Database *database_;
6569 id<UINavigationControllerDelegate> delegate_;
6572 - (id) initWithDatabase:(Database *)database;
6573 - (void) reloadData;
6578 @implementation CYNavigationController
6580 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6581 // Inherit autorotation settings for modal parents.
6582 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6583 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6585 return [super shouldAutorotateToInterfaceOrientation:orientation];
6593 - (void) reloadData {
6594 size_t count([[self viewControllers] count]);
6595 for (size_t i(0); i != count; ++i) {
6596 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6601 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6602 delegate_ = delegate;
6605 - (id) initWithDatabase:(Database *)database {
6606 if ((self = [super init]) != nil) {
6607 database_ = database;
6613 /* Cydia:// Protocol {{{ */
6614 @interface CydiaURLProtocol : NSURLProtocol {
6619 @implementation CydiaURLProtocol
6621 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6622 NSURL *url([request URL]);
6625 NSString *scheme([[url scheme] lowercaseString]);
6626 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6631 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6635 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6636 id<NSURLProtocolClient> client([self client]);
6638 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6640 NSData *data(UIImagePNGRepresentation(icon));
6642 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6643 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6644 [client URLProtocol:self didLoadData:data];
6645 [client URLProtocolDidFinishLoading:self];
6649 - (void) startLoading {
6650 id<NSURLProtocolClient> client([self client]);
6651 NSURLRequest *request([self request]);
6653 NSURL *url([request URL]);
6654 NSString *href([url absoluteString]);
6656 NSString *path([href substringFromIndex:8]);
6657 NSRange slash([path rangeOfString:@"/"]);
6660 if (slash.location == NSNotFound) {
6664 command = [path substringToIndex:slash.location];
6665 path = [path substringFromIndex:(slash.location + 1)];
6668 Database *database([Database sharedInstance]);
6670 if ([command isEqualToString:@"package-icon"]) {
6673 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6674 Package *package([database packageWithName:path]);
6677 UIImage *icon([package icon]);
6678 [self _returnPNGWithImage:icon forRequest:request];
6679 } else if ([command isEqualToString:@"source-icon"]) {
6682 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6683 NSString *source(Simplify(path));
6684 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6686 icon = [UIImage applicationImageNamed:@"unknown.png"];
6687 [self _returnPNGWithImage:icon forRequest:request];
6688 } else if ([command isEqualToString:@"uikit-image"]) {
6691 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6692 UIImage *icon(_UIImageWithName(path));
6693 [self _returnPNGWithImage:icon forRequest:request];
6694 } else if ([command isEqualToString:@"section-icon"]) {
6697 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6698 NSString *section(Simplify(path));
6699 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6701 icon = [UIImage applicationImageNamed:@"unknown.png"];
6702 [self _returnPNGWithImage:icon forRequest:request];
6704 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6708 - (void) stopLoading {
6714 /* Sections Controller {{{ */
6715 @interface SectionsController : CYViewController <
6716 UITableViewDataSource,
6719 _transient Database *database_;
6720 NSMutableArray *sections_;
6721 NSMutableArray *filtered_;
6727 - (id) initWithDatabase:(Database *)database;
6728 - (void) reloadData;
6731 - (void) editButtonClicked;
6735 @implementation SectionsController
6738 [list_ setDataSource:nil];
6739 [list_ setDelegate:nil];
6741 [sections_ release];
6742 [filtered_ release];
6744 [accessory_ release];
6748 - (void) viewDidAppear:(BOOL)animated {
6749 [super viewDidAppear:animated];
6750 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6753 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6754 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6758 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6759 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6762 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6766 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6767 static NSString *reuseIdentifier = @"SectionCell";
6769 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6770 if (cell == nil) cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6771 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6776 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6780 Section *section = [self sectionAtIndexPath:indexPath];
6781 NSString *name = [section name];
6784 if ([indexPath row] == 0) {
6787 title = UCLocalize("ALL_PACKAGES");
6790 name = [NSString stringWithString:name];
6791 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6794 title = UCLocalize("NO_SECTION");
6798 FilteredPackageController *table = [[[FilteredPackageController alloc]
6799 initWithDatabase:database_
6801 filter:@selector(isVisibleInSection:)
6805 [table setDelegate:delegate_];
6807 [[self navigationController] pushViewController:table animated:YES];
6810 - (NSString *) title { return UCLocalize("SECTIONS"); }
6812 - (id) initWithDatabase:(Database *)database {
6813 if ((self = [super init]) != nil) {
6814 database_ = database;
6816 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6818 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6819 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6821 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6822 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6823 [list_ setRowHeight:45.0f];
6824 [[self view] addSubview:list_];
6826 [list_ setDataSource:self];
6827 [list_ setDelegate:self];
6833 - (void) reloadData {
6834 NSArray *packages = [database_ packages];
6836 [sections_ removeAllObjects];
6837 [filtered_ removeAllObjects];
6840 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6841 SectionMap sections;
6842 sections.resize(64);
6844 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6848 for (Package *package in packages) {
6849 NSString *name([package section]);
6850 NSString *key(name == nil ? @"" : name);
6855 _profile(SectionsView$reloadData$Section)
6856 section = §ions[key];
6857 if (*section == nil) {
6858 _profile(SectionsView$reloadData$Section$Allocate)
6859 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6864 [*section addToCount];
6866 _profile(SectionsView$reloadData$Filter)
6867 if (![package valid] || ![package visible])
6871 [*section addToRow];
6875 _profile(SectionsView$reloadData$Section)
6876 section = [sections objectForKey:key];
6877 if (section == nil) {
6878 _profile(SectionsView$reloadData$Section$Allocate)
6879 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6880 [sections setObject:section forKey:key];
6885 [section addToCount];
6887 _profile(SectionsView$reloadData$Filter)
6888 if (![package valid] || ![package visible])
6898 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6899 [sections_ addObject:i->second];
6901 [sections_ addObjectsFromArray:[sections allValues]];
6904 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6906 for (Section *section in sections_) {
6907 size_t count([section row]);
6911 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6912 [section setCount:count];
6913 [filtered_ addObject:section];
6916 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6917 initWithTitle:[sections_ count] == 0 ? nil : UCLocalize("EDIT")
6918 style:UIBarButtonItemStylePlain
6920 action:@selector(editButtonClicked)
6922 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] != nil];
6923 [rightItem release];
6929 - (void) resetView {
6931 [self editButtonClicked];
6934 - (void) editButtonClicked {
6935 if ((editing_ = !editing_))
6938 [delegate_ updateData];
6940 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6941 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6942 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6945 - (UIView *) accessoryView {
6951 /* Changes Controller {{{ */
6952 @interface ChangesController : CYViewController <
6953 UITableViewDataSource,
6956 _transient Database *database_;
6957 CFMutableArrayRef packages_;
6958 NSMutableArray *sections_;
6961 BOOL hasSentFirstLoad_;
6964 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6965 - (void) reloadData;
6969 @implementation ChangesController
6972 [list_ setDelegate:nil];
6973 [list_ setDataSource:nil];
6975 CFRelease(packages_);
6977 [sections_ release];
6982 - (void) viewDidAppear:(BOOL)animated {
6983 [super viewDidAppear:animated];
6984 if (!hasSentFirstLoad_) {
6985 hasSentFirstLoad_ = YES;
6986 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6988 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6992 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6993 NSInteger count([sections_ count]);
6994 return count == 0 ? 1 : count;
6997 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6998 if ([sections_ count] == 0)
7000 return [[sections_ objectAtIndex:section] name];
7003 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7004 if ([sections_ count] == 0)
7006 return [[sections_ objectAtIndex:section] count];
7009 - (Package *) packageAtIndex:(NSUInteger)index {
7010 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7013 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7014 Section *section([sections_ objectAtIndex:[path section]]);
7015 NSInteger row([path row]);
7016 return [self packageAtIndex:([section row] + row)];
7019 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7020 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7022 cell = [[[PackageCell alloc] init] autorelease];
7023 [cell setPackage:[self packageAtIndexPath:path]];
7027 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7028 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7031 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7032 Package *package([self packageAtIndexPath:path]);
7033 PackageController *view([delegate_ packageController]);
7034 [view setDelegate:delegate_];
7035 [view setPackage:package];
7036 [[self navigationController] pushViewController:view animated:YES];
7040 - (void) refreshButtonClicked {
7041 [delegate_ beginUpdate];
7042 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7045 - (void) upgradeButtonClicked {
7046 [delegate_ distUpgrade];
7049 - (NSString *) title { return UCLocalize("CHANGES"); }
7051 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7052 if ((self = [super init]) != nil) {
7053 database_ = database;
7054 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7056 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7058 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7060 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7061 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7062 [list_ setRowHeight:73.0f];
7063 [[self view] addSubview:list_];
7065 [list_ setDataSource:self];
7066 [list_ setDelegate:self];
7068 delegate_ = delegate;
7072 - (void) _reloadPackages:(NSArray *)packages {
7074 for (Package *package in packages)
7076 [package uninstalled] && [package valid] && [package visible] ||
7077 [package upgradableAndEssential:YES]
7079 CFArrayAppendValue(packages_, package);
7082 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7086 - (void) reloadData {
7087 NSArray *packages = [database_ packages];
7089 CFArrayRemoveAllValues(packages_);
7091 [sections_ removeAllObjects];
7094 UIProgressHUD *hud([delegate_ addProgressHUD]);
7096 [hud setText:@"Loading Changes"];
7097 //NSLog(@"HUD:%@::%@", delegate_, hud);
7098 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7099 [delegate_ removeProgressHUD:hud];
7101 [self _reloadPackages:packages];
7104 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7105 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7106 Section *section = nil;
7110 bool unseens = false;
7112 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7114 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7115 Package *package = [self packageAtIndex:offset];
7117 BOOL uae = [package upgradableAndEssential:YES];
7123 _profile(ChangesController$reloadData$Remember)
7124 seen = [package seen];
7127 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7132 name = UCLocalize("UNKNOWN");
7134 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7138 _profile(ChangesController$reloadData$Allocate)
7139 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7140 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7141 [sections_ addObject:section];
7145 [section addToCount];
7146 } else if ([package ignored])
7147 [ignored addToCount];
7150 [upgradable addToCount];
7155 CFRelease(formatter);
7158 Section *last = [sections_ lastObject];
7159 size_t count = [last count];
7160 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7161 [sections_ removeLastObject];
7164 if ([ignored count] != 0)
7165 [sections_ insertObject:ignored atIndex:0];
7167 [sections_ insertObject:upgradable atIndex:0];
7171 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7172 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7173 style:UIBarButtonItemStylePlain
7175 action:@selector(upgradeButtonClicked)
7177 if (upgrades_ > 0) [[self navigationItem] setRightBarButtonItem:rightItem];
7178 [rightItem release];
7180 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
7181 initWithTitle:UCLocalize("REFRESH")
7182 style:UIBarButtonItemStylePlain
7184 action:@selector(refreshButtonClicked)
7186 if (![delegate_ updating]) [[self navigationItem] setLeftBarButtonItem:leftItem];
7192 /* Search Controller {{{ */
7193 @interface SearchController : FilteredPackageController <
7196 UISearchBar *search_;
7199 - (id) initWithDatabase:(Database *)database;
7200 - (void) reloadData;
7204 @implementation SearchController
7211 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7212 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7213 [search_ resignFirstResponder];
7217 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7218 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7222 - (NSString *) title { return nil; }
7224 - (id) initWithDatabase:(Database *)database {
7225 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7228 - (void)viewDidAppear:(BOOL)animated {
7229 [super viewDidAppear:animated];
7231 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7232 [search_ layoutSubviews];
7233 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7234 UITextField *textField = [search_ searchField];
7235 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7236 [search_ setDelegate:self];
7237 [textField setEnablesReturnKeyAutomatically:NO];
7238 [[self navigationItem] setTitleView:textField];
7242 - (void) _reloadData {
7245 - (void) reloadData {
7246 _profile(SearchController$reloadData)
7247 [packages_ reloadData];
7250 [packages_ resetCursor];
7253 - (void) didSelectPackage:(Package *)package {
7254 [search_ resignFirstResponder];
7255 [super didSelectPackage:package];
7260 /* Settings Controller {{{ */
7261 @interface SettingsController : CYViewController <
7262 UITableViewDataSource,
7265 _transient Database *database_;
7268 UITableView *table_;
7269 id subscribedSwitch_;
7271 UITableViewCell *subscribedCell_;
7272 UITableViewCell *ignoredCell_;
7275 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7279 @implementation SettingsController
7283 if (package_ != nil)
7286 [subscribedSwitch_ release];
7287 [ignoredSwitch_ release];
7288 [subscribedCell_ release];
7289 [ignoredCell_ release];
7294 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7295 if (package_ == nil)
7301 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7302 if (package_ == nil)
7308 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7309 return UCLocalize("SHOW_ALL_CHANGES_EX");
7312 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7313 if (package_ == nil)
7316 NSMutableDictionary *metadata([package_ metadata]);
7319 if (NSNumber *number = [metadata objectForKey:key])
7320 before = [number boolValue];
7324 if (value != before) {
7325 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7327 [delegate_ updateData];
7331 - (void) onSubscribed:(id)control {
7332 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7335 - (void) onIgnored:(id)control {
7336 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
7339 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7340 if (package_ == nil)
7343 switch ([indexPath row]) {
7344 case 0: return subscribedCell_;
7345 case 1: return ignoredCell_;
7353 - (NSString *) title { return UCLocalize("SETTINGS"); }
7355 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7356 if ((self = [super init])) {
7357 database_ = database;
7358 name_ = [package retain];
7360 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7362 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7363 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7364 [[self view] addSubview:table_];
7366 subscribedSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7367 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7368 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7370 ignoredSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7371 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7372 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7374 subscribedCell_ = [[UITableViewCell alloc] init];
7375 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7376 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7377 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7379 ignoredCell_ = [[UITableViewCell alloc] init];
7380 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7381 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7382 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7384 [table_ setDataSource:self];
7385 [table_ setDelegate:self];
7390 - (void) reloadData {
7391 if (package_ != nil)
7392 [package_ autorelease];
7393 package_ = [database_ packageWithName:name_];
7394 if (package_ != nil) {
7396 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7397 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7400 [table_ reloadData];
7405 /* Signature Controller {{{ */
7406 @interface SignatureController : CYBrowserController {
7407 _transient Database *database_;
7411 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7415 @implementation SignatureController
7422 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7424 [super webView:view didClearWindowObject:window forFrame:frame];
7427 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7428 if ((self = [super init]) != nil) {
7429 database_ = database;
7430 package_ = [package retain];
7435 - (void) reloadData {
7436 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7442 /* Role Controller {{{ */
7443 @interface RoleController : CYViewController <
7444 UITableViewDataSource,
7447 _transient Database *database_;
7449 UITableView *table_;
7450 UISegmentedControl *segment_;
7454 - (void) showDoneButton;
7455 - (void) resizeSegmentedControl;
7459 @implementation RoleController
7463 [container_ release];
7468 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7469 if ((self = [super init])) {
7470 database_ = database;
7471 roledelegate_ = delegate;
7473 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7475 NSArray *items = [NSArray arrayWithObjects:
7477 UCLocalize("HACKER"),
7478 UCLocalize("DEVELOPER"),
7480 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7481 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7482 [container_ addSubview:segment_];
7485 if ([Role_ isEqualToString:@"User"]) index = 0;
7486 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7487 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7489 [segment_ setSelectedSegmentIndex:index];
7490 [self showDoneButton];
7493 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7494 [self resizeSegmentedControl];
7496 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7497 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7498 [table_ setDelegate:self];
7499 [table_ setDataSource:self];
7500 [[self view] addSubview:table_];
7501 [table_ reloadData];
7505 - (void) resizeSegmentedControl {
7506 CGFloat width = [[self view] frame].size.width;
7507 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7510 - (void) viewWillAppear:(BOOL)animated {
7511 [super viewWillAppear:animated];
7513 [self resizeSegmentedControl];
7516 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7517 [self resizeSegmentedControl];
7520 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7521 [self resizeSegmentedControl];
7525 NSString *role(nil);
7527 switch ([segment_ selectedSegmentIndex]) {
7528 case 0: role = @"User"; break;
7529 case 1: role = @"Hacker"; break;
7530 case 2: role = @"Developer"; break;
7535 if (![role isEqualToString:Role_]) {
7536 bool rolling(Role_ == nil);
7539 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7543 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7548 [roledelegate_ loadData];
7550 [roledelegate_ updateData];
7554 - (void) segmentChanged:(UISegmentedControl *)control {
7555 [self showDoneButton];
7558 - (void) saveAndClose {
7561 [[self navigationItem] setRightBarButtonItem:nil];
7562 [[self navigationController] dismissModalViewControllerAnimated:YES];
7565 - (void) doneButtonClicked {
7566 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7567 [spinner startAnimating];
7568 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7569 [[self navigationItem] setRightBarButtonItem:spinItem];
7571 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7574 - (void) showDoneButton {
7575 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7576 initWithTitle:UCLocalize("DONE")
7577 style:UIBarButtonItemStyleDone
7579 action:@selector(doneButtonClicked)
7581 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] == nil];
7582 [rightItem release];
7585 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7586 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7590 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7594 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7595 return nil; // This method is required by the protocol.
7598 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7600 return UCLocalize("ROLE_EX");
7602 return [NSString stringWithFormat:
7603 @"%@: %@\n%@: %@\n%@: %@",
7604 UCLocalize("USER"), UCLocalize("USER_EX"),
7605 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7606 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7611 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7612 if (section == 3) return 44.0f;
7616 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7617 if (section == 3) return container_;
7623 /* Stash Controller {{{ */
7624 @interface CYStashController : CYViewController {
7625 UIActivityIndicatorView *spinner_;
7631 @implementation CYStashController
7633 if ((self = [super init])) {
7634 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7636 spinner_ = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
7637 CGRect spinrect = [spinner_ frame];
7638 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7639 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7640 [spinner_ setFrame:spinrect];
7641 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7642 [[self view] addSubview:spinner_];
7644 [spinner_ startAnimating];
7647 captrect.size.width = [[self view] frame].size.width;
7648 captrect.size.height = 40.0f;
7649 captrect.origin.x = 0;
7650 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7651 caption_ = [[UILabel alloc] initWithFrame:captrect];
7652 [caption_ setText:@"Initializing Filesystem"];
7653 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7654 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7655 [caption_ setTextColor:[UIColor whiteColor]];
7656 [caption_ setBackgroundColor:[UIColor clearColor]];
7657 [caption_ setShadowColor:[UIColor blackColor]];
7658 [caption_ setTextAlignment:UITextAlignmentCenter];
7659 [[self view] addSubview:caption_];
7663 statusrect.size.width = [[self view] frame].size.width;
7664 statusrect.size.height = 30.0f;
7665 statusrect.origin.x = 0;
7666 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7667 status_ = [[UILabel alloc] initWithFrame:statusrect];
7668 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7669 [status_ setText:@"(Cydia will exit when complete.)"];
7670 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7671 [status_ setTextColor:[UIColor whiteColor]];
7672 [status_ setBackgroundColor:[UIColor clearColor]];
7673 [status_ setShadowColor:[UIColor blackColor]];
7674 [status_ setTextAlignment:UITextAlignmentCenter];
7675 [[self view] addSubview:status_];
7680 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7681 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7686 /* Cydia Container {{{ */
7687 @interface CYContainer : UIViewController <ProgressDelegate> {
7688 _transient Database *database_;
7689 RefreshBar *refreshbar_;
7693 NSObject<CydiaDelegate> *updatedelegate_;
7694 UITabBarController *root_;
7697 - (void) setTabBarController:(UITabBarController *)controller;
7699 - (void) dropBar:(BOOL)animated;
7700 - (void) beginUpdate;
7701 - (void) raiseBar:(BOOL)animated;
7706 @implementation CYContainer
7708 - (BOOL) _reallyWantsFullScreenLayout {
7712 // NOTE: UIWindow only sends the top controller these messages,
7713 // So we have to forward them on.
7715 - (void) viewDidAppear:(BOOL)animated {
7716 [super viewDidAppear:animated];
7717 [root_ viewDidAppear:animated];
7720 - (void) viewWillAppear:(BOOL)animated {
7721 [super viewWillAppear:animated];
7722 [root_ viewWillAppear:animated];
7725 - (void) viewDidDisappear:(BOOL)animated {
7726 [super viewDidDisappear:animated];
7727 [root_ viewDidDisappear:animated];
7730 - (void) viewWillDisappear:(BOOL)animated {
7731 [super viewWillDisappear:animated];
7732 [root_ viewWillDisappear:animated];
7735 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7736 return ![updatedelegate_ hudIsShowing] && (IsWildcat_ || orientation == UIInterfaceOrientationPortrait);
7739 - (void) setTabBarController:(UITabBarController *)controller {
7741 [[self view] addSubview:[root_ view]];
7744 - (void) setUpdate:(NSDate *)date {
7748 - (void) beginUpdate {
7750 [refreshbar_ start];
7755 detachNewThreadSelector:@selector(performUpdate)
7761 - (void) performUpdate { _pooled
7763 status.setDelegate(self);
7764 [database_ updateWithStatus:status];
7767 performSelectorOnMainThread:@selector(completeUpdate)
7773 - (void) completeUpdate {
7774 if (!updating_) return;
7777 [self raiseBar:YES];
7779 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7782 - (void) cancelUpdate {
7784 [self raiseBar:YES];
7786 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7789 - (void) cancelPressed {
7790 [self cancelUpdate];
7797 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7798 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7801 - (void) startProgress {
7804 - (void) setProgressTitle:(NSString *)title {
7806 performSelectorOnMainThread:@selector(_setProgressTitle:)
7812 - (bool) isCancelling:(size_t)received {
7816 - (void) setProgressPercent:(float)percent {
7818 performSelectorOnMainThread:@selector(_setProgressPercent:)
7819 withObject:[NSNumber numberWithFloat:percent]
7824 - (void) addProgressOutput:(NSString *)output {
7826 performSelectorOnMainThread:@selector(_addProgressOutput:)
7832 - (void) _setProgressTitle:(NSString *)title {
7833 [refreshbar_ setPrompt:title];
7836 - (void) _setProgressPercent:(NSNumber *)percent {
7837 [refreshbar_ setProgress:[percent floatValue]];
7840 - (void) _addProgressOutput:(NSString *)output {
7843 - (void) setUpdateDelegate:(id)delegate {
7844 updatedelegate_ = delegate;
7847 - (CGFloat) statusBarHeight {
7848 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7849 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7851 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7855 - (void) dropBar:(BOOL)animated {
7856 if (dropped_) return;
7859 [[self view] addSubview:refreshbar_];
7861 CGFloat sboffset = [self statusBarHeight];
7863 CGRect barframe = [refreshbar_ frame];
7864 barframe.origin.y = sboffset;
7865 [refreshbar_ setFrame:barframe];
7867 if (animated) [UIView beginAnimations:nil context:NULL];
7868 CGRect viewframe = [[root_ view] frame];
7869 viewframe.origin.y += barframe.size.height + sboffset;
7870 viewframe.size.height -= barframe.size.height + sboffset;
7871 [[root_ view] setFrame:viewframe];
7872 if (animated) [UIView commitAnimations];
7874 // Ensure bar has the proper width for our view, it might have changed
7875 barframe.size.width = viewframe.size.width;
7876 [refreshbar_ setFrame:barframe];
7878 // XXX: fix Apple's layout bug
7879 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7882 - (void) raiseBar:(BOOL)animated {
7883 if (!dropped_) return;
7886 [refreshbar_ removeFromSuperview];
7888 CGFloat sboffset = [self statusBarHeight];
7890 if (animated) [UIView beginAnimations:nil context:NULL];
7891 CGRect barframe = [refreshbar_ frame];
7892 CGRect viewframe = [[root_ view] frame];
7893 viewframe.origin.y -= barframe.size.height + sboffset;
7894 viewframe.size.height += barframe.size.height + sboffset;
7895 [[root_ view] setFrame:viewframe];
7896 if (animated) [UIView commitAnimations];
7898 // XXX: fix Apple's layout bug
7899 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7902 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7903 // XXX: fix Apple's layout bug
7904 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7907 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7913 // XXX: fix Apple's layout bug
7914 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7917 - (void) statusBarFrameChanged:(NSNotification *)notification {
7925 [refreshbar_ release];
7926 [[NSNotificationCenter defaultCenter] removeObserver:self];
7930 - (id) initWithDatabase:(Database *)database {
7931 if ((self = [super init]) != nil) {
7932 database_ = database;
7934 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7935 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7937 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7954 @interface Cydia : UIApplication <
7955 ConfirmationControllerDelegate,
7956 ProgressControllerDelegate,
7958 UINavigationControllerDelegate
7961 CYContainer *container_;
7964 NSMutableArray *essential_;
7965 NSMutableArray *broken_;
7967 Database *database_;
7971 UIKeyboard *keyboard_;
7974 SectionsController *sections_;
7975 ChangesController *changes_;
7976 ManageController *manage_;
7977 SearchController *search_;
7978 SourceTable *sources_;
7979 InstalledController *installed_;
7982 CYStashController *stash_;
7987 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7988 - (void) setPage:(CYViewController *)page;
7993 static _finline void _setHomePage(Cydia *self) {
7994 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7997 @implementation Cydia
7999 - (void) beginUpdate {
8000 [container_ beginUpdate];
8004 return [container_ updating];
8007 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
8012 if ([broken_ count] != 0) {
8013 int count = [broken_ count];
8015 UIAlertView *alert = [[[UIAlertView alloc]
8016 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8017 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8019 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8020 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8023 [alert setContext:@"fixhalf"];
8025 } else if (!Ignored_ && [essential_ count] != 0) {
8026 int count = [essential_ count];
8028 UIAlertView *alert = [[[UIAlertView alloc]
8029 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8030 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8032 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8033 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8036 [alert setContext:@"upgrade"];
8041 - (void) _saveConfig {
8044 NSString *error(nil);
8045 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8047 NSError *error(nil);
8048 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8049 NSLog(@"failure to save metadata data: %@", error);
8052 NSLog(@"failure to serialize metadata: %@", error);
8060 - (void) _updateData {
8063 /* XXX: this is just stupid */
8064 if (tag_ != 1 && sections_ != nil)
8065 [sections_ reloadData];
8066 if (tag_ != 2 && changes_ != nil)
8067 [changes_ reloadData];
8068 if (tag_ != 4 && search_ != nil)
8069 [search_ reloadData];
8071 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8074 - (int)indexOfTabWithTag:(int)tag {
8076 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8077 if ([[controller tabBarItem] tag] == tag) return i;
8084 - (void) _refreshIfPossible {
8085 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8087 bool recently = false;
8088 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8089 if (update != nil) {
8090 NSTimeInterval interval([update timeIntervalSinceNow]);
8091 if (interval <= 0 && interval > -(15*60))
8095 // Don't automatic refresh if:
8096 // - We already refreshed recently.
8097 // - We already auto-refreshed this launch.
8098 // - Auto-refresh is disabled.
8099 if (recently || loaded_ || ManualRefresh) {
8100 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8102 // If we are cancelling due to ManualRefresh or a recent refresh
8103 // we need to make sure it knows it's already loaded.
8107 // We are going to load, so remember that.
8111 SCNetworkReachabilityFlags flags; {
8112 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8113 SCNetworkReachabilityGetFlags(reachability, &flags);
8114 CFRelease(reachability);
8117 // XXX: this elaborate mess is what Apple is using to determine this? :(
8118 // XXX: do we care if the user has to intervene? maybe that's ok?
8120 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8121 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8122 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8123 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8124 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8125 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8129 // If we can reach the server, auto-refresh!
8131 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8136 - (void) refreshIfPossible {
8137 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8140 - (void) _reloadData {
8141 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8142 [hud setText:UCLocalize("RELOADING_DATA")];
8144 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8146 if (hud) [self removeProgressHUD:hud];
8150 [essential_ removeAllObjects];
8151 [broken_ removeAllObjects];
8153 NSArray *packages([database_ packages]);
8154 for (Package *package in packages) {
8156 [broken_ addObject:package];
8157 if ([package upgradableAndEssential:NO]) {
8158 if ([package essential])
8159 [essential_ addObject:package];
8164 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8166 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8167 [changesItem setBadgeValue:badge];
8168 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8170 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8171 [self setApplicationBadge:badge];
8173 [self setApplicationBadgeString:badge];
8175 [changesItem setBadgeValue:nil];
8176 [changesItem setAnimatedBadge:NO];
8178 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8179 [self removeApplicationBadge];
8180 else // XXX: maybe use setApplicationBadgeString also?
8181 [self setApplicationIconBadgeNumber:0];
8186 [self refreshIfPossible];
8189 - (void) updateData {
8190 [database_ setVisible];
8199 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8200 _assert(file != NULL);
8202 for (NSString *key in [Sources_ allKeys]) {
8203 NSDictionary *source([Sources_ objectForKey:key]);
8205 fprintf(file, "%s %s %s\n",
8206 [[source objectForKey:@"Type"] UTF8String],
8207 [[source objectForKey:@"URI"] UTF8String],
8208 [[source objectForKey:@"Distribution"] UTF8String]
8216 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8217 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8218 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8219 [container_ presentModalViewController:navigation animated:YES];
8222 detachNewThreadSelector:@selector(update_)
8225 title:UCLocalize("UPDATING_SOURCES")
8229 - (void) reloadData {
8230 @synchronized (self) {
8236 pkgProblemResolver *resolver = [database_ resolver];
8238 resolver->InstallProtect();
8239 if (!resolver->Resolve(true))
8243 - (CGRect) popUpBounds {
8244 return [[tabbar_ view] bounds];
8248 if (![database_ prepare])
8251 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8252 [page setDelegate:self];
8253 CYNavigationController *confirm_ = [[CYNavigationController alloc] initWithRootViewController:page];
8254 [confirm_ setDelegate:self];
8256 if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8257 [container_ presentModalViewController:confirm_ animated:YES];
8263 @synchronized (self) {
8268 - (void) clearPackage:(Package *)package {
8269 @synchronized (self) {
8276 - (void) installPackages:(NSArray *)packages {
8277 @synchronized (self) {
8278 for (Package *package in packages)
8285 - (void) installPackage:(Package *)package {
8286 @synchronized (self) {
8293 - (void) removePackage:(Package *)package {
8294 @synchronized (self) {
8301 - (void) distUpgrade {
8302 @synchronized (self) {
8303 if (![database_ upgrade])
8310 @synchronized (self) {
8315 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8316 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8318 if (navigation != nil) {
8319 [navigation pushViewController:progress animated:YES];
8321 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8322 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8323 [container_ presentModalViewController:navigation animated:YES];
8327 detachNewThreadSelector:@selector(perform)
8330 title:UCLocalize("RUNNING")
8334 - (void) progressControllerIsComplete:(ProgressController *)progress {
8338 - (void) setPage:(CYViewController *)page {
8339 [page setDelegate:self];
8341 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8342 [navController setViewControllers:[NSArray arrayWithObject:page]];
8343 for (CYNavigationController *page in [tabbar_ viewControllers]) {
8344 if (page != navController) [page setViewControllers:nil];
8348 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8349 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8350 [browser loadURL:url];
8354 - (SectionsController *) sectionsController {
8355 if (sections_ == nil)
8356 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8360 - (ChangesController *) changesController {
8361 if (changes_ == nil)
8362 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8366 - (ManageController *) manageController {
8367 if (manage_ == nil) {
8368 manage_ = (ManageController *) [[self
8369 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8370 withClass:[ManageController class]
8372 if (!IsWildcat_) queueDelegate_ = manage_;
8377 - (SearchController *) searchController {
8379 search_ = [[SearchController alloc] initWithDatabase:database_];
8383 - (SourceTable *) sourcesController {
8384 if (sources_ == nil)
8385 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8389 - (InstalledController *) installedController {
8390 if (installed_ == nil) {
8391 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8392 if (IsWildcat_) queueDelegate_ = installed_;
8397 - (void) tabBarController:(id)tabBarController didSelectViewController:(UIViewController *)viewController {
8398 int tag = [[viewController tabBarItem] tag];
8400 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8402 } else if (tag_ == 1) {
8403 [[self sectionsController] resetView];
8407 case kCydiaTag: _setHomePage(self); break;
8409 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8410 case kChangesTag: [self setPage:[self changesController]]; break;
8411 case kManageTag: [self setPage:[self manageController]]; break;
8412 case kInstalledTag: [self setPage:[self installedController]]; break;
8413 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8414 case kSearchTag: [self setPage:[self searchController]]; break;
8422 - (void) showSettings {
8423 RoleController *role = [[RoleController alloc] initWithDatabase:database_ delegate:self];
8424 CYNavigationController *nav = [[CYNavigationController alloc] initWithRootViewController:role];
8425 if (IsWildcat_) [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8426 [container_ presentModalViewController:nav animated:YES];
8429 - (void) setPackageController:(PackageController *)view {
8431 [view setPackage:nil];
8435 - (PackageController *) _packageController {
8436 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8439 - (PackageController *) packageController {
8440 return [self _packageController];
8443 // Returns the navigation controller for the queuing badge.
8444 - (id) queueBadgeController {
8445 int index = [self indexOfTabWithTag:kManageTag];
8446 if (index == -1) index = [self indexOfTabWithTag:kInstalledTag];
8448 return [[tabbar_ viewControllers] objectAtIndex:index];
8451 - (void) cancelAndClear:(bool)clear {
8452 @synchronized (self) {
8455 pkgCacheFile &cache([database_ cache]);
8456 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
8457 // Unmark method taken from Synaptic Package Manager.
8458 // Thanks for being sane, unlike Aptitude.
8459 if (!cache[iterator].Keep()) {
8460 cache->MarkKeep(iterator, false);
8461 cache->SetReInstall(iterator, false);
8467 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
8471 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8474 // Show the changes in the current view.
8475 [(CYNavigationController *) [tabbar_ selectedViewController] reloadData];
8476 [queueDelegate_ queueStatusDidChange];
8480 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8481 NSString *context([alert context]);
8483 if ([context isEqualToString:@"fixhalf"]) {
8484 if (button == [alert firstOtherButtonIndex]) {
8485 @synchronized (self) {
8486 for (Package *broken in broken_) {
8489 NSString *id = [broken id];
8490 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8491 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8492 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8493 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8499 } else if (button == [alert cancelButtonIndex]) {
8500 [broken_ removeAllObjects];
8504 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8505 } else if ([context isEqualToString:@"upgrade"]) {
8506 if (button == [alert firstOtherButtonIndex]) {
8507 @synchronized (self) {
8508 for (Package *essential in essential_)
8509 [essential install];
8514 } else if (button == [alert firstOtherButtonIndex] + 1) {
8516 } else if (button == [alert cancelButtonIndex]) {
8520 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8524 - (void) system:(NSString *)command { _pooled
8525 system([command UTF8String]);
8528 - (void) applicationWillSuspend {
8530 [super applicationWillSuspend];
8533 - (BOOL) hudIsShowing {
8537 - (void) applicationSuspend:(__GSEvent *)event {
8538 // Use external process status API internally.
8539 // This is probably a really bad idea.
8540 uint64_t status = 0;
8542 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8543 notify_get_state(notify_token, &status);
8544 notify_cancel(notify_token);
8547 if (![self hudIsShowing] && status == 0)
8548 [super applicationSuspend:event];
8551 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8552 if (![self hudIsShowing])
8553 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8556 - (void) _setSuspended:(BOOL)value {
8557 if (![self hudIsShowing])
8558 [super _setSuspended:value];
8561 - (UIProgressHUD *) addProgressHUD {
8562 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8563 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8565 [window_ setUserInteractionEnabled:NO];
8568 UIViewController *target = container_;
8569 while ([target modalViewController] != nil) target = [target modalViewController];
8570 [[target view] addSubview:hud];
8576 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8578 [hud removeFromSuperview];
8579 [window_ setUserInteractionEnabled:YES];
8583 - (CYViewController *) pageForPackage:(NSString *)name {
8584 if (Package *package = [database_ packageWithName:name]) {
8585 PackageController *view([self packageController]);
8586 [view setPackage:package];
8589 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8590 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8591 return [self _pageForURL:url withClass:[CYBrowserController class]];
8595 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8599 NSString *href([url absoluteString]);
8600 if ([href hasPrefix:@"apptapp://package/"])
8601 return [self pageForPackage:[href substringFromIndex:18]];
8603 NSString *scheme([[url scheme] lowercaseString]);
8604 if (![scheme isEqualToString:@"cydia"])
8606 NSString *path([url absoluteString]);
8607 if ([path length] < 8)
8609 path = [path substringFromIndex:8];
8610 if (![path hasPrefix:@"/"])
8611 path = [@"/" stringByAppendingString:path];
8613 if ([path isEqualToString:@"/add-source"])
8614 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8615 else if ([path isEqualToString:@"/storage"])
8616 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8617 else if ([path isEqualToString:@"/sources"])
8618 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8619 else if ([path isEqualToString:@"/packages"])
8620 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8621 else if ([path hasPrefix:@"/url/"])
8622 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8623 else if ([path hasPrefix:@"/launch/"])
8624 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8625 else if ([path hasPrefix:@"/package-settings/"])
8626 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8627 else if ([path hasPrefix:@"/package-signature/"])
8628 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8629 else if ([path hasPrefix:@"/package/"])
8630 return [self pageForPackage:[path substringFromIndex:9]];
8631 else if ([path hasPrefix:@"/files/"]) {
8632 NSString *name = [path substringFromIndex:7];
8634 if (Package *package = [database_ packageWithName:name]) {
8635 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8636 [files setPackage:package];
8644 - (void) applicationOpenURL:(NSURL *)url {
8645 [super applicationOpenURL:url];
8647 if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
8648 [self setPage:page];
8650 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8654 - (void) applicationWillResignActive:(UIApplication *)application {
8655 // Stop refreshing if you get a phone call or lock the device.
8656 if ([container_ updating]) [container_ cancelUpdate];
8658 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8659 [super applicationWillResignActive:application];
8662 - (void) addStashController {
8663 stash_ = [[CYStashController alloc] init];
8664 [window_ addSubview:[stash_ view]];
8667 - (void) removeStashController {
8668 [[stash_ view] removeFromSuperview];
8673 [self setIdleTimerDisabled:YES];
8675 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8676 [self setStatusBarShowsProgress:YES];
8677 UpdateExternalStatus(1);
8679 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8681 UpdateExternalStatus(0);
8682 [self setStatusBarShowsProgress:NO];
8684 [self removeStashController];
8686 if (ExecFork() == 0) {
8687 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8688 perror("launchctl stop");
8692 - (void) setupTabBarController {
8693 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8694 [tabbar_ setDelegate:self];
8696 NSMutableArray *items([NSMutableArray arrayWithObjects:
8697 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8698 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8699 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8700 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8704 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8705 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8707 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8710 NSMutableArray *controllers([NSMutableArray array]);
8712 for (UITabBarItem *item in items) {
8713 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8714 [controller setTabBarItem:item];
8715 [controllers addObject:controller];
8718 [tabbar_ setViewControllers:controllers];
8721 - (void) applicationDidFinishLaunching:(id)unused {
8722 [CYBrowserController _initialize];
8724 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8726 Font12_ = [[UIFont systemFontOfSize:12] retain];
8727 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8728 Font14_ = [[UIFont systemFontOfSize:14] retain];
8729 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8730 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8734 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8735 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8737 UIScreen *screen([UIScreen mainScreen]);
8739 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8740 [window_ orderFront:self];
8741 [window_ makeKey:self];
8742 [window_ setHidden:NO];
8745 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8746 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8747 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8748 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8749 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8750 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8751 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8752 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8753 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8756 [self addStashController];
8757 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8761 database_ = [Database sharedInstance];
8763 [self setupTabBarController];
8765 container_ = [[CYContainer alloc] initWithDatabase:database_];
8766 [container_ setUpdateDelegate:self];
8767 [container_ setTabBarController:tabbar_];
8768 [window_ addSubview:[container_ view]];
8770 // Show pinstripes while loading data.
8771 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8773 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8780 [self showSettings];
8784 [window_ setUserInteractionEnabled:NO];
8786 UIView *container = [[UIView alloc] init];
8787 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8789 UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
8790 [spinner startAnimating];
8791 [container addSubview:spinner];
8794 UILabel *label = [[UILabel alloc] init];
8795 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8796 [label setBackgroundColor:[UIColor clearColor]];
8797 [label setTextColor:[UIColor blackColor]];
8798 [label setShadowColor:[UIColor whiteColor]];
8799 [label setShadowOffset:CGSizeMake(0, 1)];
8800 [label setText:UCLocalize("LOADING_DATA")];
8801 [container addSubview:label];
8804 CGSize viewsize = [[tabbar_ view] frame].size;
8805 CGSize spinnersize = [spinner bounds].size;
8806 CGSize textsize = [[label text] sizeWithFont:[label font]];
8807 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8809 CGRect containrect = {
8810 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8811 CGSizeMake(bothwidth, spinnersize.height)
8814 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8822 [container setFrame:containrect];
8823 [spinner setFrame:spinrect];
8824 [label setFrame:textrect];
8825 [[container_ view] addSubview:container];
8826 [container release];
8831 // Show the home page
8832 [tabbar_ setSelectedIndex:0];
8834 [window_ setUserInteractionEnabled:YES];
8836 // XXX: does this actually slow anything down?
8837 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8838 [container removeFromSuperview];
8841 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8842 if (item != nil && IsWildcat_) {
8843 [sheet showFromBarButtonItem:item animated:YES];
8845 [sheet showInView:window_];
8852 id Alloc_(id self, SEL selector) {
8853 id object = alloc_(self, selector);
8854 lprintf("[%s]A-%p\n", self->isa->name, object);
8859 id Dealloc_(id self, SEL selector) {
8860 id object = dealloc_(self, selector);
8861 lprintf("[%s]D-%p\n", self->isa->name, object);
8865 Class $WebDefaultUIKitDelegate;
8867 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8868 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8869 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8870 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8873 static NSNumber *shouldPlayKeyboardSounds;
8877 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8879 case 1104: // Keyboard Button Clicked
8880 case 1105: // Keyboard Delete Repeated
8881 if (shouldPlayKeyboardSounds == nil) {
8882 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8883 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8886 if (![shouldPlayKeyboardSounds boolValue])
8890 _UIHardware$_playSystemSound$(self, _cmd, sound);
8894 int main(int argc, char *argv[]) { _pooled
8897 if (Class $UIDevice = objc_getClass("UIDevice")) {
8898 UIDevice *device([$UIDevice currentDevice]);
8899 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8903 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8905 /* Library Hacks {{{ */
8906 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8908 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8909 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8910 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8911 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8912 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8915 $UIHardware = objc_getClass("UIHardware");
8916 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8917 if (UIHardware$_playSystemSound$ != NULL) {
8918 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8919 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8922 /* Set Locale {{{ */
8923 Locale_ = CFLocaleCopyCurrent();
8924 Languages_ = [NSLocale preferredLanguages];
8925 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8926 //NSLog(@"%@", [Languages_ description]);
8929 if (Languages_ == nil || [Languages_ count] == 0)
8930 // XXX: consider just setting to C and then falling through?
8933 lang = [[Languages_ objectAtIndex:0] UTF8String];
8934 setenv("LANG", lang, true);
8937 //std::setlocale(LC_ALL, lang);
8938 NSLog(@"Setting Language: %s", lang);
8941 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8943 /* Parse Arguments {{{ */
8944 bool substrate(false);
8950 for (int argi(1); argi != argc; ++argi)
8951 if (strcmp(argv[argi], "--") == 0) {
8953 argv[argi] = argv[0];
8959 for (int argi(1); argi != arge; ++argi)
8960 if (strcmp(args[argi], "--substrate") == 0)
8963 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8967 App_ = [[NSBundle mainBundle] bundlePath];
8968 Home_ = NSHomeDirectory();
8974 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8975 alloc_ = alloc->method_imp;
8976 alloc->method_imp = (IMP) &Alloc_;*/
8978 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8979 dealloc_ = dealloc->method_imp;
8980 dealloc->method_imp = (IMP) &Dealloc_;*/
8982 /* System Information {{{ */
8986 size = sizeof(maxproc);
8987 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8988 perror("sysctlbyname(\"kern.maxproc\", ?)");
8989 else if (maxproc < 64) {
8991 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8992 perror("sysctlbyname(\"kern.maxproc\", #)");
8995 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8996 char *osversion = new char[size];
8997 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8998 perror("sysctlbyname(\"kern.osversion\", ?)");
9000 System_ = [NSString stringWithUTF8String:osversion];
9002 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9003 char *machine = new char[size];
9004 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9005 perror("sysctlbyname(\"hw.machine\", ?)");
9009 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9010 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9011 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9012 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9016 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9017 NSData *data((NSData *) ecid);
9018 size_t length([data length]);
9019 uint8_t bytes[length];
9020 [data getBytes:bytes];
9021 char string[length * 2 + 1];
9022 for (size_t i(0); i != length; ++i)
9023 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9024 ChipID_ = [NSString stringWithUTF8String:string];
9028 IOObjectRelease(service);
9032 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9034 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9035 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9036 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9038 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9039 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9040 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9042 if (mcc != NULL && mnc != NULL)
9043 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9050 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9051 Build_ = [system objectForKey:@"ProductBuildVersion"];
9052 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9053 Product_ = [info objectForKey:@"SafariProductVersion"];
9054 Safari_ = [info objectForKey:@"CFBundleVersion"];
9057 /* Load Database {{{ */
9059 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9061 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9063 if (Metadata_ == NULL)
9064 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9066 Settings_ = [Metadata_ objectForKey:@"Settings"];
9068 Packages_ = [Metadata_ objectForKey:@"Packages"];
9069 Sections_ = [Metadata_ objectForKey:@"Sections"];
9070 Sources_ = [Metadata_ objectForKey:@"Sources"];
9072 Token_ = [Metadata_ objectForKey:@"Token"];
9075 if (Settings_ != nil)
9076 Role_ = [Settings_ objectForKey:@"Role"];
9078 if (Packages_ == nil) {
9079 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
9080 [Metadata_ setObject:Packages_ forKey:@"Packages"];
9083 if (Sections_ == nil) {
9084 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9085 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9088 if (Sources_ == nil) {
9089 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9090 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9094 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9096 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9097 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9098 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9099 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9100 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9101 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9103 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9105 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9106 unlink("/tmp/.cydia.fw");
9108 } else if (access("/User", F_OK) != 0 || version < 2) {
9111 system("/usr/libexec/cydia/firmware.sh");
9115 _assert([[NSFileManager defaultManager]
9116 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9117 withIntermediateDirectories:YES
9122 if (access("/tmp/cydia.chk", F_OK) == 0) {
9123 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9124 _assert(errno == ENOENT);
9125 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9126 _assert(errno == ENOENT);
9129 /* APT Initialization {{{ */
9130 _assert(pkgInitConfig(*_config));
9131 _assert(pkgInitSystem(*_config, _system));
9134 _config->Set("APT::Acquire::Translation", lang);
9136 // XXX: this timeout might be important :(
9137 //_config->Set("Acquire::http::Timeout", 15);
9139 _config->Set("Acquire::http::MaxParallel", 3);
9141 /* Color Choices {{{ */
9142 space_ = CGColorSpaceCreateDeviceRGB();
9144 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9145 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9146 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9147 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9148 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9149 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9150 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9151 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9152 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9154 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9155 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9157 /* UIKit Configuration {{{ */
9158 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9159 if ($GSFontSetUseLegacyFontMetrics != NULL)
9160 $GSFontSetUseLegacyFontMetrics(YES);
9162 // XXX: I have a feeling this was important
9163 //UIKeyboardDisableAutomaticAppearance();
9166 Colon_ = UCLocalize("COLON_DELIMITED");
9167 Error_ = UCLocalize("ERROR");
9168 Warning_ = UCLocalize("WARNING");
9171 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9173 CGColorSpaceRelease(space_);