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 {{{ */
704 _finline void clear_() {
705 if (cache_ != NULL) {
712 _finline bool empty() const {
716 _finline size_t size() const {
720 _finline char *data() const {
724 _finline void clear() {
729 _finline CYString() :
736 _finline ~CYString() {
740 void operator =(const CYString &rhs) {
744 if (rhs.cache_ == nil)
747 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
750 void set(apr_pool_t *pool, const char *data, size_t size) {
756 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
757 memcpy(temp, data, size);
764 _finline void set(apr_pool_t *pool, const char *data) {
765 set(pool, data, data == NULL ? 0 : strlen(data));
768 _finline void set(apr_pool_t *pool, const std::string &rhs) {
769 set(pool, rhs.data(), rhs.size());
772 bool operator ==(const CYString &rhs) const {
773 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
776 operator CFStringRef() {
777 if (cache_ == NULL) {
780 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
782 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
786 _finline operator id() {
787 return (NSString *) static_cast<CFStringRef>(*this);
791 /* C++ NSString Algorithm Adapters {{{ */
793 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
796 struct NSStringMapHash :
797 std::unary_function<NSString *, size_t>
799 _finline size_t operator ()(NSString *value) const {
800 return CFStringHashNSString((CFStringRef) value);
804 struct NSStringMapLess :
805 std::binary_function<NSString *, NSString *, bool>
807 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
808 return [lhs compare:rhs] == NSOrderedAscending;
812 struct NSStringMapEqual :
813 std::binary_function<NSString *, NSString *, bool>
815 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
816 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
817 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
818 //[lhs isEqualToString:rhs];
823 /* Perl-Compatible RegEx {{{ */
833 Pcre(const char *regex) :
838 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
841 lprintf("%d:%s\n", offset, error);
845 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
846 matches_ = new int[(capture_ + 1) * 3];
854 NSString *operator [](size_t match) {
855 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
858 bool operator ()(NSString *data) {
859 // XXX: length is for characters, not for bytes
860 return operator ()([data UTF8String], [data length]);
863 bool operator ()(const char *data, size_t size) {
865 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
869 /* Mime Addresses {{{ */
870 @interface Address : NSObject {
876 - (NSString *) address;
878 - (void) setAddress:(NSString *)address;
880 + (Address *) addressWithString:(NSString *)string;
881 - (Address *) initWithString:(NSString *)string;
884 @implementation Address
893 - (NSString *) name {
897 - (NSString *) address {
901 - (void) setAddress:(NSString *)address {
903 [address_ autorelease];
907 address_ = [address retain];
910 + (Address *) addressWithString:(NSString *)string {
911 return [[[Address alloc] initWithString:string] autorelease];
914 + (NSArray *) _attributeKeys {
915 return [NSArray arrayWithObjects:@"address", @"name", nil];
918 - (NSArray *) attributeKeys {
919 return [[self class] _attributeKeys];
922 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
923 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
926 - (Address *) initWithString:(NSString *)string {
927 if ((self = [super init]) != nil) {
928 const char *data = [string UTF8String];
929 size_t size = [string length];
931 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
933 if (address_r(data, size)) {
934 name_ = [address_r[1] retain];
935 address_ = [address_r[2] retain];
937 name_ = [string retain];
945 /* CoreGraphics Primitives {{{ */
956 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
959 Set(space, red, green, blue, alpha);
964 CGColorRelease(color_);
971 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
973 float color[] = {red, green, blue, alpha};
974 color_ = CGColorCreate(space, (CGFloat *) color);
977 operator CGColorRef() {
983 /* Random Global Variables {{{ */
984 static const int PulseInterval_ = 50000;
985 static const int ButtonBarWidth_ = 60;
986 static const int ButtonBarHeight_ = 48;
987 static const float KeyboardTime_ = 0.3f;
990 static NSArray *Finishes_;
992 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
993 #define NotifyConfig_ "/etc/notify.conf"
995 static bool Queuing_;
997 static CYColor Blue_;
998 static CYColor Blueish_;
999 static CYColor Black_;
1000 static CYColor Off_;
1001 static CYColor White_;
1002 static CYColor Gray_;
1003 static CYColor Green_;
1004 static CYColor Purple_;
1005 static CYColor Purplish_;
1007 static UIColor *InstallingColor_;
1008 static UIColor *RemovingColor_;
1010 static NSString *App_;
1011 static NSString *Home_;
1013 static BOOL Advanced_;
1014 static BOOL Ignored_;
1016 static UIFont *Font12_;
1017 static UIFont *Font12Bold_;
1018 static UIFont *Font14_;
1019 static UIFont *Font18Bold_;
1020 static UIFont *Font22Bold_;
1022 static const char *Machine_ = NULL;
1023 static NSString *System_ = nil;
1024 static NSString *SerialNumber_ = nil;
1025 static NSString *ChipID_ = nil;
1026 static NSString *Token_ = nil;
1027 static NSString *UniqueID_ = nil;
1028 static NSString *PLMN_ = nil;
1029 static NSString *Build_ = nil;
1030 static NSString *Product_ = nil;
1031 static NSString *Safari_ = nil;
1033 static CFLocaleRef Locale_;
1034 static NSArray *Languages_;
1035 static CGColorSpaceRef space_;
1037 static NSDictionary *SectionMap_;
1038 static NSMutableDictionary *Metadata_;
1039 static _transient NSMutableDictionary *Settings_;
1040 static _transient NSString *Role_;
1041 static _transient NSMutableDictionary *Packages_;
1042 static _transient NSMutableDictionary *Sections_;
1043 static _transient NSMutableDictionary *Sources_;
1044 static bool Changed_;
1045 static NSDate *now_;
1047 static bool IsWildcat_;
1050 /* Display Helpers {{{ */
1051 inline float Interpolate(float begin, float end, float fraction) {
1052 return (end - begin) * fraction + begin;
1055 /* XXX: localize this! */
1056 NSString *SizeString(double size) {
1057 bool negative = size < 0;
1062 while (size > 1024) {
1067 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1069 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1072 static _finline CFStringRef CFCString(const char *value) {
1073 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1076 const char *StripVersion_(const char *version) {
1077 const char *colon(strchr(version, ':'));
1079 version = colon + 1;
1083 CFStringRef StripVersion(const char *version) {
1084 const char *colon(strchr(version, ':'));
1086 version = colon + 1;
1087 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1089 return CFCString(version);
1092 NSString *LocalizeSection(NSString *section) {
1093 static Pcre title_r("^(.*?) \\((.*)\\)$");
1094 if (title_r(section)) {
1095 NSString *parent(title_r[1]);
1096 NSString *child(title_r[2]);
1098 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1099 LocalizeSection(parent),
1100 LocalizeSection(child)
1104 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1107 NSString *Simplify(NSString *title) {
1108 const char *data = [title UTF8String];
1109 size_t size = [title length];
1111 static Pcre square_r("^\\[(.*)\\]$");
1112 if (square_r(data, size))
1113 return Simplify(square_r[1]);
1115 static Pcre paren_r("^\\((.*)\\)$");
1116 if (paren_r(data, size))
1117 return Simplify(paren_r[1]);
1119 static Pcre title_r("^(.*?) \\((.*)\\)$");
1120 if (title_r(data, size))
1121 return Simplify(title_r[1]);
1127 NSString *GetLastUpdate() {
1128 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1131 return UCLocalize("NEVER_OR_UNKNOWN");
1133 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1134 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1136 CFRelease(formatter);
1138 return [(NSString *) formatted autorelease];
1141 bool isSectionVisible(NSString *section) {
1142 NSDictionary *metadata([Sections_ objectForKey:section]);
1143 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1144 return hidden == nil || ![hidden boolValue];
1149 /* Delegate Prototypes {{{ */
1153 @interface NSObject (ProgressDelegate)
1156 @protocol ProgressDelegate
1157 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1158 - (void) setProgressTitle:(NSString *)title;
1159 - (void) setProgressPercent:(float)percent;
1160 - (void) startProgress;
1161 - (void) addProgressOutput:(NSString *)output;
1162 - (bool) isCancelling:(size_t)received;
1165 @protocol ConfigurationDelegate
1166 - (void) repairWithSelector:(SEL)selector;
1167 - (void) setConfigurationData:(NSString *)data;
1170 @class PackageController;
1172 @protocol CydiaDelegate
1173 - (void) setPackageController:(PackageController *)view;
1174 - (void) clearPackage:(Package *)package;
1175 - (void) installPackage:(Package *)package;
1176 - (void) installPackages:(NSArray *)packages;
1177 - (void) removePackage:(Package *)package;
1178 - (void) beginUpdate;
1180 - (void) distUpgrade;
1182 - (void) updateData;
1184 - (void) showSettings;
1185 - (UIProgressHUD *) addProgressHUD;
1186 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1187 - (CYViewController *) pageForPackage:(NSString *)name;
1188 - (PackageController *) packageController;
1189 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1193 /* Status Delegation {{{ */
1195 public pkgAcquireStatus
1198 _transient NSObject<ProgressDelegate> *delegate_;
1206 void setDelegate(id delegate) {
1207 delegate_ = delegate;
1210 NSObject<ProgressDelegate> *getDelegate() const {
1214 virtual bool MediaChange(std::string media, std::string drive) {
1218 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1221 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1222 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1223 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1226 virtual void Done(pkgAcquire::ItemDesc &item) {
1229 virtual void Fail(pkgAcquire::ItemDesc &item) {
1231 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1232 item.Owner->Status == pkgAcquire::Item::StatDone
1236 std::string &error(item.Owner->ErrorText);
1240 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1241 NSArray *fields([description componentsSeparatedByString:@" "]);
1242 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1244 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1245 withObject:[NSArray arrayWithObjects:
1246 [NSString stringWithUTF8String:error.c_str()],
1253 virtual bool Pulse(pkgAcquire *Owner) {
1254 bool value = pkgAcquireStatus::Pulse(Owner);
1257 double(CurrentBytes + CurrentItems) /
1258 double(TotalBytes + TotalItems)
1261 [delegate_ setProgressPercent:percent];
1262 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1265 virtual void Start() {
1266 [delegate_ startProgress];
1269 virtual void Stop() {
1273 /* Progress Delegation {{{ */
1278 _transient id<ProgressDelegate> delegate_;
1282 virtual void Update() {
1283 /*if (abs(Percent - percent_) > 2)
1284 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1288 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1289 [delegate_ setProgressPercent:(Percent / 100)];*/
1299 void setDelegate(id delegate) {
1300 delegate_ = delegate;
1303 id getDelegate() const {
1307 virtual void Done() {
1309 //[delegate_ setProgressPercent:1];
1314 /* Database Interface {{{ */
1315 typedef std::map< unsigned long, _H<Source> > SourceMap;
1317 @interface Database : NSObject {
1323 pkgCacheFile cache_;
1324 pkgDepCache::Policy *policy_;
1325 pkgRecords *records_;
1326 pkgProblemResolver *resolver_;
1327 pkgAcquire *fetcher_;
1329 SPtr<pkgPackageManager> manager_;
1330 pkgSourceList *list_;
1333 CFMutableArrayRef packages_;
1335 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1344 + (Database *) sharedInstance;
1347 - (void) _readCydia:(NSNumber *)fd;
1348 - (void) _readStatus:(NSNumber *)fd;
1349 - (void) _readOutput:(NSNumber *)fd;
1353 - (Package *) packageWithName:(NSString *)name;
1355 - (pkgCacheFile &) cache;
1356 - (pkgDepCache::Policy *) policy;
1357 - (pkgRecords *) records;
1358 - (pkgProblemResolver *) resolver;
1359 - (pkgAcquire &) fetcher;
1360 - (pkgSourceList &) list;
1361 - (NSArray *) packages;
1362 - (NSArray *) sources;
1363 - (void) reloadData;
1371 - (void) setVisible;
1373 - (void) updateWithStatus:(Status &)status;
1375 - (void) setDelegate:(id)delegate;
1376 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1379 /* Delegate Helpers {{{ */
1380 @implementation NSObject (ProgressDelegate)
1382 - (void) _setProgressErrorPackage:(NSArray *)args {
1383 [self performSelector:@selector(setProgressError:forPackage:)
1384 withObject:[args objectAtIndex:0]
1385 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1389 - (void) _setProgressErrorTitle:(NSArray *)args {
1390 [self performSelector:@selector(setProgressError:withTitle:)
1391 withObject:[args objectAtIndex:0]
1392 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1396 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1397 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1398 withObject:[NSArray arrayWithObjects:error, title, nil]
1403 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1404 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1406 [self performSelector:@selector(setProgressError:withTitle:)
1408 withObject:(package == nil ? id : [package name])
1415 /* Source Class {{{ */
1416 @interface Source : NSObject {
1417 CYString depiction_;
1418 CYString description_;
1424 CYString distribution_;
1429 NSString *authority_;
1431 CYString defaultIcon_;
1433 NSDictionary *record_;
1437 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1439 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1441 - (NSString *) depictionForPackage:(NSString *)package;
1442 - (NSString *) supportForPackage:(NSString *)package;
1444 - (NSDictionary *) record;
1448 - (NSString *) distribution;
1449 - (NSString *) type;
1451 - (NSString *) host;
1453 - (NSString *) name;
1454 - (NSString *) description;
1455 - (NSString *) label;
1456 - (NSString *) origin;
1457 - (NSString *) version;
1459 - (NSString *) defaultIcon;
1463 @implementation Source
1467 distribution_.clear();
1470 description_.clear();
1476 defaultIcon_.clear();
1478 if (record_ != nil) {
1488 if (authority_ != nil) {
1489 [authority_ release];
1499 + (NSArray *) _attributeKeys {
1500 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1503 - (NSArray *) attributeKeys {
1504 return [[self class] _attributeKeys];
1507 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1508 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1511 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1514 trusted_ = index->IsTrusted();
1516 uri_.set(pool, index->GetURI());
1517 distribution_.set(pool, index->GetDist());
1518 type_.set(pool, index->GetType());
1520 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1521 if (dindex != NULL) {
1523 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1526 pkgTagFile tags(&fd);
1528 pkgTagSection section;
1535 {"default-icon", &defaultIcon_},
1536 {"depiction", &depiction_},
1537 {"description", &description_},
1539 {"origin", &origin_},
1540 {"support", &support_},
1541 {"version", &version_},
1544 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1545 const char *start, *end;
1547 if (section.Find(names[i].name_, start, end)) {
1548 CYString &value(*names[i].value_);
1549 value.set(pool, start, end - start);
1555 record_ = [Sources_ objectForKey:[self key]];
1557 record_ = [record_ retain];
1559 NSURL *url([NSURL URLWithString:uri_]);
1563 host_ = [[host_ lowercaseString] retain];
1568 authority_ = [url path];
1570 if (authority_ != nil)
1571 authority_ = [authority_ retain];
1574 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1575 if ((self = [super init]) != nil) {
1576 [self setMetaIndex:index inPool:pool];
1580 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1581 NSDictionary *lhr = [self record];
1582 NSDictionary *rhr = [source record];
1585 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1587 NSString *lhs = [self name];
1588 NSString *rhs = [source name];
1590 if ([lhs length] != 0 && [rhs length] != 0) {
1591 unichar lhc = [lhs characterAtIndex:0];
1592 unichar rhc = [rhs characterAtIndex:0];
1594 if (isalpha(lhc) && !isalpha(rhc))
1595 return NSOrderedAscending;
1596 else if (!isalpha(lhc) && isalpha(rhc))
1597 return NSOrderedDescending;
1600 return [lhs compare:rhs options:LaxCompareOptions_];
1603 - (NSString *) depictionForPackage:(NSString *)package {
1604 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1607 - (NSString *) supportForPackage:(NSString *)package {
1608 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1611 - (NSDictionary *) record {
1619 - (NSString *) uri {
1623 - (NSString *) distribution {
1624 return distribution_;
1627 - (NSString *) type {
1631 - (NSString *) key {
1632 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1635 - (NSString *) host {
1639 - (NSString *) name {
1640 return origin_.empty() ? authority_ : origin_;
1643 - (NSString *) description {
1644 return description_;
1647 - (NSString *) label {
1648 return label_.empty() ? authority_ : label_;
1651 - (NSString *) origin {
1655 - (NSString *) version {
1659 - (NSString *) defaultIcon {
1660 return defaultIcon_;
1665 /* Relationship Class {{{ */
1666 @interface Relationship : NSObject {
1671 - (NSString *) type;
1673 - (NSString *) name;
1677 @implementation Relationship
1685 - (NSString *) type {
1693 - (NSString *) name {
1700 /* Package Class {{{ */
1701 @interface Package : NSObject {
1705 pkgCache::VerIterator version_;
1706 pkgCache::PkgIterator iterator_;
1707 _transient Database *database_;
1708 pkgCache::VerFileIterator file_;
1715 NSString *section$_;
1722 CYString installed_;
1728 CYString depiction_;
1739 NSMutableArray *tags_;
1742 NSArray *relationships_;
1744 NSMutableDictionary *metadata_;
1745 _transient NSDate *firstSeen_;
1746 _transient NSDate *lastSeen_;
1750 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1751 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1753 - (pkgCache::PkgIterator) iterator;
1756 - (NSString *) section;
1757 - (NSString *) simpleSection;
1759 - (NSString *) longSection;
1760 - (NSString *) shortSection;
1764 - (Address *) maintainer;
1766 - (NSString *) longDescription;
1767 - (NSString *) shortDescription;
1770 - (NSMutableDictionary *) metadata;
1772 - (BOOL) subscribed;
1775 - (NSString *) latest;
1776 - (NSString *) installed;
1777 - (BOOL) uninstalled;
1780 - (BOOL) upgradableAndEssential:(BOOL)essential;
1783 - (BOOL) unfiltered;
1787 - (BOOL) halfConfigured;
1788 - (BOOL) halfInstalled;
1790 - (NSString *) mode;
1792 - (void) setVisible;
1795 - (NSString *) name;
1797 - (NSString *) homepage;
1798 - (NSString *) depiction;
1799 - (Address *) author;
1801 - (NSString *) support;
1803 - (NSArray *) files;
1804 - (NSArray *) relationships;
1805 - (NSArray *) warnings;
1806 - (NSArray *) applications;
1808 - (Source *) source;
1809 - (NSString *) role;
1811 - (BOOL) matches:(NSString *)text;
1813 - (bool) hasSupportingRole;
1814 - (BOOL) hasTag:(NSString *)tag;
1815 - (NSString *) primaryPurpose;
1816 - (NSArray *) purposes;
1817 - (bool) isCommercial;
1819 - (CYString &) cyname;
1821 - (uint32_t) compareBySection:(NSArray *)sections;
1823 - (uint32_t) compareForChanges;
1828 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1829 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1830 - (bool) isInstalledAndVisible:(NSNumber *)number;
1831 - (bool) isVisibleInSection:(NSString *)section;
1832 - (bool) isVisibleInSource:(Source *)source;
1836 uint32_t PackageChangesRadix(Package *self, void *) {
1841 uint32_t timestamp : 30;
1842 uint32_t ignored : 1;
1843 uint32_t upgradable : 1;
1847 bool upgradable([self upgradableAndEssential:YES]);
1848 value.bits.upgradable = upgradable ? 1 : 0;
1851 value.bits.timestamp = 0;
1852 value.bits.ignored = [self ignored] ? 0 : 1;
1853 value.bits.upgradable = 1;
1855 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1856 value.bits.ignored = 0;
1857 value.bits.upgradable = 0;
1860 return _not(uint32_t) - value.key;
1863 _finline static void Stifle(uint8_t &value) {
1866 uint32_t PackagePrefixRadix(Package *self, void *context) {
1867 size_t offset(reinterpret_cast<size_t>(context));
1868 CYString &name([self cyname]);
1870 size_t size(name.size());
1873 char *text(name.data());
1876 if (!isdigit(text[0]))
1880 while (size != digits && isdigit(text[digits]))
1890 if (offset == 0 && zeros != 0) {
1891 memset(data, '0', zeros);
1892 memcpy(data + zeros, text, 4 - zeros);
1894 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1895 if (size <= offset - zeros)
1898 text += offset - zeros;
1899 size -= offset - zeros;
1902 memcpy(data, text, 4);
1904 memcpy(data, text, size);
1905 memset(data + size, 0, 4 - size);
1908 for (size_t i(0); i != 4; ++i)
1909 if (isalpha(data[i]))
1917 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1919 /* XXX: ntohl may be more honest */
1920 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1923 CYString &(*PackageName)(Package *self, SEL sel);
1925 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1926 _profile(PackageNameCompare)
1927 CYString &lhi(PackageName(lhs, @selector(cyname)));
1928 CYString &rhi(PackageName(rhs, @selector(cyname)));
1929 CFStringRef lhn(lhi), rhn(rhi);
1932 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1933 else if (rhn == NULL)
1934 return NSOrderedDescending;
1936 _profile(PackageNameCompare$NumbersLast)
1937 if (!lhi.empty() && !rhi.empty()) {
1938 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1939 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1940 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1941 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1942 return lha ? NSOrderedAscending : NSOrderedDescending;
1946 CFIndex length = CFStringGetLength(lhn);
1948 _profile(PackageNameCompare$Compare)
1949 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1954 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1955 return PackageNameCompare(*lhs, *rhs, context);
1958 struct PackageNameOrdering :
1959 std::binary_function<Package *, Package *, bool>
1961 _finline bool operator ()(Package *lhs, Package *rhs) const {
1962 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1966 @implementation Package
1968 - (NSString *) description {
1969 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1975 if (section$_ != nil)
1976 [section$_ release];
1981 if (sponsor$_ != nil)
1982 [sponsor$_ release];
1983 if (author$_ != nil)
1990 if (relationships_ != nil)
1991 [relationships_ release];
1992 if (metadata_ != nil)
1993 [metadata_ release];
1998 + (NSString *) webScriptNameForSelector:(SEL)selector {
1999 if (selector == @selector(hasTag:))
2005 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2006 return [self webScriptNameForSelector:selector] == nil;
2009 + (NSArray *) _attributeKeys {
2010 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];
2013 - (NSArray *) attributeKeys {
2014 return [[self class] _attributeKeys];
2017 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2018 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2028 _profile(Package$parse)
2029 pkgRecords::Parser *parser;
2031 _profile(Package$parse$Lookup)
2032 parser = &[database_ records]->Lookup(file_);
2037 _profile(Package$parse$Find)
2043 {"depiction", &depiction_},
2044 {"homepage", &homepage_},
2045 {"website", &website},
2047 {"support", &support_},
2048 {"sponsor", &sponsor_},
2049 {"author", &author_},
2052 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2053 const char *start, *end;
2055 if (parser->Find(names[i].name_, start, end)) {
2056 CYString &value(*names[i].value_);
2057 _profile(Package$parse$Value)
2058 value.set(pool_, start, end - start);
2064 _profile(Package$parse$Tagline)
2065 const char *start, *end;
2066 if (parser->ShortDesc(start, end)) {
2067 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2070 while (stop != start && stop[-1] == '\r')
2072 tagline_.set(pool_, start, stop - start);
2076 _profile(Package$parse$Retain)
2077 if (homepage_.empty())
2078 homepage_ = website;
2079 if (homepage_ == depiction_)
2085 - (void) setVisible {
2086 visible_ = required_ && [self unfiltered];
2089 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2090 if ((self = [super init]) != nil) {
2091 _profile(Package$initWithVersion)
2092 era_ = [database era];
2096 iterator_ = version.ParentPkg();
2097 database_ = database;
2099 _profile(Package$initWithVersion$Latest)
2100 latest_ = (NSString *) StripVersion(version_.VerStr());
2103 pkgCache::VerIterator current;
2104 _profile(Package$initWithVersion$Versions)
2105 current = iterator_.CurrentVer();
2107 installed_.set(pool_, StripVersion_(current.VerStr()));
2109 if (!version_.end())
2110 file_ = version_.FileList();
2112 pkgCache &cache([database_ cache]);
2113 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2117 _profile(Package$initWithVersion$Name)
2118 id_.set(pool_, iterator_.Name());
2119 name_.set(pool, iterator_.Display());
2122 _profile(Package$lowercaseString)
2123 char *data(id_.data());
2124 for (size_t i(0), e(id_.size()); i != e; ++i)
2125 // XXX: do not use tolower() as this is not locale-specific? :(
2130 _profile(Package$initWithVersion$Source)
2131 source_ = [database_ getSource:file_.File()];
2140 _profile(Package$initWithVersion$Tags)
2141 pkgCache::TagIterator tag(iterator_.TagList());
2143 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2145 const char *name(tag.Name());
2146 [tags_ addObject:(NSString *)CFCString(name)];
2147 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2148 role_ = (NSString *) CFCString(name + 6);
2149 if (required_ && strncmp(name, "require::", 9) == 0 && (
2154 } while (!tag.end());
2158 bool changed(false);
2160 _profile(Package$initWithVersion$Metadata)
2161 metadata_ = [Packages_ objectForKey:id_];
2163 if (metadata_ == nil) {
2166 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2167 firstSeen_, @"FirstSeen",
2168 latest_, @"LastVersion",
2173 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2174 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2176 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2177 subscribed_ = [subscribed boolValue];
2179 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2181 if (firstSeen_ == nil) {
2182 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2183 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2187 if (version == nil) {
2188 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2190 } else if (![version isEqualToString:latest_]) {
2191 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2193 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2198 metadata_ = [metadata_ retain];
2201 [Packages_ setObject:metadata_ forKey:id_];
2206 _profile(Package$initWithVersion$Section)
2207 section_.set(pool_, iterator_.Section());
2210 obsolete_ = [self hasTag:@"cydia::obsolete"];
2211 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2216 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2217 pkgCache::VerIterator version;
2219 _profile(Package$packageWithIterator$GetCandidateVer)
2220 version = [database policy]->GetCandidateVer(iterator);
2226 return [[[Package alloc]
2227 initWithVersion:version
2234 - (pkgCache::PkgIterator) iterator {
2238 - (NSString *) section {
2239 if (section$_ == nil) {
2240 if (section_.empty())
2243 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2244 NSString *name(section_);
2247 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2248 if (NSString *rename = [value objectForKey:@"Rename"]) {
2253 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2257 - (NSString *) simpleSection {
2258 if (NSString *section = [self section])
2259 return Simplify(section);
2264 - (NSString *) longSection {
2265 return LocalizeSection([self section]);
2268 - (NSString *) shortSection {
2269 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2272 - (NSString *) uri {
2275 pkgIndexFile *index;
2276 pkgCache::PkgFileIterator file(file_.File());
2277 if (![database_ list].FindIndex(file, index))
2279 return [NSString stringWithUTF8String:iterator_->Path];
2280 //return [NSString stringWithUTF8String:file.Site()];
2281 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2285 - (Address *) maintainer {
2288 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2289 const std::string &maintainer(parser->Maintainer());
2290 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2294 return version_.end() ? 0 : version_->InstalledSize;
2297 - (NSString *) longDescription {
2298 @synchronized (database_) {
2299 if ([database_ era] != era_ || file_.end())
2302 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2303 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2305 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2306 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2307 if ([lines count] < 2)
2310 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2311 for (size_t i(1), e([lines count]); i != e; ++i) {
2312 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2313 [trimmed addObject:trim];
2316 return [trimmed componentsJoinedByString:@"\n"];
2319 - (NSString *) shortDescription {
2324 _profile(Package$index)
2325 CFStringRef name((CFStringRef) [self name]);
2326 if (CFStringGetLength(name) == 0)
2328 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2329 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2331 return toupper(character);
2335 - (NSMutableDictionary *) metadata {
2340 if (subscribed_ && lastSeen_ != nil)
2345 - (BOOL) subscribed {
2350 NSDictionary *metadata([self metadata]);
2351 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2352 return [ignored boolValue];
2357 - (NSString *) latest {
2361 - (NSString *) installed {
2365 - (BOOL) uninstalled {
2366 return installed_.empty();
2370 return !version_.end();
2373 - (BOOL) upgradableAndEssential:(BOOL)essential {
2374 _profile(Package$upgradableAndEssential)
2375 pkgCache::VerIterator current(iterator_.CurrentVer());
2377 return essential && essential_ && visible_;
2379 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2383 - (BOOL) essential {
2388 return [database_ cache][iterator_].InstBroken();
2391 - (BOOL) unfiltered {
2392 NSString *section([self section]);
2393 return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
2401 unsigned char current(iterator_->CurrentState);
2402 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2405 - (BOOL) halfConfigured {
2406 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2409 - (BOOL) halfInstalled {
2410 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2414 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2415 return state.Mode != pkgDepCache::ModeKeep;
2418 - (NSString *) mode {
2419 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2421 switch (state.Mode) {
2422 case pkgDepCache::ModeDelete:
2423 if ((state.iFlags & pkgDepCache::Purge) != 0)
2427 case pkgDepCache::ModeKeep:
2428 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2429 return @"REINSTALL";
2430 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2434 case pkgDepCache::ModeInstall:
2435 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2436 return @"REINSTALL";
2437 else*/ switch (state.Status) {
2439 return @"DOWNGRADE";
2445 return @"NEW_INSTALL";
2456 - (NSString *) name {
2457 return name_.empty() ? id_ : name_;
2460 - (UIImage *) icon {
2461 NSString *section = [self simpleSection];
2465 if ([static_cast<id>(icon_) hasPrefix:@"file:///"])
2466 // XXX: correct escaping
2467 icon = [UIImage imageAtPath:[static_cast<id>(icon_) substringFromIndex:7]];
2468 if (icon == nil) if (section != nil)
2469 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2470 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2471 if ([dicon hasPrefix:@"file:///"])
2472 // XXX: correct escaping
2473 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2475 icon = [UIImage applicationImageNamed:@"unknown.png"];
2479 - (NSString *) homepage {
2483 - (NSString *) depiction {
2484 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2487 - (Address *) sponsor {
2488 if (sponsor$_ == nil) {
2489 if (sponsor_.empty())
2491 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2495 - (Address *) author {
2496 if (author$_ == nil) {
2497 if (author_.empty())
2499 author$_ = [[Address addressWithString:author_] retain];
2503 - (NSString *) support {
2504 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2507 - (NSArray *) files {
2508 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2509 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2512 fin.open([path UTF8String]);
2517 while (std::getline(fin, line))
2518 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2523 - (NSArray *) relationships {
2524 return relationships_;
2527 - (NSArray *) warnings {
2528 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2529 const char *name(iterator_.Name());
2531 size_t length(strlen(name));
2532 if (length < 2) invalid:
2533 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2534 else for (size_t i(0); i != length; ++i)
2536 /* XXX: technically this is not allowed */
2537 (name[i] < 'A' || name[i] > 'Z') &&
2538 (name[i] < 'a' || name[i] > 'z') &&
2539 (name[i] < '0' || name[i] > '9') &&
2540 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2543 if (strcmp(name, "cydia") != 0) {
2546 bool _private = false;
2549 bool repository = [[self section] isEqualToString:@"Repositories"];
2551 if (NSArray *files = [self files])
2552 for (NSString *file in files)
2553 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2555 else if (!user && [file isEqualToString:@"/User"])
2557 else if (!_private && [file isEqualToString:@"/private"])
2559 else if (!stash && [file isEqualToString:@"/var/stash"])
2562 /* XXX: this is not sensitive enough. only some folders are valid. */
2563 if (cydia && !repository)
2564 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2566 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2568 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2570 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2573 return [warnings count] == 0 ? nil : warnings;
2576 - (NSArray *) applications {
2577 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2579 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2581 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2582 if (NSArray *files = [self files])
2583 for (NSString *file in files)
2584 if (application_r(file)) {
2585 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2586 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2587 if ([id isEqualToString:me])
2590 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2592 display = application_r[1];
2594 NSString *bundle([file stringByDeletingLastPathComponent]);
2595 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2596 if (icon == nil || [icon length] == 0)
2598 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2600 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2601 [applications addObject:application];
2603 [application addObject:id];
2604 [application addObject:display];
2605 [application addObject:url];
2608 return [applications count] == 0 ? nil : applications;
2611 - (Source *) source {
2613 @synchronized (database_) {
2614 if ([database_ era] != era_ || file_.end())
2617 source_ = [database_ getSource:file_.File()];
2629 - (NSString *) role {
2633 - (BOOL) matches:(NSString *)text {
2639 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2640 if (range.location != NSNotFound)
2643 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2644 if (range.location != NSNotFound)
2647 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2648 if (range.location != NSNotFound)
2654 - (bool) hasSupportingRole {
2657 if ([role_ isEqualToString:@"enduser"])
2659 if ([Role_ isEqualToString:@"User"])
2661 if ([role_ isEqualToString:@"hacker"])
2663 if ([Role_ isEqualToString:@"Hacker"])
2665 if ([role_ isEqualToString:@"developer"])
2667 if ([Role_ isEqualToString:@"Developer"])
2672 - (BOOL) hasTag:(NSString *)tag {
2673 return tags_ == nil ? NO : [tags_ containsObject:tag];
2676 - (NSString *) primaryPurpose {
2677 for (NSString *tag in tags_)
2678 if ([tag hasPrefix:@"purpose::"])
2679 return [tag substringFromIndex:9];
2683 - (NSArray *) purposes {
2684 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2685 for (NSString *tag in tags_)
2686 if ([tag hasPrefix:@"purpose::"])
2687 [purposes addObject:[tag substringFromIndex:9]];
2688 return [purposes count] == 0 ? nil : purposes;
2691 - (bool) isCommercial {
2692 return [self hasTag:@"cydia::commercial"];
2695 - (CYString &) cyname {
2696 return name_.empty() ? id_ : name_;
2699 - (uint32_t) compareBySection:(NSArray *)sections {
2700 NSString *section([self section]);
2701 for (size_t i(0), e([sections count]); i != e; ++i) {
2702 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2706 return _not(uint32_t);
2709 - (uint32_t) compareForChanges {
2714 uint32_t timestamp : 30;
2715 uint32_t ignored : 1;
2716 uint32_t upgradable : 1;
2720 bool upgradable([self upgradableAndEssential:YES]);
2721 value.bits.upgradable = upgradable ? 1 : 0;
2724 value.bits.timestamp = 0;
2725 value.bits.ignored = [self ignored] ? 0 : 1;
2726 value.bits.upgradable = 1;
2728 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2729 value.bits.ignored = 0;
2730 value.bits.upgradable = 0;
2733 return _not(uint32_t) - value.key;
2737 pkgProblemResolver *resolver = [database_ resolver];
2738 resolver->Clear(iterator_);
2739 resolver->Protect(iterator_);
2743 pkgProblemResolver *resolver = [database_ resolver];
2744 resolver->Clear(iterator_);
2745 resolver->Protect(iterator_);
2746 pkgCacheFile &cache([database_ cache]);
2747 cache->MarkInstall(iterator_, false);
2748 pkgDepCache::StateCache &state((*cache)[iterator_]);
2749 if (!state.Install())
2750 cache->SetReInstall(iterator_, true);
2754 pkgProblemResolver *resolver = [database_ resolver];
2755 resolver->Clear(iterator_);
2756 resolver->Protect(iterator_);
2757 resolver->Remove(iterator_);
2758 [database_ cache]->MarkDelete(iterator_, true);
2761 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2762 _profile(Package$isUnfilteredAndSearchedForBy)
2765 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2766 value &= [self unfiltered];
2769 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2770 value &= [self matches:search];
2777 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2778 if ([search length] == 0)
2781 _profile(Package$isUnfilteredAndSelectedForBy)
2784 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2785 value &= [self unfiltered];
2788 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2789 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2796 - (bool) isInstalledAndVisible:(NSNumber *)number {
2797 return (![number boolValue] || [self visible]) && ![self uninstalled];
2800 - (bool) isVisibleInSection:(NSString *)name {
2801 NSString *section = [self section];
2806 section == nil && [name length] == 0 ||
2807 [name isEqualToString:section]
2811 - (bool) isVisibleInSource:(Source *)source {
2812 return [self source] == source && [self visible];
2817 /* Section Class {{{ */
2818 @interface Section : NSObject {
2823 NSString *localized_;
2826 - (NSComparisonResult) compareByLocalized:(Section *)section;
2827 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2828 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2829 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2830 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2831 - (NSString *) name;
2838 - (void) addToCount;
2840 - (void) setCount:(size_t)count;
2841 - (NSString *) localized;
2845 @implementation Section
2849 if (localized_ != nil)
2850 [localized_ release];
2854 - (NSComparisonResult) compareByLocalized:(Section *)section {
2855 NSString *lhs(localized_);
2856 NSString *rhs([section localized]);
2858 /*if ([lhs length] != 0 && [rhs length] != 0) {
2859 unichar lhc = [lhs characterAtIndex:0];
2860 unichar rhc = [rhs characterAtIndex:0];
2862 if (isalpha(lhc) && !isalpha(rhc))
2863 return NSOrderedAscending;
2864 else if (!isalpha(lhc) && isalpha(rhc))
2865 return NSOrderedDescending;
2868 return [lhs compare:rhs options:LaxCompareOptions_];
2871 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2872 if ((self = [self initWithName:name localize:NO]) != nil) {
2873 if (localized != nil)
2874 localized_ = [localized retain];
2878 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2879 return [self initWithName:name row:0 localize:localize];
2882 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2883 if ((self = [super init]) != nil) {
2884 name_ = [name retain];
2888 localized_ = [LocalizeSection(name_) retain];
2892 /* XXX: localize the index thingees */
2893 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2894 if ((self = [super init]) != nil) {
2895 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2901 - (NSString *) name {
2921 - (void) addToCount {
2925 - (void) setCount:(size_t)count {
2929 - (NSString *) localized {
2936 static NSString *Colon_;
2937 static NSString *Error_;
2938 static NSString *Warning_;
2940 /* Database Implementation {{{ */
2941 @implementation Database
2943 + (Database *) sharedInstance {
2944 static Database *instance;
2945 if (instance == nil)
2946 instance = [[Database alloc] init];
2956 NSRecycleZone(zone_);
2957 // XXX: malloc_destroy_zone(zone_);
2958 apr_pool_destroy(pool_);
2962 - (void) _readCydia:(NSNumber *)fd { _pooled
2963 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2964 std::istream is(&ib);
2967 static Pcre finish_r("^finish:([^:]*)$");
2969 while (std::getline(is, line)) {
2970 const char *data(line.c_str());
2971 size_t size = line.size();
2972 lprintf("C:%s\n", data);
2974 if (finish_r(data, size)) {
2975 NSString *finish = finish_r[1];
2976 int index = [Finishes_ indexOfObject:finish];
2977 if (index != INT_MAX && index > Finish_)
2985 - (void) _readStatus:(NSNumber *)fd { _pooled
2986 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2987 std::istream is(&ib);
2990 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2991 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2993 while (std::getline(is, line)) {
2994 const char *data(line.c_str());
2995 size_t size(line.size());
2996 lprintf("S:%s\n", data);
2998 if (conffile_r(data, size)) {
2999 [delegate_ setConfigurationData:conffile_r[1]];
3000 } else if (strncmp(data, "status: ", 8) == 0) {
3001 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3002 [delegate_ setProgressTitle:string];
3003 } else if (pmstatus_r(data, size)) {
3004 std::string type([pmstatus_r[1] UTF8String]);
3005 NSString *id = pmstatus_r[2];
3007 float percent([pmstatus_r[3] floatValue]);
3008 [delegate_ setProgressPercent:(percent / 100)];
3010 NSString *string = pmstatus_r[4];
3012 if (type == "pmerror")
3013 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3014 withObject:[NSArray arrayWithObjects:string, id, nil]
3017 else if (type == "pmstatus") {
3018 [delegate_ setProgressTitle:string];
3019 } else if (type == "pmconffile")
3020 [delegate_ setConfigurationData:string];
3022 lprintf("E:unknown pmstatus\n");
3024 lprintf("E:unknown status\n");
3030 - (void) _readOutput:(NSNumber *)fd { _pooled
3031 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3032 std::istream is(&ib);
3035 while (std::getline(is, line)) {
3036 lprintf("O:%s\n", line.c_str());
3037 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3047 - (Package *) packageWithName:(NSString *)name {
3048 @synchronized (self) {
3049 if (static_cast<pkgDepCache *>(cache_) == NULL)
3051 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3052 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3056 if ((self = [super init]) != nil) {
3063 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3064 apr_pool_create(&pool_, NULL);
3066 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
3070 _assert(pipe(fds) != -1);
3073 _config->Set("APT::Keep-Fds::", cydiafd_);
3074 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3077 detachNewThreadSelector:@selector(_readCydia:)
3079 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3082 _assert(pipe(fds) != -1);
3086 detachNewThreadSelector:@selector(_readStatus:)
3088 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3091 _assert(pipe(fds) != -1);
3092 _assert(dup2(fds[0], 0) != -1);
3093 _assert(close(fds[0]) != -1);
3095 input_ = fdopen(fds[1], "a");
3097 _assert(pipe(fds) != -1);
3098 _assert(dup2(fds[1], 1) != -1);
3099 _assert(close(fds[1]) != -1);
3102 detachNewThreadSelector:@selector(_readOutput:)
3104 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3109 - (pkgCacheFile &) cache {
3113 - (pkgDepCache::Policy *) policy {
3117 - (pkgRecords *) records {
3121 - (pkgProblemResolver *) resolver {
3125 - (pkgAcquire &) fetcher {
3129 - (pkgSourceList &) list {
3133 - (NSArray *) packages {
3134 return (NSArray *) packages_;
3137 - (NSArray *) sources {
3138 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3139 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3140 [sources addObject:i->second];
3144 - (NSArray *) issues {
3145 if (cache_->BrokenCount() == 0)
3148 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3150 for (Package *package in [self packages]) {
3151 if (![package broken])
3153 pkgCache::PkgIterator pkg([package iterator]);
3155 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3156 [entry addObject:[package name]];
3157 [issues addObject:entry];
3159 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3163 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3164 pkgCache::DepIterator start;
3165 pkgCache::DepIterator end;
3166 dep.GlobOr(start, end); // ++dep
3168 if (!cache_->IsImportantDep(end))
3170 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3173 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3174 [entry addObject:failure];
3175 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3177 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3178 if (Package *package = [self packageWithName:name])
3179 name = [package name];
3180 [failure addObject:name];
3182 pkgCache::PkgIterator target(start.TargetPkg());
3183 if (target->ProvidesList != 0)
3184 [failure addObject:@"?"];
3186 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3188 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3189 else if (!cache_[target].CandidateVerIter(cache_).end())
3190 [failure addObject:@"-"];
3191 else if (target->ProvidesList == 0)
3192 [failure addObject:@"!"];
3194 [failure addObject:@"%"];
3198 if (start.TargetVer() != 0)
3199 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3210 - (bool) popErrorWithTitle:(NSString *)title {
3212 std::string message;
3214 while (!_error->empty()) {
3216 bool warning(!_error->PopMessage(error));
3220 size_t size(error.size());
3221 if (size == 0 || error[size - 1] != '\n')
3223 error.resize(size - 1);
3225 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3227 if (!message.empty())
3232 if (fatal && !message.empty())
3233 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3238 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3239 return [self popErrorWithTitle:title] || !success;
3242 - (void) reloadData { CYPoolStart() {
3243 @synchronized (self) {
3246 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3247 CFArrayRemoveAllValues(packages_);
3274 apr_pool_clear(pool_);
3275 NSRecycleZone(zone_);
3277 int chk(creat("/tmp/cydia.chk", 0644));
3281 NSString *title(UCLocalize("DATABASE"));
3284 if (!cache_.Open(progress_, true)) { pop:
3286 bool warning(!_error->PopMessage(error));
3287 lprintf("cache_.Open():[%s]\n", error.c_str());
3289 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3290 [delegate_ repairWithSelector:@selector(configure)];
3291 else if (error == "The package lists or status file could not be parsed or opened.")
3292 [delegate_ repairWithSelector:@selector(update)];
3293 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3294 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3295 // else if (error == "The list of sources could not be read.")
3297 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3306 unlink("/tmp/cydia.chk");
3308 now_ = [[NSDate date] retain];
3310 policy_ = new pkgDepCache::Policy();
3311 records_ = new pkgRecords(cache_);
3312 resolver_ = new pkgProblemResolver(cache_);
3313 fetcher_ = new pkgAcquire(&status_);
3316 list_ = new pkgSourceList();
3317 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3320 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3321 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3325 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3328 if (cache_->BrokenCount() != 0) {
3329 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3332 if (cache_->BrokenCount() != 0) {
3333 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3337 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3341 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3342 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3343 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3344 // XXX: this could be more intelligent
3345 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3346 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3348 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3353 /*std::vector<Package *> packages;
3354 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3355 [packages_ release];
3360 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3361 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3362 //packages.push_back(package);
3363 CFArrayAppendValue(packages_, [package retain]);
3367 /*if (packages.empty())
3368 packages_ = [[NSArray alloc] init];
3370 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3373 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3374 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3375 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3383 /*if (!packages.empty())
3384 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3385 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3387 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3389 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3391 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3395 } } CYPoolEnd() _trace(); }
3397 - (void) configure {
3398 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3399 system([dpkg UTF8String]);
3403 // XXX: I don't remember this condition
3408 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3410 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3412 if ([self popErrorWithTitle:title])
3416 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3419 public pkgArchiveCleaner
3422 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3427 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3434 fetcher_->Shutdown();
3436 pkgRecords records(cache_);
3438 lock_ = new FileFd();
3439 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3441 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3443 if ([self popErrorWithTitle:title])
3447 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3450 manager_ = (_system->CreatePM(cache_));
3451 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3458 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3460 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3462 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3464 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3465 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3468 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3473 bool failed = false;
3474 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3475 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3477 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3480 std::string uri = (*item)->DescURI();
3481 std::string error = (*item)->ErrorText;
3483 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3486 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3487 withObject:[NSArray arrayWithObjects:
3488 [NSString stringWithUTF8String:error.c_str()],
3500 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3502 if (_error->PendingError()) {
3507 if (result == pkgPackageManager::Failed) {
3512 if (result != pkgPackageManager::Completed) {
3517 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3519 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3521 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3522 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3525 if (![before isEqualToArray:after])
3530 NSString *title(UCLocalize("UPGRADE"));
3531 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3537 [self updateWithStatus:status_];
3540 - (void) setVisible {
3541 for (Package *package in [self packages])
3542 [package setVisible];
3545 - (void) updateWithStatus:(Status &)status {
3546 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3547 NSString *title(UCLocalize("REFRESHING_DATA"));
3550 if (!list.ReadMainList())
3551 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3554 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3555 if ([self popErrorWithTitle:title])
3558 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3559 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3560 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3562 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3566 - (void) setDelegate:(id)delegate {
3567 delegate_ = delegate;
3568 status_.setDelegate(delegate);
3569 progress_.setDelegate(delegate);
3572 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3573 SourceMap::const_iterator i(sources_.find(file->ID));
3574 return i == sources_.end() ? nil : i->second;
3580 /* Confirmation Controller {{{ */
3581 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3582 if (!iterator.end())
3583 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3584 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3586 pkgCache::PkgIterator package(dep.TargetPkg());
3589 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3597 /* Web Scripting {{{ */
3598 @interface CydiaObject : NSObject {
3603 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3606 @implementation CydiaObject
3609 [indirect_ release];
3613 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3614 if ((self = [super init]) != nil) {
3615 indirect_ = [indirect retain];
3619 - (void) setDelegate:(id)delegate {
3620 delegate_ = delegate;
3623 + (NSArray *) _attributeKeys {
3624 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3627 - (NSArray *) attributeKeys {
3628 return [[self class] _attributeKeys];
3631 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3632 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3635 - (NSString *) device {
3636 return [[UIDevice currentDevice] uniqueIdentifier];
3639 #if 0 // XXX: implement!
3640 - (NSString *) mac {
3641 if (![indirect_ promptForSensitive:@"Mac Address"])
3645 - (NSString *) serial {
3646 if (![indirect_ promptForSensitive:@"Serial #"])
3650 - (NSString *) firewire {
3651 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3655 - (NSString *) imei {
3656 if (![indirect_ promptForSensitive:@"IMEI"])
3661 + (NSString *) webScriptNameForSelector:(SEL)selector {
3662 if (selector == @selector(close))
3664 else if (selector == @selector(getInstalledPackages))
3665 return @"getInstalledPackages";
3666 else if (selector == @selector(getPackageById:))
3667 return @"getPackageById";
3668 else if (selector == @selector(installPackages:))
3669 return @"installPackages";
3670 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3671 return @"setButtonImage";
3672 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3673 return @"setButtonTitle";
3674 else if (selector == @selector(setPopupHook:))
3675 return @"setPopupHook";
3676 else if (selector == @selector(setSpecial:))
3677 return @"setSpecial";
3678 else if (selector == @selector(setToken:))
3680 else if (selector == @selector(setViewportWidth:))
3681 return @"setViewportWidth";
3682 else if (selector == @selector(supports:))
3684 else if (selector == @selector(stringWithFormat:arguments:))
3686 else if (selector == @selector(localizedStringForKey:value:table:))
3688 else if (selector == @selector(du:))
3690 else if (selector == @selector(statfs:))
3696 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3697 return [self webScriptNameForSelector:selector] == nil;
3700 - (BOOL) supports:(NSString *)feature {
3701 return [feature isEqualToString:@"window.open"];
3704 - (NSArray *) getInstalledPackages {
3705 NSArray *packages([[Database sharedInstance] packages]);
3706 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3707 for (Package *package in packages)
3708 if ([package installed] != nil)
3709 [installed addObject:package];
3713 - (Package *) getPackageById:(NSString *)id {
3714 Package *package([[Database sharedInstance] packageWithName:id]);
3719 - (NSArray *) statfs:(NSString *)path {
3722 if (path == nil || statfs([path UTF8String], &stat) == -1)
3725 return [NSArray arrayWithObjects:
3726 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3727 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3728 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3732 - (NSNumber *) du:(NSString *)path {
3733 NSNumber *value(nil);
3736 _assert(pipe(fds) != -1);
3738 pid_t pid(ExecFork());
3740 _assert(dup2(fds[1], 1) != -1);
3741 _assert(close(fds[0]) != -1);
3742 _assert(close(fds[1]) != -1);
3743 /* XXX: this should probably not use du */
3744 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3749 _assert(close(fds[1]) != -1);
3751 if (FILE *du = fdopen(fds[0], "r")) {
3753 while (fgets(line, sizeof(line), du) != NULL) {
3754 size_t length(strlen(line));
3755 while (length != 0 && line[length - 1] == '\n')
3756 line[--length] = '\0';
3757 if (char *tab = strchr(line, '\t')) {
3759 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3764 } else _assert(close(fds[0]));
3768 if (waitpid(pid, &status, 0) == -1)
3771 else _assert(false);
3780 - (void) installPackages:(NSArray *)packages {
3781 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3784 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3785 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3788 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3789 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3792 - (void) setSpecial:(id)function {
3793 [indirect_ setSpecial:function];
3796 - (void) setToken:(NSString *)token {
3799 Token_ = [token retain];
3801 [Metadata_ setObject:Token_ forKey:@"Token"];
3805 - (void) setPopupHook:(id)function {
3806 [indirect_ setPopupHook:function];
3809 - (void) setViewportWidth:(float)width {
3810 [indirect_ setViewportWidth:width];
3813 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3814 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3815 unsigned count([arguments count]);
3817 for (unsigned i(0); i != count; ++i)
3818 values[i] = [arguments objectAtIndex:i];
3819 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3822 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3823 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3825 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3827 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3833 /* Cydia Browser Controller {{{ */
3834 @interface CYBrowserController : BrowserController {
3835 CydiaObject *cydia_;
3840 @implementation CYBrowserController
3847 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3850 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3851 [super webView:view didClearWindowObject:window forFrame:frame];
3853 WebDataSource *source([frame dataSource]);
3854 NSURLResponse *response([source response]);
3855 NSURL *url([response URL]);
3856 NSString *scheme([url scheme]);
3858 NSHTTPURLResponse *http;
3859 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3860 http = (NSHTTPURLResponse *) response;
3864 NSDictionary *headers([http allHeaderFields]);
3865 NSString *host([url host]);
3866 [self setHeaders:headers forHost:host];
3869 [host isEqualToString:@"cydia.saurik.com"] ||
3870 [host hasSuffix:@".cydia.saurik.com"] ||
3871 [scheme isEqualToString:@"file"]
3873 [window setValue:cydia_ forKey:@"cydia"];
3876 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3877 if (System_ != NULL)
3878 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3879 if (Machine_ != NULL)
3880 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3882 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3884 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3887 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3888 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3889 [self _setMoreHeaders:copy];
3893 - (void) setDelegate:(id)delegate {
3894 [super setDelegate:delegate];
3895 [cydia_ setDelegate:delegate];
3899 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3900 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3902 WebView *webview([[webview_ _documentView] webView]);
3904 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3906 NSString *application = package == nil ? @"Cydia" : [NSString
3907 stringWithFormat:@"Cydia/%@",
3912 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3914 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3915 if (Product_ != nil)
3916 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3918 [webview setApplicationNameForUserAgent:application];
3925 /* Confirmation {{{ */
3926 @protocol ConfirmationControllerDelegate
3927 - (void) cancelAndClear:(bool)clear;
3928 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3932 @interface ConfirmationController : CYBrowserController {
3933 _transient Database *database_;
3934 UIAlertView *essential_;
3941 - (id) initWithDatabase:(Database *)database;
3945 @implementation ConfirmationController
3952 if (essential_ != nil)
3953 [essential_ release];
3957 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3958 NSString *context([alert context]);
3960 if ([context isEqualToString:@"remove"]) {
3961 if (button == [alert cancelButtonIndex]) {
3962 [self dismissModalViewControllerAnimated:YES];
3963 } else if (button == [alert firstOtherButtonIndex]) {
3966 [delegate_ confirmWithNavigationController:[self navigationController]];
3969 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3970 } else if ([context isEqualToString:@"unable"]) {
3971 [self dismissModalViewControllerAnimated:YES];
3972 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3974 [super alertView:alert clickedButtonAtIndex:button];
3978 - (void) _doContinue {
3979 [self dismissModalViewControllerAnimated:YES];
3980 [delegate_ cancelAndClear:NO];
3983 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
3984 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
3988 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3989 [super webView:view didClearWindowObject:window forFrame:frame];
3990 [window setValue:changes_ forKey:@"changes"];
3991 [window setValue:issues_ forKey:@"issues"];
3992 [window setValue:sizes_ forKey:@"sizes"];
3993 [window setValue:self forKey:@"queue"];
3996 - (id) initWithDatabase:(Database *)database {
3997 if ((self = [super init]) != nil) {
3998 database_ = database;
4000 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4002 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4003 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4004 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4005 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4006 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4010 pkgDepCache::Policy *policy([database_ policy]);
4012 pkgCacheFile &cache([database_ cache]);
4013 NSArray *packages = [database_ packages];
4014 for (Package *package in packages) {
4015 pkgCache::PkgIterator iterator = [package iterator];
4016 pkgDepCache::StateCache &state(cache[iterator]);
4018 NSString *name([package name]);
4020 if (state.NewInstall())
4021 [installing addObject:name];
4022 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4023 [reinstalling addObject:name];
4024 else if (state.Upgrade())
4025 [upgrading addObject:name];
4026 else if (state.Downgrade())
4027 [downgrading addObject:name];
4028 else if (state.Delete()) {
4029 if ([package essential])
4031 [removing addObject:name];
4034 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4035 substrate_ |= DepSubstrate(iterator.CurrentVer());
4040 else if (Advanced_) {
4041 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4043 essential_ = [[UIAlertView alloc]
4044 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4045 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4047 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4048 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4051 [essential_ setContext:@"remove"];
4053 essential_ = [[UIAlertView alloc]
4054 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4055 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4057 cancelButtonTitle:UCLocalize("OKAY")
4058 otherButtonTitles:nil
4061 [essential_ setContext:@"unable"];
4064 changes_ = [[NSArray alloc] initWithObjects:
4072 issues_ = [database_ issues];
4074 issues_ = [issues_ retain];
4076 sizes_ = [[NSArray alloc] initWithObjects:
4077 SizeString([database_ fetcher].FetchNeeded()),
4078 SizeString([database_ fetcher].PartialPresent()),
4081 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4083 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
4084 initWithTitle:UCLocalize("CANCEL")
4085 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4086 style:UIBarButtonItemStylePlain
4088 action:@selector(cancelButtonClicked)
4090 [[self navigationItem] setLeftBarButtonItem:leftItem];
4095 - (void) applyRightButton {
4096 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
4097 initWithTitle:UCLocalize("CONFIRM")
4098 style:UIBarButtonItemStylePlain
4100 action:@selector(confirmButtonClicked)
4102 #if !AlwaysReload && !IgnoreInstall
4103 if (issues_ == nil && ![self isLoading]) [[self navigationItem] setRightBarButtonItem:rightItem];
4104 else [super applyRightButton];
4106 [[self navigationItem] setRightBarButtonItem:nil];
4108 [rightItem release];
4111 - (void) cancelButtonClicked {
4112 [self dismissModalViewControllerAnimated:YES];
4113 [delegate_ cancelAndClear:YES];
4117 - (void) confirmButtonClicked {
4121 if (essential_ != nil)
4126 [delegate_ confirmWithNavigationController:[self navigationController]];
4134 /* Progress Data {{{ */
4135 @interface ProgressData : NSObject {
4141 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4148 @implementation ProgressData
4150 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4151 if ((self = [super init]) != nil) {
4152 selector_ = selector;
4172 /* Progress Controller {{{ */
4173 @interface ProgressController : CYViewController <
4174 ConfigurationDelegate,
4177 _transient Database *database_;
4178 UIProgressBar *progress_;
4179 UITextView *output_;
4180 UITextLabel *status_;
4181 UIPushButton *close_;
4183 SHA1SumValue springlist_;
4184 SHA1SumValue notifyconf_;
4188 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4190 - (void) _retachThread;
4191 - (void) _detachNewThreadData:(ProgressData *)data;
4192 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4198 @protocol ProgressControllerDelegate
4199 - (void) progressControllerIsComplete:(ProgressController *)sender;
4202 @implementation ProgressController
4205 [database_ setDelegate:nil];
4206 [progress_ release];
4215 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4216 if ((self = [super init]) != nil) {
4217 database_ = database;
4218 [database_ setDelegate:self];
4219 delegate_ = delegate;
4221 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4223 progress_ = [[UIProgressBar alloc] init];
4224 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4225 [progress_ setStyle:0];
4227 status_ = [[UITextLabel alloc] init];
4228 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4229 [status_ setColor:[UIColor whiteColor]];
4230 [status_ setBackgroundColor:[UIColor clearColor]];
4231 [status_ setCentersHorizontally:YES];
4232 //[status_ setFont:font];
4234 output_ = [[UITextView alloc] init];
4236 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4237 //[output_ setTextFont:@"Courier New"];
4238 [output_ setFont:[[output_ font] fontWithSize:12]];
4239 [output_ setTextColor:[UIColor whiteColor]];
4240 [output_ setBackgroundColor:[UIColor clearColor]];
4241 [output_ setMarginTop:0];
4242 [output_ setAllowsRubberBanding:YES];
4243 [output_ setEditable:NO];
4244 [[self view] addSubview:output_];
4246 close_ = [[UIPushButton alloc] init];
4247 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4248 [close_ setAutosizesToFit:NO];
4249 [close_ setDrawsShadow:YES];
4250 [close_ setStretchBackground:YES];
4251 [close_ setEnabled:YES];
4252 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4253 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4254 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4255 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4259 - (void) positionViews {
4260 CGRect bounds = [[self view] bounds];
4261 CGSize prgsize = [UIProgressBar defaultSize];
4264 (bounds.size.width - prgsize.width) / 2,
4265 bounds.size.height - prgsize.height - 20
4268 float closewidth = bounds.size.width - 20;
4269 if (closewidth > 300) closewidth = 300;
4271 [progress_ setFrame:prgrect];
4272 [status_ setFrame:CGRectMake(
4274 bounds.size.height - prgsize.height - 50,
4275 bounds.size.width - 20,
4278 [output_ setFrame:CGRectMake(
4281 bounds.size.width - 20,
4282 bounds.size.height - 62
4284 [close_ setFrame:CGRectMake(
4285 (bounds.size.width - closewidth) / 2,
4286 bounds.size.height - prgsize.height - 50,
4292 - (void) viewWillAppear:(BOOL)animated {
4293 [super viewDidAppear:animated];
4294 [[self navigationItem] setHidesBackButton:YES];
4295 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4297 [self positionViews];
4300 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4301 [self positionViews];
4304 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4305 NSString *context([alert context]);
4307 if ([context isEqualToString:@"conffile"]) {
4308 FILE *input = [database_ input];
4309 if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
4310 else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
4315 - (void) closeButtonPushed {
4318 UpdateExternalStatus(0);
4322 [self dismissModalViewControllerAnimated:YES];
4326 [delegate_ terminateWithSuccess];
4327 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4328 [delegate_ suspendWithAnimation:YES];
4330 [delegate_ suspend];*/
4334 system("launchctl stop com.apple.SpringBoard");
4338 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4347 - (void) _retachThread {
4348 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4350 [[self view] addSubview:close_];
4351 [progress_ removeFromSuperview];
4352 [status_ removeFromSuperview];
4354 [database_ popErrorWithTitle:title_];
4355 [delegate_ progressControllerIsComplete:self];
4359 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4362 MMap mmap(file, MMap::ReadOnly);
4364 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4365 if (!(notifyconf_ == sha1.Result()))
4372 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4375 MMap mmap(file, MMap::ReadOnly);
4377 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4378 if (!(springlist_ == sha1.Result()))
4384 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4385 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4386 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4387 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4388 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4391 system("su -c /usr/bin/uicache mobile");
4393 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4395 [delegate_ setStatusBarShowsProgress:NO];
4398 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4399 [[data target] performSelector:[data selector] withObject:[data object]];
4402 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4405 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4406 UpdateExternalStatus(1);
4413 title_ = [title retain];
4415 [[self navigationItem] setTitle:title_];
4417 [status_ setText:nil];
4418 [output_ setText:@""];
4419 [progress_ setProgress:0];
4421 [close_ removeFromSuperview];
4422 [[self view] addSubview:progress_];
4423 [[self view] addSubview:status_];
4425 [delegate_ setStatusBarShowsProgress:YES];
4430 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4433 MMap mmap(file, MMap::ReadOnly);
4435 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4436 notifyconf_ = sha1.Result();
4442 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4445 MMap mmap(file, MMap::ReadOnly);
4447 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4448 springlist_ = sha1.Result();
4453 detachNewThreadSelector:@selector(_detachNewThreadData:)
4455 withObject:[[ProgressData alloc]
4456 initWithSelector:selector
4463 - (void) repairWithSelector:(SEL)selector {
4465 detachNewThreadSelector:selector
4468 title:UCLocalize("REPAIRING")
4472 - (void) setConfigurationData:(NSString *)data {
4474 performSelectorOnMainThread:@selector(_setConfigurationData:)
4480 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4481 CYActionSheet *sheet([[[CYActionSheet alloc]
4483 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4484 defaultButtonIndex:0
4487 [sheet setMessage:error];
4488 [sheet yieldToPopupAlertAnimated:YES];
4492 - (void) setProgressTitle:(NSString *)title {
4494 performSelectorOnMainThread:@selector(_setProgressTitle:)
4500 - (void) setProgressPercent:(float)percent {
4502 performSelectorOnMainThread:@selector(_setProgressPercent:)
4503 withObject:[NSNumber numberWithFloat:percent]
4508 - (void) startProgress {
4511 - (void) addProgressOutput:(NSString *)output {
4513 performSelectorOnMainThread:@selector(_addProgressOutput:)
4519 - (bool) isCancelling:(size_t)received {
4523 - (void) _setConfigurationData:(NSString *)data {
4524 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4526 if (!conffile_r(data)) {
4527 lprintf("E:invalid conffile\n");
4531 NSString *ofile = conffile_r[1];
4532 //NSString *nfile = conffile_r[2];
4534 UIAlertView *alert = [[[UIAlertView alloc]
4535 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4536 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4538 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4539 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4540 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4544 [alert setContext:@"conffile"];
4548 - (void) _setProgressTitle:(NSString *)title {
4549 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4550 for (size_t i(0), e([words count]); i != e; ++i) {
4551 NSString *word([words objectAtIndex:i]);
4552 if (Package *package = [database_ packageWithName:word])
4553 [words replaceObjectAtIndex:i withObject:[package name]];
4556 [status_ setText:[words componentsJoinedByString:@" "]];
4559 - (void) _setProgressPercent:(NSNumber *)percent {
4560 [progress_ setProgress:[percent floatValue]];
4563 - (void) _addProgressOutput:(NSString *)output {
4564 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4565 CGSize size = [output_ contentSize];
4566 CGRect rect = {{0, size.height}, {size.width, 0}};
4567 [output_ scrollRectToVisible:rect animated:YES];
4570 - (BOOL) isRunning {
4577 /* Cell Content View {{{ */
4578 @protocol ContentDelegate
4579 - (void) drawContentRect:(CGRect)rect;
4582 @interface ContentView : UIView {
4583 _transient id<ContentDelegate> delegate_;
4588 @implementation ContentView
4589 - (id) initWithFrame:(CGRect)frame {
4590 if ((self = [super initWithFrame:frame]) != nil) {
4591 /* Fix landscape stretching. */
4592 [self setNeedsDisplayOnBoundsChange:YES];
4596 - (void) setDelegate:(id<ContentDelegate>)delegate {
4597 delegate_ = delegate;
4600 - (void) drawRect:(CGRect)rect {
4601 [super drawRect:rect];
4602 [delegate_ drawContentRect:rect];
4606 /* Package Cell {{{ */
4607 @interface PackageCell : UITableViewCell <
4612 NSString *description_;
4618 ContentView *content_;
4624 - (PackageCell *) init;
4625 - (void) setPackage:(Package *)package;
4627 + (int) heightForPackage:(Package *)package;
4628 - (void) drawContentRect:(CGRect)rect;
4632 @implementation PackageCell
4634 - (void) clearPackage {
4645 if (description_ != nil) {
4646 [description_ release];
4650 if (source_ != nil) {
4655 if (badge_ != nil) {
4660 if (placard_ != nil) {
4670 [self clearPackage];
4677 return faded_ ? [self selectionPercent] : fade_;
4680 - (PackageCell *) init {
4681 CGRect frame(CGRectMake(0, 0, 320, 74));
4682 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4683 UIView *content([self contentView]);
4684 CGRect bounds([content bounds]);
4686 content_ = [[ContentView alloc] initWithFrame:bounds];
4687 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4688 [content addSubview:content_];
4690 [content_ setDelegate:self];
4691 [content_ setOpaque:YES];
4692 if ([self respondsToSelector:@selector(selectionPercent)])
4697 - (void) _setBackgroundColor {
4699 if (NSString *mode = [package_ mode]) {
4700 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4701 color = remove ? RemovingColor_ : InstallingColor_;
4703 color = [UIColor whiteColor];
4705 [content_ setBackgroundColor:color];
4706 [self setNeedsDisplay];
4709 - (void) setPackage:(Package *)package {
4710 [self clearPackage];
4713 Source *source = [package source];
4715 icon_ = [[package icon] retain];
4716 name_ = [[package name] retain];
4719 description_ = [package longDescription];
4720 if (description_ == nil)
4721 description_ = [package shortDescription];
4722 if (description_ != nil)
4723 description_ = [description_ retain];
4725 commercial_ = [package isCommercial];
4727 package_ = [package retain];
4729 NSString *label = nil;
4730 bool trusted = false;
4732 if (source != nil) {
4733 label = [source label];
4734 trusted = [source trusted];
4735 } else if ([[package id] isEqualToString:@"firmware"])
4736 label = UCLocalize("APPLE");
4738 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4740 NSString *from(label);
4742 NSString *section = [package simpleSection];
4743 if (section != nil && ![section isEqualToString:label]) {
4744 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4745 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4748 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4749 source_ = [from retain];
4751 if (NSString *purpose = [package primaryPurpose])
4752 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4753 badge_ = [badge_ retain];
4755 if ([package installed] != nil)
4756 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4757 placard_ = [placard_ retain];
4759 [self _setBackgroundColor];
4760 [content_ setNeedsDisplay];
4763 - (void) drawContentRect:(CGRect)rect {
4764 bool selected([self isSelected]);
4765 float width([self bounds].size.width);
4768 CGContextRef context(UIGraphicsGetCurrentContext());
4769 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4770 CGContextFillRect(context, rect);
4775 rect.size = [icon_ size];
4777 rect.size.width /= 2;
4778 rect.size.height /= 2;
4780 rect.origin.x = 25 - rect.size.width / 2;
4781 rect.origin.y = 25 - rect.size.height / 2;
4783 [icon_ drawInRect:rect];
4786 if (badge_ != nil) {
4787 CGSize size = [badge_ size];
4789 [badge_ drawAtPoint:CGPointMake(
4790 36 - size.width / 2,
4791 36 - size.height / 2
4799 UISetColor(commercial_ ? Purple_ : Black_);
4800 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4801 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4804 UISetColor(commercial_ ? Purplish_ : Gray_);
4805 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4807 if (placard_ != nil)
4808 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4811 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4812 //[self _setBackgroundColor];
4813 [super setSelected:selected animated:fade];
4814 [content_ setNeedsDisplay];
4817 + (int) heightForPackage:(Package *)package {
4823 /* Section Cell {{{ */
4824 @interface SectionCell : UITableViewCell <
4832 ContentView *content_;
4837 - (void) setSection:(Section *)section editing:(BOOL)editing;
4841 @implementation SectionCell
4843 - (void) clearSection {
4844 if (basic_ != nil) {
4849 if (section_ != nil) {
4859 if (count_ != nil) {
4866 [self clearSection];
4874 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4875 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4876 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4877 switch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4878 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4880 UIView *content([self contentView]);
4881 CGRect bounds([content bounds]);
4883 content_ = [[ContentView alloc] initWithFrame:bounds];
4884 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4885 [content addSubview:content_];
4886 [content_ setBackgroundColor:[UIColor whiteColor]];
4888 [content_ setDelegate:self];
4892 - (void) onSwitch:(id)sender {
4893 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4894 if (metadata == nil) {
4895 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4896 [Sections_ setObject:metadata forKey:basic_];
4900 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4903 - (void) setSection:(Section *)section editing:(BOOL)editing {
4904 if (editing != editing_) {
4906 [switch_ removeFromSuperview];
4908 [self addSubview:switch_];
4912 [self clearSection];
4914 if (section == nil) {
4915 name_ = [UCLocalize("ALL_PACKAGES") retain];
4918 basic_ = [section name];
4920 basic_ = [basic_ retain];
4922 section_ = [section localized];
4923 if (section_ != nil)
4924 section_ = [section_ retain];
4926 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4927 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4930 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4933 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4934 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
4936 [content_ setNeedsDisplay];
4939 - (void) setFrame:(CGRect)frame {
4940 [super setFrame:frame];
4942 CGRect rect([switch_ frame]);
4943 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4946 - (void) drawContentRect:(CGRect)rect {
4947 BOOL selected = [self isSelected];
4949 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4957 float width(rect.size.width);
4961 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4963 CGSize size = [count_ sizeWithFont:Font14_];
4967 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4973 /* File Table {{{ */
4974 @interface FileTable : CYViewController <
4975 UITableViewDataSource,
4978 _transient Database *database_;
4981 NSMutableArray *files_;
4985 - (id) initWithDatabase:(Database *)database;
4986 - (void) setPackage:(Package *)package;
4990 @implementation FileTable
4993 if (package_ != nil)
5002 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5003 return files_ == nil ? 0 : [files_ count];
5006 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5010 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5011 static NSString *reuseIdentifier = @"Cell";
5013 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5015 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5016 [cell setFont:[UIFont systemFontOfSize:16]];
5018 [cell setText:[files_ objectAtIndex:indexPath.row]];
5019 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5024 - (id) initWithDatabase:(Database *)database {
5025 if ((self = [super init]) != nil) {
5026 database_ = database;
5028 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5030 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5032 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5033 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5034 [list_ setRowHeight:24.0f];
5035 [[self view] addSubview:list_];
5037 [list_ setDataSource:self];
5038 [list_ setDelegate:self];
5042 - (void) setPackage:(Package *)package {
5043 if (package_ != nil) {
5044 [package_ autorelease];
5053 [files_ removeAllObjects];
5055 if (package != nil) {
5056 package_ = [package retain];
5057 name_ = [[package id] retain];
5059 if (NSArray *files = [package files])
5060 [files_ addObjectsFromArray:files];
5062 if ([files_ count] != 0) {
5063 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5064 [files_ removeObjectAtIndex:0];
5065 [files_ sortUsingSelector:@selector(compareByPath:)];
5067 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5068 [stack addObject:@"/"];
5070 for (int i(0), e([files_ count]); i != e; ++i) {
5071 NSString *file = [files_ objectAtIndex:i];
5072 while (![file hasPrefix:[stack lastObject]])
5073 [stack removeLastObject];
5074 NSString *directory = [stack lastObject];
5075 [stack addObject:[file stringByAppendingString:@"/"]];
5076 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5077 ([stack count] - 2) * 3, "",
5078 [file substringFromIndex:[directory length]]
5087 - (void) reloadData {
5088 [self setPackage:[database_ packageWithName:name_]];
5093 /* Package Controller {{{ */
5094 @interface PackageController : CYBrowserController <
5095 UIActionSheetDelegate
5097 _transient Database *database_;
5101 NSMutableArray *buttons_;
5102 UIBarButtonItem *button_;
5105 - (id) initWithDatabase:(Database *)database;
5106 - (void) setPackage:(Package *)package;
5110 @implementation PackageController
5113 if (package_ != nil)
5127 if ([self retainCount] == 1)
5128 [delegate_ setPackageController:self];
5132 /* XXX: this is not safe at all... localization of /fail/ */
5133 - (void) _clickButtonWithName:(NSString *)name {
5134 if ([name isEqualToString:UCLocalize("CLEAR")])
5135 [delegate_ clearPackage:package_];
5136 else if ([name isEqualToString:UCLocalize("INSTALL")])
5137 [delegate_ installPackage:package_];
5138 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5139 [delegate_ installPackage:package_];
5140 else if ([name isEqualToString:UCLocalize("REMOVE")])
5141 [delegate_ removePackage:package_];
5142 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5143 [delegate_ installPackage:package_];
5144 else _assert(false);
5147 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5148 NSString *context([sheet context]);
5150 if ([context isEqualToString:@"modify"]) {
5151 if (button != [sheet cancelButtonIndex]) {
5152 NSString *buttonName = [buttons_ objectAtIndex:button];
5153 [self _clickButtonWithName:buttonName];
5156 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5160 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5161 [super webView:view didClearWindowObject:window forFrame:frame];
5162 [window setValue:package_ forKey:@"package"];
5165 - (bool) _allowJavaScriptPanel {
5170 - (void) _customButtonClicked {
5171 int count([buttons_ count]);
5176 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5178 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5179 [buttons addObjectsFromArray:buttons_];
5181 UIActionSheet *sheet = [[[UIActionSheet alloc]
5184 cancelButtonTitle:nil
5185 destructiveButtonTitle:nil
5186 otherButtonTitles:nil
5189 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5191 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5192 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5194 [sheet setContext:@"modify"];
5196 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5200 // We don't want to allow non-commercial packages to do custom things to the install button,
5201 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5202 - (void) customButtonClicked {
5204 [super customButtonClicked];
5206 [self _customButtonClicked];
5209 - (void) reloadButtonClicked {
5210 // Don't reload a package view by clicking the button.
5213 - (void) applyLoadingTitle {
5214 // Don't show "Loading" as the title. Ever.
5217 - (UIBarButtonItem *) rightButton {
5222 - (id) initWithDatabase:(Database *)database {
5223 if ((self = [super init]) != nil) {
5224 database_ = database;
5225 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5226 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5230 - (void) setPackage:(Package *)package {
5231 if (package_ != nil) {
5232 [package_ autorelease];
5241 [buttons_ removeAllObjects];
5243 if (package != nil) {
5246 package_ = [package retain];
5247 name_ = [[package id] retain];
5248 commercial_ = [package isCommercial];
5250 if ([package_ mode] != nil)
5251 [buttons_ addObject:UCLocalize("CLEAR")];
5252 if ([package_ source] == nil);
5253 else if ([package_ upgradableAndEssential:NO])
5254 [buttons_ addObject:UCLocalize("UPGRADE")];
5255 else if ([package_ uninstalled])
5256 [buttons_ addObject:UCLocalize("INSTALL")];
5258 [buttons_ addObject:UCLocalize("REINSTALL")];
5259 if (![package_ uninstalled])
5260 [buttons_ addObject:UCLocalize("REMOVE")];
5267 switch ([buttons_ count]) {
5268 case 0: title = nil; break;
5269 case 1: title = [buttons_ objectAtIndex:0]; break;
5270 default: title = UCLocalize("MODIFY"); break;
5273 button_ = [[UIBarButtonItem alloc]
5275 style:UIBarButtonItemStylePlain
5277 action:@selector(customButtonClicked)
5281 - (bool) isLoading {
5282 return commercial_ ? [super isLoading] : false;
5285 - (void) reloadData {
5286 [self setPackage:[database_ packageWithName:name_]];
5291 /* Package Table {{{ */
5292 @interface PackageTable : UIView <
5293 UITableViewDataSource,
5296 _transient Database *database_;
5297 NSMutableArray *packages_;
5298 NSMutableArray *sections_;
5300 NSMutableArray *index_;
5301 NSMutableDictionary *indices_;
5307 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5309 - (void) setDelegate:(id)delegate;
5311 - (void) reloadData;
5312 - (void) resetCursor;
5314 - (UITableView *) list;
5316 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5318 - (void) deselectWithAnimation:(BOOL)animated;
5322 @implementation PackageTable
5325 [packages_ release];
5326 [sections_ release];
5334 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5335 NSInteger count([sections_ count]);
5336 return count == 0 ? 1 : count;
5339 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5340 if ([sections_ count] == 0)
5342 return [[sections_ objectAtIndex:section] name];
5345 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5346 if ([sections_ count] == 0)
5348 return [[sections_ objectAtIndex:section] count];
5351 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5352 Section *section([sections_ objectAtIndex:[path section]]);
5353 NSInteger row([path row]);
5354 Package *package([packages_ objectAtIndex:([section row] + row)]);
5358 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5359 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5361 cell = [[[PackageCell alloc] init] autorelease];
5362 [cell setPackage:[self packageAtIndexPath:path]];
5366 - (void) deselectWithAnimation:(BOOL)animated {
5367 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5370 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5371 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5374 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5375 Package *package([self packageAtIndexPath:path]);
5376 package = [database_ packageWithName:[package id]];
5377 [target_ performSelector:action_ withObject:package];
5381 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5382 return [packages_ count] > 20 ? index_ : nil;
5385 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5389 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5390 if ((self = [super initWithFrame:frame]) != nil) {
5391 database_ = database;
5396 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5397 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5399 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5400 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5402 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5403 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5404 [list_ setRowHeight:73.0f];
5405 [self addSubview:list_];
5407 [list_ setDataSource:self];
5408 [list_ setDelegate:self];
5412 - (void) setDelegate:(id)delegate {
5413 delegate_ = delegate;
5416 - (bool) hasPackage:(Package *)package {
5420 - (void) reloadData {
5421 NSArray *packages = [database_ packages];
5423 [packages_ removeAllObjects];
5424 [sections_ removeAllObjects];
5426 _profile(PackageTable$reloadData$Filter)
5427 for (Package *package in packages)
5428 if ([self hasPackage:package])
5429 [packages_ addObject:package];
5432 [index_ removeAllObjects];
5433 [indices_ removeAllObjects];
5435 Section *section = nil;
5437 _profile(PackageTable$reloadData$Section)
5438 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5442 _profile(PackageTable$reloadData$Section$Package)
5443 package = [packages_ objectAtIndex:offset];
5444 index = [package index];
5447 if (section == nil || [section index] != index) {
5448 _profile(PackageTable$reloadData$Section$Allocate)
5449 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5452 [index_ addObject:[section name]];
5453 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5455 _profile(PackageTable$reloadData$Section$Add)
5456 [sections_ addObject:section];
5460 [section addToCount];
5464 _profile(PackageTable$reloadData$List)
5469 - (void) resetCursor {
5470 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5473 - (UITableView *) list {
5477 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5478 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5483 /* Filtered Package Table {{{ */
5484 @interface FilteredPackageTable : PackageTable {
5490 - (void) setObject:(id)object;
5491 - (void) setObject:(id)object forFilter:(SEL)filter;
5493 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5497 @implementation FilteredPackageTable
5505 - (void) setFilter:(SEL)filter {
5508 /* XXX: this is an unsafe optimization of doomy hell */
5509 Method method(class_getInstanceMethod([Package class], filter));
5510 _assert(method != NULL);
5511 imp_ = method_getImplementation(method);
5512 _assert(imp_ != NULL);
5515 - (void) setObject:(id)object {
5521 object_ = [object retain];
5524 - (void) setObject:(id)object forFilter:(SEL)filter {
5525 [self setFilter:filter];
5526 [self setObject:object];
5529 - (bool) hasPackage:(Package *)package {
5530 _profile(FilteredPackageTable$hasPackage)
5531 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5535 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5536 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5537 [self setFilter:filter];
5538 object_ = [object retain];
5546 /* Filtered Package Controller {{{ */
5547 @interface FilteredPackageController : CYViewController {
5548 _transient Database *database_;
5549 FilteredPackageTable *packages_;
5553 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5557 @implementation FilteredPackageController
5560 [packages_ release];
5566 - (void) viewDidAppear:(BOOL)animated {
5567 [super viewDidAppear:animated];
5568 [packages_ deselectWithAnimation:animated];
5571 - (void) didSelectPackage:(Package *)package {
5572 PackageController *view([delegate_ packageController]);
5573 [view setPackage:package];
5574 [view setDelegate:delegate_];
5575 [[self navigationController] pushViewController:view animated:YES];
5578 - (NSString *) title { return title_; }
5580 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5581 if ((self = [super init]) != nil) {
5582 database_ = database;
5583 title_ = [title copy];
5584 [[self navigationItem] setTitle:title_];
5586 packages_ = [[FilteredPackageTable alloc]
5587 initWithFrame:[[self view] bounds]
5590 action:@selector(didSelectPackage:)
5595 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5596 [[self view] addSubview:packages_];
5600 - (void) reloadData {
5601 [packages_ reloadData];
5604 - (void) setDelegate:(id)delegate {
5605 [super setDelegate:delegate];
5606 [packages_ setDelegate:delegate];
5613 /* Add Source Controller {{{ */
5614 @interface AddSourceController : CYViewController {
5615 _transient Database *database_;
5618 - (id) initWithDatabase:(Database *)database;
5622 @implementation AddSourceController
5624 - (id) initWithDatabase:(Database *)database {
5625 if ((self = [super init]) != nil) {
5626 database_ = database;
5632 /* Source Cell {{{ */
5633 @interface SourceCell : UITableViewCell <
5638 NSString *description_;
5640 ContentView *content_;
5643 - (void) setSource:(Source *)source;
5647 @implementation SourceCell
5649 - (void) clearSource {
5652 [description_ release];
5661 - (void) setSource:(Source *)source {
5665 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5667 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5668 icon_ = [icon_ retain];
5670 origin_ = [[source name] retain];
5671 label_ = [[source uri] retain];
5672 description_ = [[source description] retain];
5674 [content_ setNeedsDisplay];
5683 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5684 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5685 UIView *content([self contentView]);
5686 CGRect bounds([content bounds]);
5688 content_ = [[ContentView alloc] initWithFrame:bounds];
5689 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5690 [content_ setBackgroundColor:[UIColor whiteColor]];
5691 [content addSubview:content_];
5693 [content_ setDelegate:self];
5694 [content_ setOpaque:YES];
5698 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5699 [super setSelected:selected animated:animated];
5700 [content_ setNeedsDisplay];
5703 - (void) drawContentRect:(CGRect)rect {
5704 bool selected([self isSelected]);
5705 float width(rect.size.width);
5708 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5715 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5719 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5723 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5728 /* Source Table {{{ */
5729 @interface SourceTable : CYViewController <
5730 UITableViewDataSource,
5733 _transient Database *database_;
5735 NSMutableArray *sources_;
5739 UIProgressHUD *hud_;
5742 //NSURLConnection *installer_;
5743 NSURLConnection *trivial_;
5744 NSURLConnection *trivial_bz2_;
5745 NSURLConnection *trivial_gz_;
5746 //NSURLConnection *automatic_;
5751 - (id) initWithDatabase:(Database *)database;
5753 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5757 @implementation SourceTable
5759 - (void) _deallocConnection:(NSURLConnection *)connection {
5760 if (connection != nil) {
5761 [connection cancel];
5762 //[connection setDelegate:nil];
5763 [connection release];
5775 //[self _deallocConnection:installer_];
5776 [self _deallocConnection:trivial_];
5777 [self _deallocConnection:trivial_gz_];
5778 [self _deallocConnection:trivial_bz2_];
5779 //[self _deallocConnection:automatic_];
5786 - (void) viewDidAppear:(BOOL)animated {
5787 [super viewDidAppear:animated];
5788 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5791 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5792 return offset_ == 0 ? 1 : 2;
5795 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5796 switch (section + (offset_ == 0 ? 1 : 0)) {
5797 case 0: return UCLocalize("ENTERED_BY_USER");
5798 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5804 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5805 int count = [sources_ count];
5807 case 0: return (offset_ == 0 ? count : offset_);
5808 case 1: return count - offset_;
5814 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5816 switch (indexPath.section) {
5817 case 0: idx = indexPath.row; break;
5818 case 1: idx = indexPath.row + offset_; break;
5822 return [sources_ objectAtIndex:idx];
5825 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5826 Source *source = [self sourceAtIndexPath:indexPath];
5827 return [source description] == nil ? 56 : 73;
5830 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5831 static NSString *cellIdentifier = @"SourceCell";
5833 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5834 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5835 [cell setSource:[self sourceAtIndexPath:indexPath]];
5840 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5841 return UITableViewCellAccessoryDisclosureIndicator;
5844 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5845 Source *source = [self sourceAtIndexPath:indexPath];
5847 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5848 initWithDatabase:database_
5849 title:[source label]
5850 filter:@selector(isVisibleInSource:)
5854 [packages setDelegate:delegate_];
5856 [[self navigationController] pushViewController:packages animated:YES];
5859 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5860 Source *source = [self sourceAtIndexPath:indexPath];
5861 return [source record] != nil;
5864 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5865 Source *source = [self sourceAtIndexPath:indexPath];
5866 [Sources_ removeObjectForKey:[source key]];
5867 [delegate_ syncData];
5871 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5874 @"./", @"Distribution",
5875 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5877 [delegate_ syncData];
5880 - (NSString *) getWarning {
5881 NSString *href(href_);
5882 NSRange colon([href rangeOfString:@"://"]);
5883 if (colon.location != NSNotFound)
5884 href = [href substringFromIndex:(colon.location + 3)];
5885 href = [href stringByAddingPercentEscapes];
5886 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5887 href = [href stringByCachingURLWithCurrentCDN];
5889 NSURL *url([NSURL URLWithString:href]);
5891 NSStringEncoding encoding;
5892 NSError *error(nil);
5894 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5895 return [warning length] == 0 ? nil : warning;
5899 - (void) _endConnection:(NSURLConnection *)connection {
5900 NSURLConnection **field = NULL;
5901 if (connection == trivial_)
5903 else if (connection == trivial_bz2_)
5904 field = &trivial_bz2_;
5905 else if (connection == trivial_gz_)
5906 field = &trivial_gz_;
5907 _assert(field != NULL);
5908 [connection release];
5913 trivial_bz2_ == nil &&
5919 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5922 UIAlertView *alert = [[[UIAlertView alloc]
5923 initWithTitle:UCLocalize("SOURCE_WARNING")
5926 cancelButtonTitle:UCLocalize("CANCEL")
5927 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5930 [alert setContext:@"warning"];
5931 [alert setNumberOfRows:1];
5935 } else if (error_ != nil) {
5936 UIAlertView *alert = [[[UIAlertView alloc]
5937 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5938 message:[error_ localizedDescription]
5940 cancelButtonTitle:UCLocalize("OK")
5941 otherButtonTitles:nil
5944 [alert setContext:@"urlerror"];
5947 UIAlertView *alert = [[[UIAlertView alloc]
5948 initWithTitle:UCLocalize("NOT_REPOSITORY")
5949 message:UCLocalize("NOT_REPOSITORY_EX")
5951 cancelButtonTitle:UCLocalize("OK")
5952 otherButtonTitles:nil
5955 [alert setContext:@"trivial"];
5959 [delegate_ setStatusBarShowsProgress:NO];
5960 [delegate_ removeProgressHUD:hud_];
5970 if (error_ != nil) {
5977 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5978 switch ([response statusCode]) {
5984 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5985 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5987 error_ = [error retain];
5988 [self _endConnection:connection];
5991 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5992 [self _endConnection:connection];
5995 - (NSString *) title { return UCLocalize("SOURCES"); }
5997 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5998 NSMutableURLRequest *request = [NSMutableURLRequest
5999 requestWithURL:[NSURL URLWithString:href]
6000 cachePolicy:NSURLRequestUseProtocolCachePolicy
6001 timeoutInterval:120.0
6004 [request setHTTPMethod:method];
6006 if (Machine_ != NULL)
6007 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6008 if (UniqueID_ != nil)
6009 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6011 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6013 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6016 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6017 NSString *context([alert context]);
6019 if ([context isEqualToString:@"source"]) {
6022 NSString *href = [[alert textField] text];
6024 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6026 if (![href hasSuffix:@"/"])
6027 href_ = [href stringByAppendingString:@"/"];
6030 href_ = [href_ retain];
6032 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6033 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6034 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6035 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6039 hud_ = [[delegate_ addProgressHUD] retain];
6040 [hud_ setText:UCLocalize("VERIFYING_URL")];
6049 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6050 } else if ([context isEqualToString:@"trivial"])
6051 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6052 else if ([context isEqualToString:@"urlerror"])
6053 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6054 else if ([context isEqualToString:@"warning"]) {
6069 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6073 - (id) initWithDatabase:(Database *)database {
6074 if ((self = [super init]) != nil) {
6075 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6076 [self updateButtonsForEditingStatus:NO animated:NO];
6078 database_ = database;
6079 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6081 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6082 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6083 [[self view] addSubview:list_];
6085 [list_ setDataSource:self];
6086 [list_ setDelegate:self];
6092 - (void) reloadData {
6094 if (!list.ReadMainList())
6097 [sources_ removeAllObjects];
6098 [sources_ addObjectsFromArray:[database_ sources]];
6100 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6103 int count([sources_ count]);
6105 for (int i = 0; i != count; i++) {
6106 if ([[sources_ objectAtIndex:i] record] == nil) break;
6110 [list_ setEditing:NO];
6111 [self updateButtonsForEditingStatus:NO animated:NO];
6115 - (void) addButtonClicked {
6116 /*[book_ pushPage:[[[AddSourceController alloc]
6121 UIAlertView *alert = [[[UIAlertView alloc]
6122 initWithTitle:UCLocalize("ENTER_APT_URL")
6125 cancelButtonTitle:UCLocalize("CANCEL")
6126 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6129 [alert setContext:@"source"];
6130 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6132 [alert setNumberOfRows:1];
6133 [alert addTextFieldWithValue:@"http://" label:@""];
6135 UITextInputTraits *traits = [[alert textField] textInputTraits];
6136 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6137 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6138 [traits setKeyboardType:UIKeyboardTypeURL];
6139 // XXX: UIReturnKeyDone
6140 [traits setReturnKeyType:UIReturnKeyNext];
6145 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6146 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
6147 initWithTitle:UCLocalize("ADD")
6148 style:UIBarButtonItemStylePlain
6150 action:@selector(addButtonClicked)
6152 [[self navigationItem] setLeftBarButtonItem:editing ? leftItem : [[self navigationItem] backBarButtonItem] animated:animated];
6155 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6156 initWithTitle:editing ? UCLocalize("DONE") : UCLocalize("EDIT")
6157 style:editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6159 action:@selector(editButtonClicked)
6161 [[self navigationItem] setRightBarButtonItem:rightItem animated:animated];
6162 [rightItem release];
6164 if (IsWildcat_ && !editing) {
6165 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6166 initWithTitle:UCLocalize("SETTINGS")
6167 style:UIBarButtonItemStylePlain
6169 action:@selector(settingsButtonClicked)
6171 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6172 [settingsItem release];
6176 - (void) settingsButtonClicked {
6177 [delegate_ showSettings];
6180 - (void) editButtonClicked {
6181 [list_ setEditing:![list_ isEditing] animated:YES];
6183 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6189 /* Installed Controller {{{ */
6190 @interface InstalledController : FilteredPackageController {
6194 - (id) initWithDatabase:(Database *)database;
6196 - (void) updateRoleButton;
6197 - (void) queueStatusDidChange;
6201 @implementation InstalledController
6207 - (NSString *) title { return UCLocalize("INSTALLED"); }
6209 - (id) initWithDatabase:(Database *)database {
6210 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6211 [self updateRoleButton];
6212 [self queueStatusDidChange];
6217 - (void) queueButtonClicked {
6222 - (void) queueStatusDidChange {
6225 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6226 initWithTitle:UCLocalize("QUEUE")
6227 style:UIBarButtonItemStyleDone
6229 action:@selector(queueButtonClicked)
6231 if (Queuing_) [[self navigationItem] setLeftBarButtonItem:queueItem];
6232 else [[self navigationItem] setLeftBarButtonItem:nil];
6233 [queueItem release];
6238 - (void) reloadData {
6239 [packages_ reloadData];
6242 - (void) updateRoleButton {
6243 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6244 initWithTitle:expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")
6245 style:expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6247 action:@selector(roleButtonClicked)
6249 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) [[self navigationItem] setRightBarButtonItem:rightItem];
6250 [rightItem release];
6253 - (void) roleButtonClicked {
6254 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6255 [packages_ reloadData];
6258 [self updateRoleButton];
6261 - (void) setDelegate:(id)delegate {
6262 [super setDelegate:delegate];
6263 [packages_ setDelegate:delegate];
6269 /* Home Controller {{{ */
6270 @interface HomeController : CYBrowserController {
6275 @implementation HomeController
6277 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6278 [super _setMoreHeaders:request];
6281 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6282 if (UniqueID_ != nil)
6283 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6285 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6288 - (void) aboutButtonClicked {
6289 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6291 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6292 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6293 [alert setCancelButtonIndex:0];
6296 @"Copyright (C) 2008-2010\n"
6297 "Jay Freeman (saurik)\n"
6298 "saurik@saurik.com\n"
6299 "http://www.saurik.com/"
6305 - (void) viewWillAppear:(BOOL)animated {
6306 [super viewWillAppear:animated];
6307 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6310 - (void) viewWillDisappear:(BOOL)animated {
6311 [super viewWillDisappear:animated];
6312 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6316 if ((self = [super init]) != nil) {
6317 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6318 initWithTitle:UCLocalize("ABOUT")
6319 style:UIBarButtonItemStylePlain
6321 action:@selector(aboutButtonClicked)
6328 /* Manage Controller {{{ */
6329 @interface ManageController : CYBrowserController {
6332 - (void) queueStatusDidChange;
6335 @implementation ManageController
6338 if ((self = [super init]) != nil) {
6339 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6341 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6342 initWithTitle:UCLocalize("SETTINGS")
6343 style:UIBarButtonItemStylePlain
6345 action:@selector(settingsButtonClicked)
6347 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6348 [settingsItem release];
6350 [self queueStatusDidChange];
6354 - (void) settingsButtonClicked {
6355 [delegate_ showSettings];
6359 - (void) queueButtonClicked {
6363 - (void) applyLoadingTitle {
6364 // No "Loading" title.
6367 - (void) applyRightButton {
6372 - (void) queueStatusDidChange {
6374 if (!IsWildcat_ && Queuing_) {
6375 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6376 initWithTitle:UCLocalize("QUEUE")
6377 style:UIBarButtonItemStyleDone
6379 action:@selector(queueButtonClicked)
6381 [[self navigationItem] setRightBarButtonItem:queueItem];
6383 [queueItem release];
6385 [[self navigationItem] setRightBarButtonItem:nil];
6390 - (bool) isLoading {
6397 /* Refresh Bar {{{ */
6398 @interface RefreshBar : UINavigationBar {
6399 UIProgressIndicator *indicator_;
6400 UITextLabel *prompt_;
6401 UIProgressBar *progress_;
6402 UINavigationButton *cancel_;
6407 @implementation RefreshBar
6409 - (void) positionViews {
6410 CGRect frame = [cancel_ frame];
6411 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6412 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6413 [cancel_ setFrame:frame];
6415 CGSize prgsize = {75, 100};
6417 [self frame].size.width - prgsize.width - 10,
6418 ([self frame].size.height - prgsize.height) / 2
6420 [progress_ setFrame:prgrect];
6422 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6423 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6424 CGRect indrect = {{indoffset, indoffset}, indsize};
6425 [indicator_ setFrame:indrect];
6427 CGSize prmsize = {215, indsize.height + 4};
6429 indoffset * 2 + indsize.width,
6430 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6432 [prompt_ setFrame:prmrect];
6435 - (void)setFrame:(CGRect)frame {
6436 [super setFrame:frame];
6438 [self positionViews];
6441 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6442 if ((self = [super initWithFrame:frame])) {
6443 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6445 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6446 [self setBarStyle:UIBarStyleBlack];
6448 UIBarStyle barstyle([self _barStyle:NO]);
6449 bool ugly(barstyle == UIBarStyleDefault);
6451 UIProgressIndicatorStyle style = ugly ?
6452 UIProgressIndicatorStyleMediumBrown :
6453 UIProgressIndicatorStyleMediumWhite;
6455 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6456 [indicator_ setStyle:style];
6457 [indicator_ startAnimation];
6458 [self addSubview:indicator_];
6460 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6461 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6462 [prompt_ setBackgroundColor:[UIColor clearColor]];
6463 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6464 [self addSubview:prompt_];
6466 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6467 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6468 [progress_ setStyle:0];
6469 [self addSubview:progress_];
6471 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6472 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6473 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6474 [cancel_ setBarStyle:barstyle];
6476 [self positionViews];
6481 [cancel_ removeFromSuperview];
6485 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6486 [progress_ setProgress:0];
6487 [self addSubview:cancel_];
6491 [cancel_ removeFromSuperview];
6494 - (void) setPrompt:(NSString *)prompt {
6495 [prompt_ setText:prompt];
6498 - (void) setProgress:(float)progress {
6499 [progress_ setProgress:progress];
6505 @class CYNavigationController;
6507 /* Cydia Tab Bar Controller {{{ */
6508 @interface CYTabBarController : UITabBarController {
6509 Database *database_;
6514 @implementation CYTabBarController
6516 /* XXX: some logic should probably go here related to
6517 freeing the view controllers on tab change */
6519 - (void) reloadData {
6520 size_t count([[self viewControllers] count]);
6521 for (size_t i(0); i != count; ++i) {
6522 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6527 - (id) initWithDatabase:(Database *)database {
6528 if ((self = [super init]) != nil) {
6529 database_ = database;
6536 /* Cydia Navigation Controller {{{ */
6537 @interface CYNavigationController : UINavigationController {
6538 _transient Database *database_;
6539 id<UINavigationControllerDelegate> delegate_;
6542 - (id) initWithDatabase:(Database *)database;
6543 - (void) reloadData;
6548 @implementation CYNavigationController
6550 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6551 // Inherit autorotation settings for modal parents.
6552 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6553 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6555 return [super shouldAutorotateToInterfaceOrientation:orientation];
6563 - (void) reloadData {
6564 size_t count([[self viewControllers] count]);
6565 for (size_t i(0); i != count; ++i) {
6566 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6571 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6572 delegate_ = delegate;
6575 - (id) initWithDatabase:(Database *)database {
6576 if ((self = [super init]) != nil) {
6577 database_ = database;
6583 /* Cydia:// Protocol {{{ */
6584 @interface CydiaURLProtocol : NSURLProtocol {
6589 @implementation CydiaURLProtocol
6591 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6592 NSURL *url([request URL]);
6595 NSString *scheme([[url scheme] lowercaseString]);
6596 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6601 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6605 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6606 id<NSURLProtocolClient> client([self client]);
6608 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6610 NSData *data(UIImagePNGRepresentation(icon));
6612 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6613 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6614 [client URLProtocol:self didLoadData:data];
6615 [client URLProtocolDidFinishLoading:self];
6619 - (void) startLoading {
6620 id<NSURLProtocolClient> client([self client]);
6621 NSURLRequest *request([self request]);
6623 NSURL *url([request URL]);
6624 NSString *href([url absoluteString]);
6626 NSString *path([href substringFromIndex:8]);
6627 NSRange slash([path rangeOfString:@"/"]);
6630 if (slash.location == NSNotFound) {
6634 command = [path substringToIndex:slash.location];
6635 path = [path substringFromIndex:(slash.location + 1)];
6638 Database *database([Database sharedInstance]);
6640 if ([command isEqualToString:@"package-icon"]) {
6643 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6644 Package *package([database packageWithName:path]);
6647 UIImage *icon([package icon]);
6648 [self _returnPNGWithImage:icon forRequest:request];
6649 } else if ([command isEqualToString:@"source-icon"]) {
6652 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6653 NSString *source(Simplify(path));
6654 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6656 icon = [UIImage applicationImageNamed:@"unknown.png"];
6657 [self _returnPNGWithImage:icon forRequest:request];
6658 } else if ([command isEqualToString:@"uikit-image"]) {
6661 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6662 UIImage *icon(_UIImageWithName(path));
6663 [self _returnPNGWithImage:icon forRequest:request];
6664 } else if ([command isEqualToString:@"section-icon"]) {
6667 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6668 NSString *section(Simplify(path));
6669 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6671 icon = [UIImage applicationImageNamed:@"unknown.png"];
6672 [self _returnPNGWithImage:icon forRequest:request];
6674 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6678 - (void) stopLoading {
6684 /* Sections Controller {{{ */
6685 @interface SectionsController : CYViewController <
6686 UITableViewDataSource,
6689 _transient Database *database_;
6690 NSMutableArray *sections_;
6691 NSMutableArray *filtered_;
6697 - (id) initWithDatabase:(Database *)database;
6698 - (void) reloadData;
6701 - (void) editButtonClicked;
6705 @implementation SectionsController
6708 [list_ setDataSource:nil];
6709 [list_ setDelegate:nil];
6711 [sections_ release];
6712 [filtered_ release];
6714 [accessory_ release];
6718 - (void) viewDidAppear:(BOOL)animated {
6719 [super viewDidAppear:animated];
6720 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6723 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6724 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6728 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6729 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6732 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6736 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6737 static NSString *reuseIdentifier = @"SectionCell";
6739 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6740 if (cell == nil) cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6741 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6746 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6750 Section *section = [self sectionAtIndexPath:indexPath];
6751 NSString *name = [section name];
6754 if ([indexPath row] == 0) {
6757 title = UCLocalize("ALL_PACKAGES");
6760 name = [NSString stringWithString:name];
6761 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6764 title = UCLocalize("NO_SECTION");
6768 FilteredPackageController *table = [[[FilteredPackageController alloc]
6769 initWithDatabase:database_
6771 filter:@selector(isVisibleInSection:)
6775 [table setDelegate:delegate_];
6777 [[self navigationController] pushViewController:table animated:YES];
6780 - (NSString *) title { return UCLocalize("SECTIONS"); }
6782 - (id) initWithDatabase:(Database *)database {
6783 if ((self = [super init]) != nil) {
6784 database_ = database;
6786 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6788 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6789 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6791 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6792 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6793 [list_ setRowHeight:45.0f];
6794 [[self view] addSubview:list_];
6796 [list_ setDataSource:self];
6797 [list_ setDelegate:self];
6803 - (void) reloadData {
6804 NSArray *packages = [database_ packages];
6806 [sections_ removeAllObjects];
6807 [filtered_ removeAllObjects];
6810 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6811 SectionMap sections;
6812 sections.resize(64);
6814 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6818 for (Package *package in packages) {
6819 NSString *name([package section]);
6820 NSString *key(name == nil ? @"" : name);
6825 _profile(SectionsView$reloadData$Section)
6826 section = §ions[key];
6827 if (*section == nil) {
6828 _profile(SectionsView$reloadData$Section$Allocate)
6829 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6834 [*section addToCount];
6836 _profile(SectionsView$reloadData$Filter)
6837 if (![package valid] || ![package visible])
6841 [*section addToRow];
6845 _profile(SectionsView$reloadData$Section)
6846 section = [sections objectForKey:key];
6847 if (section == nil) {
6848 _profile(SectionsView$reloadData$Section$Allocate)
6849 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6850 [sections setObject:section forKey:key];
6855 [section addToCount];
6857 _profile(SectionsView$reloadData$Filter)
6858 if (![package valid] || ![package visible])
6868 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6869 [sections_ addObject:i->second];
6871 [sections_ addObjectsFromArray:[sections allValues]];
6874 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6876 for (Section *section in sections_) {
6877 size_t count([section row]);
6881 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6882 [section setCount:count];
6883 [filtered_ addObject:section];
6886 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6887 initWithTitle:[sections_ count] == 0 ? nil : UCLocalize("EDIT")
6888 style:UIBarButtonItemStylePlain
6890 action:@selector(editButtonClicked)
6892 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] != nil];
6893 [rightItem release];
6899 - (void) resetView {
6901 [self editButtonClicked];
6904 - (void) editButtonClicked {
6905 if ((editing_ = !editing_))
6908 [delegate_ updateData];
6910 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6911 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6912 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6915 - (UIView *) accessoryView {
6921 /* Changes Controller {{{ */
6922 @interface ChangesController : CYViewController <
6923 UITableViewDataSource,
6926 _transient Database *database_;
6927 CFMutableArrayRef packages_;
6928 NSMutableArray *sections_;
6931 BOOL hasSentFirstLoad_;
6934 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6935 - (void) reloadData;
6939 @implementation ChangesController
6942 [list_ setDelegate:nil];
6943 [list_ setDataSource:nil];
6945 CFRelease(packages_);
6947 [sections_ release];
6952 - (void) viewDidAppear:(BOOL)animated {
6953 [super viewDidAppear:animated];
6954 if (!hasSentFirstLoad_) {
6955 hasSentFirstLoad_ = YES;
6956 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6958 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6962 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6963 NSInteger count([sections_ count]);
6964 return count == 0 ? 1 : count;
6967 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6968 if ([sections_ count] == 0)
6970 return [[sections_ objectAtIndex:section] name];
6973 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6974 if ([sections_ count] == 0)
6976 return [[sections_ objectAtIndex:section] count];
6979 - (Package *) packageAtIndex:(NSUInteger)index {
6980 return (Package *) CFArrayGetValueAtIndex(packages_, index);
6983 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6984 Section *section([sections_ objectAtIndex:[path section]]);
6985 NSInteger row([path row]);
6986 return [self packageAtIndex:([section row] + row)];
6989 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6990 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6992 cell = [[[PackageCell alloc] init] autorelease];
6993 [cell setPackage:[self packageAtIndexPath:path]];
6997 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
6998 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7001 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7002 Package *package([self packageAtIndexPath:path]);
7003 PackageController *view([delegate_ packageController]);
7004 [view setDelegate:delegate_];
7005 [view setPackage:package];
7006 [[self navigationController] pushViewController:view animated:YES];
7010 - (void) refreshButtonClicked {
7011 [delegate_ beginUpdate];
7012 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7015 - (void) upgradeButtonClicked {
7016 [delegate_ distUpgrade];
7019 - (NSString *) title { return UCLocalize("CHANGES"); }
7021 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7022 if ((self = [super init]) != nil) {
7023 database_ = database;
7024 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7026 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7028 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7030 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7031 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7032 [list_ setRowHeight:73.0f];
7033 [[self view] addSubview:list_];
7035 [list_ setDataSource:self];
7036 [list_ setDelegate:self];
7038 delegate_ = delegate;
7042 - (void) _reloadPackages:(NSArray *)packages {
7044 for (Package *package in packages)
7046 [package uninstalled] && [package valid] && [package visible] ||
7047 [package upgradableAndEssential:YES]
7049 CFArrayAppendValue(packages_, package);
7052 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7056 - (void) reloadData {
7057 NSArray *packages = [database_ packages];
7059 CFArrayRemoveAllValues(packages_);
7061 [sections_ removeAllObjects];
7064 UIProgressHUD *hud([delegate_ addProgressHUD]);
7066 [hud setText:@"Loading Changes"];
7067 //NSLog(@"HUD:%@::%@", delegate_, hud);
7068 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7069 [delegate_ removeProgressHUD:hud];
7071 [self _reloadPackages:packages];
7074 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7075 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7076 Section *section = nil;
7080 bool unseens = false;
7082 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7084 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7085 Package *package = [self packageAtIndex:offset];
7087 BOOL uae = [package upgradableAndEssential:YES];
7093 _profile(ChangesController$reloadData$Remember)
7094 seen = [package seen];
7097 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7102 name = UCLocalize("UNKNOWN");
7104 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7108 _profile(ChangesController$reloadData$Allocate)
7109 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7110 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7111 [sections_ addObject:section];
7115 [section addToCount];
7116 } else if ([package ignored])
7117 [ignored addToCount];
7120 [upgradable addToCount];
7125 CFRelease(formatter);
7128 Section *last = [sections_ lastObject];
7129 size_t count = [last count];
7130 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7131 [sections_ removeLastObject];
7134 if ([ignored count] != 0)
7135 [sections_ insertObject:ignored atIndex:0];
7137 [sections_ insertObject:upgradable atIndex:0];
7141 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7142 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7143 style:UIBarButtonItemStylePlain
7145 action:@selector(upgradeButtonClicked)
7147 if (upgrades_ > 0) [[self navigationItem] setRightBarButtonItem:rightItem];
7148 [rightItem release];
7150 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
7151 initWithTitle:UCLocalize("REFRESH")
7152 style:UIBarButtonItemStylePlain
7154 action:@selector(refreshButtonClicked)
7156 if (![delegate_ updating]) [[self navigationItem] setLeftBarButtonItem:leftItem];
7162 /* Search Controller {{{ */
7163 @interface SearchController : FilteredPackageController <
7166 UISearchBar *search_;
7169 - (id) initWithDatabase:(Database *)database;
7170 - (void) reloadData;
7174 @implementation SearchController
7181 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7182 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7183 [search_ resignFirstResponder];
7187 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7188 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7192 - (NSString *) title { return nil; }
7194 - (id) initWithDatabase:(Database *)database {
7195 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7198 - (void)viewDidAppear:(BOOL)animated {
7199 [super viewDidAppear:animated];
7201 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7202 [search_ layoutSubviews];
7203 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7204 UITextField *textField = [search_ searchField];
7205 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7206 [search_ setDelegate:self];
7207 [textField setEnablesReturnKeyAutomatically:NO];
7208 [[self navigationItem] setTitleView:textField];
7212 - (void) _reloadData {
7215 - (void) reloadData {
7216 _profile(SearchController$reloadData)
7217 [packages_ reloadData];
7220 [packages_ resetCursor];
7223 - (void) didSelectPackage:(Package *)package {
7224 [search_ resignFirstResponder];
7225 [super didSelectPackage:package];
7230 /* Settings Controller {{{ */
7231 @interface SettingsController : CYViewController <
7232 UITableViewDataSource,
7235 _transient Database *database_;
7238 UITableView *table_;
7239 id subscribedSwitch_;
7241 UITableViewCell *subscribedCell_;
7242 UITableViewCell *ignoredCell_;
7245 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7249 @implementation SettingsController
7253 if (package_ != nil)
7256 [subscribedSwitch_ release];
7257 [ignoredSwitch_ release];
7258 [subscribedCell_ release];
7259 [ignoredCell_ release];
7264 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7265 if (package_ == nil)
7271 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7272 if (package_ == nil)
7278 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7279 return UCLocalize("SHOW_ALL_CHANGES_EX");
7282 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7283 if (package_ == nil)
7286 NSMutableDictionary *metadata([package_ metadata]);
7289 if (NSNumber *number = [metadata objectForKey:key])
7290 before = [number boolValue];
7294 if (value != before) {
7295 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7297 [delegate_ updateData];
7301 - (void) onSubscribed:(id)control {
7302 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7305 - (void) onIgnored:(id)control {
7306 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
7309 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7310 if (package_ == nil)
7313 switch ([indexPath row]) {
7314 case 0: return subscribedCell_;
7315 case 1: return ignoredCell_;
7323 - (NSString *) title { return UCLocalize("SETTINGS"); }
7325 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7326 if ((self = [super init])) {
7327 database_ = database;
7328 name_ = [package retain];
7330 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7332 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7333 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7334 [[self view] addSubview:table_];
7336 subscribedSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7337 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7338 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7340 ignoredSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7341 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7342 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7344 subscribedCell_ = [[UITableViewCell alloc] init];
7345 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7346 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7347 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7349 ignoredCell_ = [[UITableViewCell alloc] init];
7350 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7351 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7352 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7354 [table_ setDataSource:self];
7355 [table_ setDelegate:self];
7360 - (void) reloadData {
7361 if (package_ != nil)
7362 [package_ autorelease];
7363 package_ = [database_ packageWithName:name_];
7364 if (package_ != nil) {
7366 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7367 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7370 [table_ reloadData];
7375 /* Signature Controller {{{ */
7376 @interface SignatureController : CYBrowserController {
7377 _transient Database *database_;
7381 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7385 @implementation SignatureController
7392 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7394 [super webView:view didClearWindowObject:window forFrame:frame];
7397 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7398 if ((self = [super init]) != nil) {
7399 database_ = database;
7400 package_ = [package retain];
7405 - (void) reloadData {
7406 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7412 /* Role Controller {{{ */
7413 @interface RoleController : CYViewController <
7414 UITableViewDataSource,
7417 _transient Database *database_;
7419 UITableView *table_;
7420 UISegmentedControl *segment_;
7424 - (void) showDoneButton;
7425 - (void) resizeSegmentedControl;
7429 @implementation RoleController
7433 [container_ release];
7438 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7439 if ((self = [super init])) {
7440 database_ = database;
7441 roledelegate_ = delegate;
7443 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7445 NSArray *items = [NSArray arrayWithObjects:
7447 UCLocalize("HACKER"),
7448 UCLocalize("DEVELOPER"),
7450 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7451 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7452 [container_ addSubview:segment_];
7455 if ([Role_ isEqualToString:@"User"]) index = 0;
7456 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7457 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7459 [segment_ setSelectedSegmentIndex:index];
7460 [self showDoneButton];
7463 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7464 [self resizeSegmentedControl];
7466 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7467 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7468 [table_ setDelegate:self];
7469 [table_ setDataSource:self];
7470 [[self view] addSubview:table_];
7471 [table_ reloadData];
7475 - (void) resizeSegmentedControl {
7476 CGFloat width = [[self view] frame].size.width;
7477 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7480 - (void) viewWillAppear:(BOOL)animated {
7481 [super viewWillAppear:animated];
7483 [self resizeSegmentedControl];
7486 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7487 [self resizeSegmentedControl];
7490 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7491 [self resizeSegmentedControl];
7495 NSString *role(nil);
7497 switch ([segment_ selectedSegmentIndex]) {
7498 case 0: role = @"User"; break;
7499 case 1: role = @"Hacker"; break;
7500 case 2: role = @"Developer"; break;
7505 if (![role isEqualToString:Role_]) {
7506 bool rolling(Role_ == nil);
7509 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7513 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7518 [roledelegate_ loadData];
7520 [roledelegate_ updateData];
7524 - (void) segmentChanged:(UISegmentedControl *)control {
7525 [self showDoneButton];
7528 - (void) doneButtonClicked {
7530 [[self navigationController] dismissModalViewControllerAnimated:YES];
7533 - (void) showDoneButton {
7534 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7535 initWithTitle:UCLocalize("DONE")
7536 style:UIBarButtonItemStyleDone
7538 action:@selector(doneButtonClicked)
7540 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] == nil];
7541 [rightItem release];
7544 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7545 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7549 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7553 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7554 return nil; // This method is required by the protocol.
7557 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7559 return UCLocalize("ROLE_EX");
7561 return [NSString stringWithFormat:
7562 @"%@: %@\n%@: %@\n%@: %@",
7563 UCLocalize("USER"), UCLocalize("USER_EX"),
7564 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7565 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7570 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7571 if (section == 3) return 44.0f;
7575 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7576 if (section == 3) return container_;
7582 /* Stash Controller {{{ */
7583 @interface CYStashController : CYViewController {
7584 UIActivityIndicatorView *spinner_;
7590 @implementation CYStashController
7592 if ((self = [super init])) {
7593 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7595 spinner_ = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
7596 CGRect spinrect = [spinner_ frame];
7597 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7598 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7599 [spinner_ setFrame:spinrect];
7600 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7601 [[self view] addSubview:spinner_];
7603 [spinner_ startAnimating];
7606 captrect.size.width = [[self view] frame].size.width;
7607 captrect.size.height = 40.0f;
7608 captrect.origin.x = 0;
7609 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7610 caption_ = [[UILabel alloc] initWithFrame:captrect];
7611 [caption_ setText:@"Initializing Filesystem"];
7612 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7613 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7614 [caption_ setTextColor:[UIColor whiteColor]];
7615 [caption_ setBackgroundColor:[UIColor clearColor]];
7616 [caption_ setShadowColor:[UIColor blackColor]];
7617 [caption_ setTextAlignment:UITextAlignmentCenter];
7618 [[self view] addSubview:caption_];
7622 statusrect.size.width = [[self view] frame].size.width;
7623 statusrect.size.height = 30.0f;
7624 statusrect.origin.x = 0;
7625 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7626 status_ = [[UILabel alloc] initWithFrame:statusrect];
7627 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7628 [status_ setText:@"(Cydia will exit when complete.)"];
7629 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7630 [status_ setTextColor:[UIColor whiteColor]];
7631 [status_ setBackgroundColor:[UIColor clearColor]];
7632 [status_ setShadowColor:[UIColor blackColor]];
7633 [status_ setTextAlignment:UITextAlignmentCenter];
7634 [[self view] addSubview:status_];
7639 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7640 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7645 /* Cydia Container {{{ */
7646 @interface CYContainer : UIViewController <ProgressDelegate> {
7647 _transient Database *database_;
7648 RefreshBar *refreshbar_;
7653 UITabBarController *root_;
7656 - (void) setTabBarController:(UITabBarController *)controller;
7658 - (void) dropBar:(BOOL)animated;
7659 - (void) beginUpdate;
7660 - (void) raiseBar:(BOOL)animated;
7665 @implementation CYContainer
7667 - (BOOL) _reallyWantsFullScreenLayout {
7671 // NOTE: UIWindow only sends the top controller these messages,
7672 // So we have to forward them on.
7674 - (void) viewDidAppear:(BOOL)animated {
7675 [super viewDidAppear:animated];
7676 [root_ viewDidAppear:animated];
7679 - (void) viewWillAppear:(BOOL)animated {
7680 [super viewWillAppear:animated];
7681 [root_ viewWillAppear:animated];
7684 - (void) viewDidDisappear:(BOOL)animated {
7685 [super viewDidDisappear:animated];
7686 [root_ viewDidDisappear:animated];
7689 - (void) viewWillDisappear:(BOOL)animated {
7690 [super viewWillDisappear:animated];
7691 [root_ viewWillDisappear:animated];
7694 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7695 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7698 - (void) setTabBarController:(UITabBarController *)controller {
7700 [[self view] addSubview:[root_ view]];
7703 - (void) setUpdate:(NSDate *)date {
7707 - (void) beginUpdate {
7709 [refreshbar_ start];
7714 detachNewThreadSelector:@selector(performUpdate)
7720 - (void) performUpdate { _pooled
7722 status.setDelegate(self);
7723 [database_ updateWithStatus:status];
7726 performSelectorOnMainThread:@selector(completeUpdate)
7732 - (void) completeUpdate {
7733 if (!updating_) return;
7736 [self raiseBar:YES];
7738 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7741 - (void) cancelUpdate {
7743 [self raiseBar:YES];
7745 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7748 - (void) cancelPressed {
7749 [self cancelUpdate];
7756 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7757 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7760 - (void) startProgress {
7763 - (void) setProgressTitle:(NSString *)title {
7765 performSelectorOnMainThread:@selector(_setProgressTitle:)
7771 - (bool) isCancelling:(size_t)received {
7775 - (void) setProgressPercent:(float)percent {
7777 performSelectorOnMainThread:@selector(_setProgressPercent:)
7778 withObject:[NSNumber numberWithFloat:percent]
7783 - (void) addProgressOutput:(NSString *)output {
7785 performSelectorOnMainThread:@selector(_addProgressOutput:)
7791 - (void) _setProgressTitle:(NSString *)title {
7792 [refreshbar_ setPrompt:title];
7795 - (void) _setProgressPercent:(NSNumber *)percent {
7796 [refreshbar_ setProgress:[percent floatValue]];
7799 - (void) _addProgressOutput:(NSString *)output {
7802 - (void) setUpdateDelegate:(id)delegate {
7803 updatedelegate_ = delegate;
7806 - (CGFloat) statusBarHeight {
7807 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7808 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7810 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7814 - (void) dropBar:(BOOL)animated {
7815 if (dropped_) return;
7818 [[self view] addSubview:refreshbar_];
7820 CGFloat sboffset = [self statusBarHeight];
7822 CGRect barframe = [refreshbar_ frame];
7823 barframe.origin.y = sboffset;
7824 [refreshbar_ setFrame:barframe];
7826 if (animated) [UIView beginAnimations:nil context:NULL];
7827 CGRect viewframe = [[root_ view] frame];
7828 viewframe.origin.y += barframe.size.height + sboffset;
7829 viewframe.size.height -= barframe.size.height + sboffset;
7830 [[root_ view] setFrame:viewframe];
7831 if (animated) [UIView commitAnimations];
7833 // Ensure bar has the proper width for our view, it might have changed
7834 barframe.size.width = viewframe.size.width;
7835 [refreshbar_ setFrame:barframe];
7837 // XXX: fix Apple's layout bug
7838 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7841 - (void) raiseBar:(BOOL)animated {
7842 if (!dropped_) return;
7845 [refreshbar_ removeFromSuperview];
7847 CGFloat sboffset = [self statusBarHeight];
7849 if (animated) [UIView beginAnimations:nil context:NULL];
7850 CGRect barframe = [refreshbar_ frame];
7851 CGRect viewframe = [[root_ view] frame];
7852 viewframe.origin.y -= barframe.size.height + sboffset;
7853 viewframe.size.height += barframe.size.height + sboffset;
7854 [[root_ view] setFrame:viewframe];
7855 if (animated) [UIView commitAnimations];
7857 // XXX: fix Apple's layout bug
7858 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7861 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7862 // XXX: fix Apple's layout bug
7863 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7866 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7872 // XXX: fix Apple's layout bug
7873 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7876 - (void) statusBarFrameChanged:(NSNotification *)notification {
7884 [refreshbar_ release];
7885 [[NSNotificationCenter defaultCenter] removeObserver:self];
7889 - (id) initWithDatabase:(Database *)database {
7890 if ((self = [super init]) != nil) {
7891 database_ = database;
7893 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7894 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7896 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7913 @interface Cydia : UIApplication <
7914 ConfirmationControllerDelegate,
7915 ProgressControllerDelegate,
7917 UINavigationControllerDelegate
7920 CYContainer *container_;
7923 NSMutableArray *essential_;
7924 NSMutableArray *broken_;
7926 Database *database_;
7930 UIKeyboard *keyboard_;
7931 UIProgressHUD *hud_;
7933 SectionsController *sections_;
7934 ChangesController *changes_;
7935 ManageController *manage_;
7936 SearchController *search_;
7937 SourceTable *sources_;
7938 InstalledController *installed_;
7941 CYStashController *stash_;
7946 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7947 - (void) setPage:(CYViewController *)page;
7952 static _finline void _setHomePage(Cydia *self) {
7953 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7956 @implementation Cydia
7958 - (void) beginUpdate {
7959 [container_ beginUpdate];
7963 return [container_ updating];
7966 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7971 if ([broken_ count] != 0) {
7972 int count = [broken_ count];
7974 UIAlertView *alert = [[[UIAlertView alloc]
7975 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7976 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7978 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7979 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
7982 [alert setContext:@"fixhalf"];
7984 } else if (!Ignored_ && [essential_ count] != 0) {
7985 int count = [essential_ count];
7987 UIAlertView *alert = [[[UIAlertView alloc]
7988 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7989 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
7991 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
7992 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
7995 [alert setContext:@"upgrade"];
8000 - (void) _saveConfig {
8003 NSString *error(nil);
8004 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8006 NSError *error(nil);
8007 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8008 NSLog(@"failure to save metadata data: %@", error);
8011 NSLog(@"failure to serialize metadata: %@", error);
8019 - (void) _updateData {
8022 /* XXX: this is just stupid */
8023 if (tag_ != 1 && sections_ != nil)
8024 [sections_ reloadData];
8025 if (tag_ != 2 && changes_ != nil)
8026 [changes_ reloadData];
8027 if (tag_ != 4 && search_ != nil)
8028 [search_ reloadData];
8030 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8033 - (int)indexOfTabWithTag:(int)tag {
8035 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8036 if ([[controller tabBarItem] tag] == tag) return i;
8043 - (void) _refreshIfPossible {
8044 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8046 bool recently = false;
8047 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8048 if (update != nil) {
8049 NSTimeInterval interval([update timeIntervalSinceNow]);
8050 if (interval <= 0 && interval > -(15*60))
8054 // Don't automatic refresh if:
8055 // - We already refreshed recently.
8056 // - We already auto-refreshed this launch.
8057 // - Auto-refresh is disabled.
8058 if (recently || loaded_ || ManualRefresh) {
8059 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8061 // If we are cancelling due to ManualRefresh or a recent refresh
8062 // we need to make sure it knows it's already loaded.
8066 // We are going to load, so remember that.
8070 SCNetworkReachabilityFlags flags; {
8071 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8072 SCNetworkReachabilityGetFlags(reachability, &flags);
8073 CFRelease(reachability);
8076 // XXX: this elaborate mess is what Apple is using to determine this? :(
8077 // XXX: do we care if the user has to intervene? maybe that's ok?
8079 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8080 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8081 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8082 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8083 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8084 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8088 // If we can reach the server, auto-refresh!
8090 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8095 - (void) refreshIfPossible {
8096 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8099 - (void) _reloadData {
8100 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8101 [hud setText:UCLocalize("RELOADING_DATA")];
8103 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8105 if (hud) [self removeProgressHUD:hud];
8109 [essential_ removeAllObjects];
8110 [broken_ removeAllObjects];
8112 NSArray *packages([database_ packages]);
8113 for (Package *package in packages) {
8115 [broken_ addObject:package];
8116 if ([package upgradableAndEssential:NO]) {
8117 if ([package essential])
8118 [essential_ addObject:package];
8123 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8125 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8126 [changesItem setBadgeValue:badge];
8127 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8129 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8130 [self setApplicationBadge:badge];
8132 [self setApplicationBadgeString:badge];
8134 [changesItem setBadgeValue:nil];
8135 [changesItem setAnimatedBadge:NO];
8137 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8138 [self removeApplicationBadge];
8139 else // XXX: maybe use setApplicationBadgeString also?
8140 [self setApplicationIconBadgeNumber:0];
8145 [self refreshIfPossible];
8148 - (void) updateData {
8149 [database_ setVisible];
8158 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8159 _assert(file != NULL);
8161 for (NSString *key in [Sources_ allKeys]) {
8162 NSDictionary *source([Sources_ objectForKey:key]);
8164 fprintf(file, "%s %s %s\n",
8165 [[source objectForKey:@"Type"] UTF8String],
8166 [[source objectForKey:@"URI"] UTF8String],
8167 [[source objectForKey:@"Distribution"] UTF8String]
8175 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8176 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8177 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8178 [container_ presentModalViewController:navigation animated:YES];
8181 detachNewThreadSelector:@selector(update_)
8184 title:UCLocalize("UPDATING_SOURCES")
8188 - (void) reloadData {
8189 @synchronized (self) {
8195 pkgProblemResolver *resolver = [database_ resolver];
8197 resolver->InstallProtect();
8198 if (!resolver->Resolve(true))
8202 - (CGRect) popUpBounds {
8203 return [[tabbar_ view] bounds];
8207 if (![database_ prepare])
8210 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8211 [page setDelegate:self];
8212 CYNavigationController *confirm_ = [[CYNavigationController alloc] initWithRootViewController:page];
8213 [confirm_ setDelegate:self];
8215 if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8216 [container_ presentModalViewController:confirm_ animated:YES];
8222 @synchronized (self) {
8227 - (void) clearPackage:(Package *)package {
8228 @synchronized (self) {
8235 - (void) installPackages:(NSArray *)packages {
8236 @synchronized (self) {
8237 for (Package *package in packages)
8244 - (void) installPackage:(Package *)package {
8245 @synchronized (self) {
8252 - (void) removePackage:(Package *)package {
8253 @synchronized (self) {
8260 - (void) distUpgrade {
8261 @synchronized (self) {
8262 if (![database_ upgrade])
8269 @synchronized (self) {
8274 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8275 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8277 if (navigation != nil) {
8278 [navigation pushViewController:progress animated:YES];
8280 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8281 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8282 [container_ presentModalViewController:navigation animated:YES];
8286 detachNewThreadSelector:@selector(perform)
8289 title:UCLocalize("RUNNING")
8293 - (void) progressControllerIsComplete:(ProgressController *)progress {
8297 - (void) setPage:(CYViewController *)page {
8298 [page setDelegate:self];
8300 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8301 [navController setViewControllers:[NSArray arrayWithObject:page]];
8302 for (CYNavigationController *page in [tabbar_ viewControllers]) {
8303 if (page != navController) [page setViewControllers:nil];
8307 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8308 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8309 [browser loadURL:url];
8313 - (SectionsController *) sectionsController {
8314 if (sections_ == nil)
8315 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8319 - (ChangesController *) changesController {
8320 if (changes_ == nil)
8321 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8325 - (ManageController *) manageController {
8326 if (manage_ == nil) {
8327 manage_ = (ManageController *) [[self
8328 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8329 withClass:[ManageController class]
8331 if (!IsWildcat_) queueDelegate_ = manage_;
8336 - (SearchController *) searchController {
8338 search_ = [[SearchController alloc] initWithDatabase:database_];
8342 - (SourceTable *) sourcesController {
8343 if (sources_ == nil)
8344 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8348 - (InstalledController *) installedController {
8349 if (installed_ == nil) {
8350 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8351 if (IsWildcat_) queueDelegate_ = installed_;
8356 - (void) tabBarController:(id)tabBarController didSelectViewController:(UIViewController *)viewController {
8357 int tag = [[viewController tabBarItem] tag];
8359 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8361 } else if (tag_ == 1) {
8362 [[self sectionsController] resetView];
8366 case kCydiaTag: _setHomePage(self); break;
8368 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8369 case kChangesTag: [self setPage:[self changesController]]; break;
8370 case kManageTag: [self setPage:[self manageController]]; break;
8371 case kInstalledTag: [self setPage:[self installedController]]; break;
8372 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8373 case kSearchTag: [self setPage:[self searchController]]; break;
8381 - (void) showSettings {
8382 RoleController *role = [[RoleController alloc] initWithDatabase:database_ delegate:self];
8383 CYNavigationController *nav = [[CYNavigationController alloc] initWithRootViewController:role];
8384 if (IsWildcat_) [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8385 [container_ presentModalViewController:nav animated:YES];
8388 - (void) setPackageController:(PackageController *)view {
8390 [view setPackage:nil];
8394 - (PackageController *) _packageController {
8395 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8398 - (PackageController *) packageController {
8399 return [self _packageController];
8402 // Returns the navigation controller for the queuing badge.
8403 - (id) queueBadgeController {
8404 int index = [self indexOfTabWithTag:kManageTag];
8405 if (index == -1) index = [self indexOfTabWithTag:kInstalledTag];
8407 return [[tabbar_ viewControllers] objectAtIndex:index];
8410 - (void) cancelAndClear:(bool)clear {
8411 @synchronized (self) {
8414 pkgCacheFile &cache([database_ cache]);
8415 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
8416 // Unmark method taken from Synaptic Package Manager.
8417 // Thanks for being sane, unlike Aptitude.
8418 if (!cache[iterator].Keep()) {
8419 cache->MarkKeep(iterator, false);
8420 cache->SetReInstall(iterator, false);
8426 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
8430 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8433 // Show the changes in the current view.
8434 [(CYNavigationController *) [tabbar_ selectedViewController] reloadData];
8435 [queueDelegate_ queueStatusDidChange];
8439 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8440 NSString *context([alert context]);
8442 if ([context isEqualToString:@"fixhalf"]) {
8443 if (button == [alert firstOtherButtonIndex]) {
8444 @synchronized (self) {
8445 for (Package *broken in broken_) {
8448 NSString *id = [broken id];
8449 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8450 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8451 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8452 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8458 } else if (button == [alert cancelButtonIndex]) {
8459 [broken_ removeAllObjects];
8463 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8464 } else if ([context isEqualToString:@"upgrade"]) {
8465 if (button == [alert firstOtherButtonIndex]) {
8466 @synchronized (self) {
8467 for (Package *essential in essential_)
8468 [essential install];
8473 } else if (button == [alert firstOtherButtonIndex] + 1) {
8475 } else if (button == [alert cancelButtonIndex]) {
8479 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8483 - (void) system:(NSString *)command { _pooled
8484 system([command UTF8String]);
8487 - (void) applicationWillSuspend {
8489 [super applicationWillSuspend];
8492 - (void) applicationSuspend:(__GSEvent *)event {
8493 // Use external process status API internally.
8494 // This is probably a really bad idea.
8495 uint64_t status = 0;
8497 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8498 notify_get_state(notify_token, &status);
8499 notify_cancel(notify_token);
8502 if (hud_ == nil && status == 0)
8503 [super applicationSuspend:event];
8506 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8508 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8511 - (void) _setSuspended:(BOOL)value {
8513 [super _setSuspended:value];
8516 - (UIProgressHUD *) addProgressHUD {
8517 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8518 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8520 [window_ setUserInteractionEnabled:NO];
8523 UIViewController *target = container_;
8524 while ([target modalViewController] != nil) target = [target modalViewController];
8525 [[target view] addSubview:hud];
8530 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8532 [hud removeFromSuperview];
8533 [window_ setUserInteractionEnabled:YES];
8536 - (CYViewController *) pageForPackage:(NSString *)name {
8537 if (Package *package = [database_ packageWithName:name]) {
8538 PackageController *view([self packageController]);
8539 [view setPackage:package];
8542 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8543 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8544 return [self _pageForURL:url withClass:[CYBrowserController class]];
8548 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8552 NSString *href([url absoluteString]);
8553 if ([href hasPrefix:@"apptapp://package/"])
8554 return [self pageForPackage:[href substringFromIndex:18]];
8556 NSString *scheme([[url scheme] lowercaseString]);
8557 if (![scheme isEqualToString:@"cydia"])
8559 NSString *path([url absoluteString]);
8560 if ([path length] < 8)
8562 path = [path substringFromIndex:8];
8563 if (![path hasPrefix:@"/"])
8564 path = [@"/" stringByAppendingString:path];
8566 if ([path isEqualToString:@"/add-source"])
8567 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8568 else if ([path isEqualToString:@"/storage"])
8569 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8570 else if ([path isEqualToString:@"/sources"])
8571 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8572 else if ([path isEqualToString:@"/packages"])
8573 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8574 else if ([path hasPrefix:@"/url/"])
8575 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8576 else if ([path hasPrefix:@"/launch/"])
8577 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8578 else if ([path hasPrefix:@"/package-settings/"])
8579 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8580 else if ([path hasPrefix:@"/package-signature/"])
8581 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8582 else if ([path hasPrefix:@"/package/"])
8583 return [self pageForPackage:[path substringFromIndex:9]];
8584 else if ([path hasPrefix:@"/files/"]) {
8585 NSString *name = [path substringFromIndex:7];
8587 if (Package *package = [database_ packageWithName:name]) {
8588 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8589 [files setPackage:package];
8597 - (void) applicationOpenURL:(NSURL *)url {
8598 [super applicationOpenURL:url];
8600 if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
8601 [self setPage:page];
8603 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8607 - (void) applicationWillResignActive:(UIApplication *)application {
8608 // Stop refreshing if you get a phone call or lock the device.
8609 if ([container_ updating]) [container_ cancelUpdate];
8611 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8612 [super applicationWillResignActive:application];
8615 - (void) addStashController {
8616 stash_ = [[CYStashController alloc] init];
8617 [window_ addSubview:[stash_ view]];
8620 - (void) removeStashController {
8621 [[stash_ view] removeFromSuperview];
8626 [self setIdleTimerDisabled:YES];
8628 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8629 [self setStatusBarShowsProgress:YES];
8630 UpdateExternalStatus(1);
8632 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8634 UpdateExternalStatus(0);
8635 [self setStatusBarShowsProgress:NO];
8637 [self removeStashController];
8639 if (ExecFork() == 0) {
8640 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8641 perror("launchctl stop");
8645 - (void) setupTabBarController {
8646 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8647 [tabbar_ setDelegate:self];
8649 NSMutableArray *items([NSMutableArray arrayWithObjects:
8650 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8651 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8652 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8653 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8657 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8658 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8660 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8663 NSMutableArray *controllers([NSMutableArray array]);
8665 for (UITabBarItem *item in items) {
8666 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8667 [controller setTabBarItem:item];
8668 [controllers addObject:controller];
8671 [tabbar_ setViewControllers:controllers];
8674 - (void) applicationDidFinishLaunching:(id)unused {
8675 [CYBrowserController _initialize];
8677 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8679 Font12_ = [[UIFont systemFontOfSize:12] retain];
8680 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8681 Font14_ = [[UIFont systemFontOfSize:14] retain];
8682 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8683 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8687 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8688 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8690 UIScreen *screen([UIScreen mainScreen]);
8692 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8693 [window_ orderFront:self];
8694 [window_ makeKey:self];
8695 [window_ setHidden:NO];
8698 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8699 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8700 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8701 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8702 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8703 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8704 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8705 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8706 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8709 [self addStashController];
8710 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8714 database_ = [Database sharedInstance];
8716 [self setupTabBarController];
8718 container_ = [[CYContainer alloc] initWithDatabase:database_];
8719 [container_ setUpdateDelegate:self];
8720 [container_ setTabBarController:tabbar_];
8721 [window_ addSubview:[container_ view]];
8723 // Show pinstripes while loading data.
8724 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8726 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8733 [self showSettings];
8737 [window_ setUserInteractionEnabled:NO];
8739 UIView *container = [[UIView alloc] init];
8740 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8742 UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
8743 [spinner startAnimating];
8744 [container addSubview:spinner];
8747 UILabel *label = [[UILabel alloc] init];
8748 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8749 [label setBackgroundColor:[UIColor clearColor]];
8750 [label setTextColor:[UIColor blackColor]];
8751 [label setShadowColor:[UIColor whiteColor]];
8752 [label setShadowOffset:CGSizeMake(0, 1)];
8753 [label setText:UCLocalize("LOADING_DATA")];
8754 [container addSubview:label];
8757 CGSize viewsize = [[tabbar_ view] frame].size;
8758 CGSize spinnersize = [spinner bounds].size;
8759 CGSize textsize = [[label text] sizeWithFont:[label font]];
8760 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8762 CGRect containrect = {
8763 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8764 CGSizeMake(bothwidth, spinnersize.height)
8767 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8775 [container setFrame:containrect];
8776 [spinner setFrame:spinrect];
8777 [label setFrame:textrect];
8778 [[container_ view] addSubview:container];
8779 [container release];
8784 // Show the home page
8785 [tabbar_ setSelectedIndex:0];
8787 [window_ setUserInteractionEnabled:YES];
8789 // XXX: does this actually slow anything down?
8790 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8791 [container removeFromSuperview];
8794 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8795 if (item != nil && IsWildcat_) {
8796 [sheet showFromBarButtonItem:item animated:YES];
8798 [sheet showInView:window_];
8805 id Alloc_(id self, SEL selector) {
8806 id object = alloc_(self, selector);
8807 lprintf("[%s]A-%p\n", self->isa->name, object);
8812 id Dealloc_(id self, SEL selector) {
8813 id object = dealloc_(self, selector);
8814 lprintf("[%s]D-%p\n", self->isa->name, object);
8818 Class $WebDefaultUIKitDelegate;
8820 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8821 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8822 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8823 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8826 static NSNumber *shouldPlayKeyboardSounds;
8830 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8832 case 1104: // Keyboard Button Clicked
8833 case 1105: // Keyboard Delete Repeated
8834 if (shouldPlayKeyboardSounds == nil) {
8835 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8836 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8839 if (![shouldPlayKeyboardSounds boolValue])
8843 _UIHardware$_playSystemSound$(self, _cmd, sound);
8847 int main(int argc, char *argv[]) { _pooled
8850 if (Class $UIDevice = objc_getClass("UIDevice")) {
8851 UIDevice *device([$UIDevice currentDevice]);
8852 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8856 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8858 /* Library Hacks {{{ */
8859 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8861 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8862 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8863 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8864 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8865 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8868 $UIHardware = objc_getClass("UIHardware");
8869 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8870 if (UIHardware$_playSystemSound$ != NULL) {
8871 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8872 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8875 /* Set Locale {{{ */
8876 Locale_ = CFLocaleCopyCurrent();
8877 Languages_ = [NSLocale preferredLanguages];
8878 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8879 //NSLog(@"%@", [Languages_ description]);
8882 if (Languages_ == nil || [Languages_ count] == 0)
8883 // XXX: consider just setting to C and then falling through?
8886 lang = [[Languages_ objectAtIndex:0] UTF8String];
8887 setenv("LANG", lang, true);
8890 //std::setlocale(LC_ALL, lang);
8891 NSLog(@"Setting Language: %s", lang);
8894 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8896 /* Parse Arguments {{{ */
8897 bool substrate(false);
8903 for (int argi(1); argi != argc; ++argi)
8904 if (strcmp(argv[argi], "--") == 0) {
8906 argv[argi] = argv[0];
8912 for (int argi(1); argi != arge; ++argi)
8913 if (strcmp(args[argi], "--substrate") == 0)
8916 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8920 App_ = [[NSBundle mainBundle] bundlePath];
8921 Home_ = NSHomeDirectory();
8927 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8928 alloc_ = alloc->method_imp;
8929 alloc->method_imp = (IMP) &Alloc_;*/
8931 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8932 dealloc_ = dealloc->method_imp;
8933 dealloc->method_imp = (IMP) &Dealloc_;*/
8935 /* System Information {{{ */
8939 size = sizeof(maxproc);
8940 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8941 perror("sysctlbyname(\"kern.maxproc\", ?)");
8942 else if (maxproc < 64) {
8944 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8945 perror("sysctlbyname(\"kern.maxproc\", #)");
8948 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8949 char *osversion = new char[size];
8950 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8951 perror("sysctlbyname(\"kern.osversion\", ?)");
8953 System_ = [NSString stringWithUTF8String:osversion];
8955 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8956 char *machine = new char[size];
8957 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8958 perror("sysctlbyname(\"hw.machine\", ?)");
8962 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8963 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8964 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8965 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8969 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8970 NSData *data((NSData *) ecid);
8971 size_t length([data length]);
8972 uint8_t bytes[length];
8973 [data getBytes:bytes];
8974 char string[length * 2 + 1];
8975 for (size_t i(0); i != length; ++i)
8976 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8977 ChipID_ = [NSString stringWithUTF8String:string];
8981 IOObjectRelease(service);
8985 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8987 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
8988 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
8989 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
8991 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
8992 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
8993 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
8995 if (mcc != NULL && mnc != NULL)
8996 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9003 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9004 Build_ = [system objectForKey:@"ProductBuildVersion"];
9005 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9006 Product_ = [info objectForKey:@"SafariProductVersion"];
9007 Safari_ = [info objectForKey:@"CFBundleVersion"];
9010 /* Load Database {{{ */
9012 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9014 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9016 if (Metadata_ == NULL)
9017 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9019 Settings_ = [Metadata_ objectForKey:@"Settings"];
9021 Packages_ = [Metadata_ objectForKey:@"Packages"];
9022 Sections_ = [Metadata_ objectForKey:@"Sections"];
9023 Sources_ = [Metadata_ objectForKey:@"Sources"];
9025 Token_ = [Metadata_ objectForKey:@"Token"];
9028 if (Settings_ != nil)
9029 Role_ = [Settings_ objectForKey:@"Role"];
9031 if (Packages_ == nil) {
9032 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
9033 [Metadata_ setObject:Packages_ forKey:@"Packages"];
9036 if (Sections_ == nil) {
9037 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9038 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9041 if (Sources_ == nil) {
9042 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9043 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9047 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9049 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9050 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9051 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9052 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9053 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9054 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9056 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9058 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9059 unlink("/tmp/.cydia.fw");
9061 } else if (access("/User", F_OK) != 0 || version < 2) {
9064 system("/usr/libexec/cydia/firmware.sh");
9068 _assert([[NSFileManager defaultManager]
9069 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9070 withIntermediateDirectories:YES
9075 if (access("/tmp/cydia.chk", F_OK) == 0) {
9076 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9077 _assert(errno == ENOENT);
9078 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9079 _assert(errno == ENOENT);
9082 /* APT Initialization {{{ */
9083 _assert(pkgInitConfig(*_config));
9084 _assert(pkgInitSystem(*_config, _system));
9087 _config->Set("APT::Acquire::Translation", lang);
9089 // XXX: this timeout might be important :(
9090 //_config->Set("Acquire::http::Timeout", 15);
9092 _config->Set("Acquire::http::MaxParallel", 3);
9094 /* Color Choices {{{ */
9095 space_ = CGColorSpaceCreateDeviceRGB();
9097 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9098 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9099 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9100 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9101 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9102 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9103 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9104 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9105 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9107 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9108 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9110 /* UIKit Configuration {{{ */
9111 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9112 if ($GSFontSetUseLegacyFontMetrics != NULL)
9113 $GSFontSetUseLegacyFontMetrics(YES);
9115 // XXX: I have a feeling this was important
9116 //UIKeyboardDisableAutomaticAppearance();
9119 Colon_ = UCLocalize("COLON_DELIMITED");
9120 Error_ = UCLocalize("ERROR");
9121 Warning_ = UCLocalize("WARNING");
9124 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9126 CGColorSpaceRelease(space_);