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_)])
3343 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3344 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3345 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3346 // XXX: this could be more intelligent
3347 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3348 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3350 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3357 /*std::vector<Package *> packages;
3358 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3359 [packages_ release];
3364 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3365 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3366 //packages.push_back(package);
3367 CFArrayAppendValue(packages_, [package retain]);
3371 /*if (packages.empty())
3372 packages_ = [[NSArray alloc] init];
3374 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3377 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3378 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3379 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3387 /*if (!packages.empty())
3388 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3389 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3391 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3393 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3395 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3402 - (void) configure {
3403 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3404 system([dpkg UTF8String]);
3408 // XXX: I don't remember this condition
3413 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3415 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3417 if ([self popErrorWithTitle:title])
3421 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3424 public pkgArchiveCleaner
3427 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3432 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3439 fetcher_->Shutdown();
3441 pkgRecords records(cache_);
3443 lock_ = new FileFd();
3444 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3446 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3448 if ([self popErrorWithTitle:title])
3452 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3455 manager_ = (_system->CreatePM(cache_));
3456 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3463 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3465 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3467 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3469 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3470 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3473 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3478 bool failed = false;
3479 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3480 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3482 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3485 std::string uri = (*item)->DescURI();
3486 std::string error = (*item)->ErrorText;
3488 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3491 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3492 withObject:[NSArray arrayWithObjects:
3493 [NSString stringWithUTF8String:error.c_str()],
3505 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3507 if (_error->PendingError()) {
3512 if (result == pkgPackageManager::Failed) {
3517 if (result != pkgPackageManager::Completed) {
3522 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3524 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3526 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3527 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3530 if (![before isEqualToArray:after])
3535 NSString *title(UCLocalize("UPGRADE"));
3536 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3542 [self updateWithStatus:status_];
3545 - (void) setVisible {
3546 for (Package *package in [self packages])
3547 [package setVisible];
3550 - (void) updateWithStatus:(Status &)status {
3551 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3552 NSString *title(UCLocalize("REFRESHING_DATA"));
3555 if (!list.ReadMainList())
3556 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3559 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3560 if ([self popErrorWithTitle:title])
3563 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3564 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3565 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3567 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3571 - (void) setDelegate:(id)delegate {
3572 delegate_ = delegate;
3573 status_.setDelegate(delegate);
3574 progress_.setDelegate(delegate);
3577 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3578 SourceMap::const_iterator i(sources_.find(file->ID));
3579 return i == sources_.end() ? nil : i->second;
3585 /* Confirmation Controller {{{ */
3586 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3587 if (!iterator.end())
3588 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3589 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3591 pkgCache::PkgIterator package(dep.TargetPkg());
3594 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3602 /* Web Scripting {{{ */
3603 @interface CydiaObject : NSObject {
3608 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3611 @implementation CydiaObject
3614 [indirect_ release];
3618 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3619 if ((self = [super init]) != nil) {
3620 indirect_ = [indirect retain];
3624 - (void) setDelegate:(id)delegate {
3625 delegate_ = delegate;
3628 + (NSArray *) _attributeKeys {
3629 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3632 - (NSArray *) attributeKeys {
3633 return [[self class] _attributeKeys];
3636 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3637 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3640 - (NSString *) device {
3641 return [[UIDevice currentDevice] uniqueIdentifier];
3644 #if 0 // XXX: implement!
3645 - (NSString *) mac {
3646 if (![indirect_ promptForSensitive:@"Mac Address"])
3650 - (NSString *) serial {
3651 if (![indirect_ promptForSensitive:@"Serial #"])
3655 - (NSString *) firewire {
3656 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3660 - (NSString *) imei {
3661 if (![indirect_ promptForSensitive:@"IMEI"])
3666 + (NSString *) webScriptNameForSelector:(SEL)selector {
3667 if (selector == @selector(close))
3669 else if (selector == @selector(getInstalledPackages))
3670 return @"getInstalledPackages";
3671 else if (selector == @selector(getPackageById:))
3672 return @"getPackageById";
3673 else if (selector == @selector(installPackages:))
3674 return @"installPackages";
3675 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3676 return @"setButtonImage";
3677 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3678 return @"setButtonTitle";
3679 else if (selector == @selector(setPopupHook:))
3680 return @"setPopupHook";
3681 else if (selector == @selector(setSpecial:))
3682 return @"setSpecial";
3683 else if (selector == @selector(setToken:))
3685 else if (selector == @selector(setViewportWidth:))
3686 return @"setViewportWidth";
3687 else if (selector == @selector(supports:))
3689 else if (selector == @selector(stringWithFormat:arguments:))
3691 else if (selector == @selector(localizedStringForKey:value:table:))
3693 else if (selector == @selector(du:))
3695 else if (selector == @selector(statfs:))
3701 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3702 return [self webScriptNameForSelector:selector] == nil;
3705 - (BOOL) supports:(NSString *)feature {
3706 return [feature isEqualToString:@"window.open"];
3709 - (NSArray *) getInstalledPackages {
3710 NSArray *packages([[Database sharedInstance] packages]);
3711 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3712 for (Package *package in packages)
3713 if ([package installed] != nil)
3714 [installed addObject:package];
3718 - (Package *) getPackageById:(NSString *)id {
3719 Package *package([[Database sharedInstance] packageWithName:id]);
3724 - (NSArray *) statfs:(NSString *)path {
3727 if (path == nil || statfs([path UTF8String], &stat) == -1)
3730 return [NSArray arrayWithObjects:
3731 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3732 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3733 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3737 - (NSNumber *) du:(NSString *)path {
3738 NSNumber *value(nil);
3741 _assert(pipe(fds) != -1);
3743 pid_t pid(ExecFork());
3745 _assert(dup2(fds[1], 1) != -1);
3746 _assert(close(fds[0]) != -1);
3747 _assert(close(fds[1]) != -1);
3748 /* XXX: this should probably not use du */
3749 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3754 _assert(close(fds[1]) != -1);
3756 if (FILE *du = fdopen(fds[0], "r")) {
3758 while (fgets(line, sizeof(line), du) != NULL) {
3759 size_t length(strlen(line));
3760 while (length != 0 && line[length - 1] == '\n')
3761 line[--length] = '\0';
3762 if (char *tab = strchr(line, '\t')) {
3764 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3769 } else _assert(close(fds[0]));
3773 if (waitpid(pid, &status, 0) == -1)
3776 else _assert(false);
3785 - (void) installPackages:(NSArray *)packages {
3786 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3789 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3790 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3793 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3794 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3797 - (void) setSpecial:(id)function {
3798 [indirect_ setSpecial:function];
3801 - (void) setToken:(NSString *)token {
3804 Token_ = [token retain];
3806 [Metadata_ setObject:Token_ forKey:@"Token"];
3810 - (void) setPopupHook:(id)function {
3811 [indirect_ setPopupHook:function];
3814 - (void) setViewportWidth:(float)width {
3815 [indirect_ setViewportWidth:width];
3818 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3819 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3820 unsigned count([arguments count]);
3822 for (unsigned i(0); i != count; ++i)
3823 values[i] = [arguments objectAtIndex:i];
3824 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3827 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3828 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3830 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3832 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3838 /* Cydia Browser Controller {{{ */
3839 @interface CYBrowserController : BrowserController {
3840 CydiaObject *cydia_;
3845 @implementation CYBrowserController
3852 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3855 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3856 [super webView:view didClearWindowObject:window forFrame:frame];
3858 WebDataSource *source([frame dataSource]);
3859 NSURLResponse *response([source response]);
3860 NSURL *url([response URL]);
3861 NSString *scheme([url scheme]);
3863 NSHTTPURLResponse *http;
3864 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3865 http = (NSHTTPURLResponse *) response;
3869 NSDictionary *headers([http allHeaderFields]);
3870 NSString *host([url host]);
3871 [self setHeaders:headers forHost:host];
3874 [host isEqualToString:@"cydia.saurik.com"] ||
3875 [host hasSuffix:@".cydia.saurik.com"] ||
3876 [scheme isEqualToString:@"file"]
3878 [window setValue:cydia_ forKey:@"cydia"];
3881 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3882 if (System_ != NULL)
3883 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3884 if (Machine_ != NULL)
3885 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3887 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3889 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3892 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3893 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3894 [self _setMoreHeaders:copy];
3898 - (void) setDelegate:(id)delegate {
3899 [super setDelegate:delegate];
3900 [cydia_ setDelegate:delegate];
3904 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3905 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3907 WebView *webview([[webview_ _documentView] webView]);
3909 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3911 NSString *application = package == nil ? @"Cydia" : [NSString
3912 stringWithFormat:@"Cydia/%@",
3917 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3919 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3920 if (Product_ != nil)
3921 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3923 [webview setApplicationNameForUserAgent:application];
3930 /* Confirmation {{{ */
3931 @protocol ConfirmationControllerDelegate
3932 - (void) cancelAndClear:(bool)clear;
3933 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3937 @interface ConfirmationController : CYBrowserController {
3938 _transient Database *database_;
3939 UIAlertView *essential_;
3946 - (id) initWithDatabase:(Database *)database;
3950 @implementation ConfirmationController
3957 if (essential_ != nil)
3958 [essential_ release];
3962 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3963 NSString *context([alert context]);
3965 if ([context isEqualToString:@"remove"]) {
3966 if (button == [alert cancelButtonIndex]) {
3967 [self dismissModalViewControllerAnimated:YES];
3968 } else if (button == [alert firstOtherButtonIndex]) {
3971 [delegate_ confirmWithNavigationController:[self navigationController]];
3974 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3975 } else if ([context isEqualToString:@"unable"]) {
3976 [self dismissModalViewControllerAnimated:YES];
3977 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3979 [super alertView:alert clickedButtonAtIndex:button];
3983 - (void) _doContinue {
3984 [self dismissModalViewControllerAnimated:YES];
3985 [delegate_ cancelAndClear:NO];
3988 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
3989 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
3993 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3994 [super webView:view didClearWindowObject:window forFrame:frame];
3995 [window setValue:changes_ forKey:@"changes"];
3996 [window setValue:issues_ forKey:@"issues"];
3997 [window setValue:sizes_ forKey:@"sizes"];
3998 [window setValue:self forKey:@"queue"];
4001 - (id) initWithDatabase:(Database *)database {
4002 if ((self = [super init]) != nil) {
4003 database_ = database;
4005 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4007 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4008 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4009 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4010 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4011 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4015 pkgDepCache::Policy *policy([database_ policy]);
4017 pkgCacheFile &cache([database_ cache]);
4018 NSArray *packages = [database_ packages];
4019 for (Package *package in packages) {
4020 pkgCache::PkgIterator iterator = [package iterator];
4021 pkgDepCache::StateCache &state(cache[iterator]);
4023 NSString *name([package name]);
4025 if (state.NewInstall())
4026 [installing addObject:name];
4027 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4028 [reinstalling addObject:name];
4029 else if (state.Upgrade())
4030 [upgrading addObject:name];
4031 else if (state.Downgrade())
4032 [downgrading addObject:name];
4033 else if (state.Delete()) {
4034 if ([package essential])
4036 [removing addObject:name];
4039 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4040 substrate_ |= DepSubstrate(iterator.CurrentVer());
4045 else if (Advanced_) {
4046 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4048 essential_ = [[UIAlertView alloc]
4049 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4050 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4052 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4053 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4056 [essential_ setContext:@"remove"];
4058 essential_ = [[UIAlertView alloc]
4059 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4060 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4062 cancelButtonTitle:UCLocalize("OKAY")
4063 otherButtonTitles:nil
4066 [essential_ setContext:@"unable"];
4069 changes_ = [[NSArray alloc] initWithObjects:
4077 issues_ = [database_ issues];
4079 issues_ = [issues_ retain];
4081 sizes_ = [[NSArray alloc] initWithObjects:
4082 SizeString([database_ fetcher].FetchNeeded()),
4083 SizeString([database_ fetcher].PartialPresent()),
4086 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4088 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
4089 initWithTitle:UCLocalize("CANCEL")
4090 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4091 style:UIBarButtonItemStylePlain
4093 action:@selector(cancelButtonClicked)
4095 [[self navigationItem] setLeftBarButtonItem:leftItem];
4100 - (void) applyRightButton {
4101 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
4102 initWithTitle:UCLocalize("CONFIRM")
4103 style:UIBarButtonItemStylePlain
4105 action:@selector(confirmButtonClicked)
4107 #if !AlwaysReload && !IgnoreInstall
4108 if (issues_ == nil && ![self isLoading]) [[self navigationItem] setRightBarButtonItem:rightItem];
4109 else [super applyRightButton];
4111 [[self navigationItem] setRightBarButtonItem:nil];
4113 [rightItem release];
4116 - (void) cancelButtonClicked {
4117 [self dismissModalViewControllerAnimated:YES];
4118 [delegate_ cancelAndClear:YES];
4122 - (void) confirmButtonClicked {
4126 if (essential_ != nil)
4131 [delegate_ confirmWithNavigationController:[self navigationController]];
4139 /* Progress Data {{{ */
4140 @interface ProgressData : NSObject {
4146 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4153 @implementation ProgressData
4155 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4156 if ((self = [super init]) != nil) {
4157 selector_ = selector;
4177 /* Progress Controller {{{ */
4178 @interface ProgressController : CYViewController <
4179 ConfigurationDelegate,
4182 _transient Database *database_;
4183 UIProgressBar *progress_;
4184 UITextView *output_;
4185 UITextLabel *status_;
4186 UIPushButton *close_;
4188 SHA1SumValue springlist_;
4189 SHA1SumValue notifyconf_;
4193 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4195 - (void) _retachThread;
4196 - (void) _detachNewThreadData:(ProgressData *)data;
4197 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4203 @protocol ProgressControllerDelegate
4204 - (void) progressControllerIsComplete:(ProgressController *)sender;
4207 @implementation ProgressController
4210 [database_ setDelegate:nil];
4211 [progress_ release];
4220 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4221 if ((self = [super init]) != nil) {
4222 database_ = database;
4223 [database_ setDelegate:self];
4224 delegate_ = delegate;
4226 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4228 progress_ = [[UIProgressBar alloc] init];
4229 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4230 [progress_ setStyle:0];
4232 status_ = [[UITextLabel alloc] init];
4233 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4234 [status_ setColor:[UIColor whiteColor]];
4235 [status_ setBackgroundColor:[UIColor clearColor]];
4236 [status_ setCentersHorizontally:YES];
4237 //[status_ setFont:font];
4239 output_ = [[UITextView alloc] init];
4241 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4242 //[output_ setTextFont:@"Courier New"];
4243 [output_ setFont:[[output_ font] fontWithSize:12]];
4244 [output_ setTextColor:[UIColor whiteColor]];
4245 [output_ setBackgroundColor:[UIColor clearColor]];
4246 [output_ setMarginTop:0];
4247 [output_ setAllowsRubberBanding:YES];
4248 [output_ setEditable:NO];
4249 [[self view] addSubview:output_];
4251 close_ = [[UIPushButton alloc] init];
4252 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4253 [close_ setAutosizesToFit:NO];
4254 [close_ setDrawsShadow:YES];
4255 [close_ setStretchBackground:YES];
4256 [close_ setEnabled:YES];
4257 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4258 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4259 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4260 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4264 - (void) positionViews {
4265 CGRect bounds = [[self view] bounds];
4266 CGSize prgsize = [UIProgressBar defaultSize];
4269 (bounds.size.width - prgsize.width) / 2,
4270 bounds.size.height - prgsize.height - 20
4273 float closewidth = bounds.size.width - 20;
4274 if (closewidth > 300) closewidth = 300;
4276 [progress_ setFrame:prgrect];
4277 [status_ setFrame:CGRectMake(
4279 bounds.size.height - prgsize.height - 50,
4280 bounds.size.width - 20,
4283 [output_ setFrame:CGRectMake(
4286 bounds.size.width - 20,
4287 bounds.size.height - 62
4289 [close_ setFrame:CGRectMake(
4290 (bounds.size.width - closewidth) / 2,
4291 bounds.size.height - prgsize.height - 50,
4297 - (void) viewWillAppear:(BOOL)animated {
4298 [super viewDidAppear:animated];
4299 [[self navigationItem] setHidesBackButton:YES];
4300 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4302 [self positionViews];
4305 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4306 [self positionViews];
4309 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4310 NSString *context([alert context]);
4312 if ([context isEqualToString:@"conffile"]) {
4313 FILE *input = [database_ input];
4314 if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
4315 else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
4320 - (void) closeButtonPushed {
4323 UpdateExternalStatus(0);
4327 [self dismissModalViewControllerAnimated:YES];
4331 [delegate_ terminateWithSuccess];
4332 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4333 [delegate_ suspendWithAnimation:YES];
4335 [delegate_ suspend];*/
4339 system("launchctl stop com.apple.SpringBoard");
4343 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4352 - (void) _retachThread {
4353 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4355 [[self view] addSubview:close_];
4356 [progress_ removeFromSuperview];
4357 [status_ removeFromSuperview];
4359 [database_ popErrorWithTitle:title_];
4360 [delegate_ progressControllerIsComplete:self];
4364 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4367 MMap mmap(file, MMap::ReadOnly);
4369 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4370 if (!(notifyconf_ == sha1.Result()))
4377 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4380 MMap mmap(file, MMap::ReadOnly);
4382 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4383 if (!(springlist_ == sha1.Result()))
4389 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4390 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4391 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4392 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4393 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4396 system("su -c /usr/bin/uicache mobile");
4398 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4400 [delegate_ setStatusBarShowsProgress:NO];
4403 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4404 [[data target] performSelector:[data selector] withObject:[data object]];
4407 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4410 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4411 UpdateExternalStatus(1);
4418 title_ = [title retain];
4420 [[self navigationItem] setTitle:title_];
4422 [status_ setText:nil];
4423 [output_ setText:@""];
4424 [progress_ setProgress:0];
4426 [close_ removeFromSuperview];
4427 [[self view] addSubview:progress_];
4428 [[self view] addSubview:status_];
4430 [delegate_ setStatusBarShowsProgress:YES];
4435 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4438 MMap mmap(file, MMap::ReadOnly);
4440 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4441 notifyconf_ = sha1.Result();
4447 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4450 MMap mmap(file, MMap::ReadOnly);
4452 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4453 springlist_ = sha1.Result();
4458 detachNewThreadSelector:@selector(_detachNewThreadData:)
4460 withObject:[[ProgressData alloc]
4461 initWithSelector:selector
4468 - (void) repairWithSelector:(SEL)selector {
4470 detachNewThreadSelector:selector
4473 title:UCLocalize("REPAIRING")
4477 - (void) setConfigurationData:(NSString *)data {
4479 performSelectorOnMainThread:@selector(_setConfigurationData:)
4485 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4486 CYActionSheet *sheet([[[CYActionSheet alloc]
4488 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4489 defaultButtonIndex:0
4492 [sheet setMessage:error];
4493 [sheet yieldToPopupAlertAnimated:YES];
4497 - (void) setProgressTitle:(NSString *)title {
4499 performSelectorOnMainThread:@selector(_setProgressTitle:)
4505 - (void) setProgressPercent:(float)percent {
4507 performSelectorOnMainThread:@selector(_setProgressPercent:)
4508 withObject:[NSNumber numberWithFloat:percent]
4513 - (void) startProgress {
4516 - (void) addProgressOutput:(NSString *)output {
4518 performSelectorOnMainThread:@selector(_addProgressOutput:)
4524 - (bool) isCancelling:(size_t)received {
4528 - (void) _setConfigurationData:(NSString *)data {
4529 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4531 if (!conffile_r(data)) {
4532 lprintf("E:invalid conffile\n");
4536 NSString *ofile = conffile_r[1];
4537 //NSString *nfile = conffile_r[2];
4539 UIAlertView *alert = [[[UIAlertView alloc]
4540 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4541 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4543 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4544 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4545 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4549 [alert setContext:@"conffile"];
4553 - (void) _setProgressTitle:(NSString *)title {
4554 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4555 for (size_t i(0), e([words count]); i != e; ++i) {
4556 NSString *word([words objectAtIndex:i]);
4557 if (Package *package = [database_ packageWithName:word])
4558 [words replaceObjectAtIndex:i withObject:[package name]];
4561 [status_ setText:[words componentsJoinedByString:@" "]];
4564 - (void) _setProgressPercent:(NSNumber *)percent {
4565 [progress_ setProgress:[percent floatValue]];
4568 - (void) _addProgressOutput:(NSString *)output {
4569 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4570 CGSize size = [output_ contentSize];
4571 CGRect rect = {{0, size.height}, {size.width, 0}};
4572 [output_ scrollRectToVisible:rect animated:YES];
4575 - (BOOL) isRunning {
4582 /* Cell Content View {{{ */
4583 @protocol ContentDelegate
4584 - (void) drawContentRect:(CGRect)rect;
4587 @interface ContentView : UIView {
4588 _transient id<ContentDelegate> delegate_;
4593 @implementation ContentView
4594 - (id) initWithFrame:(CGRect)frame {
4595 if ((self = [super initWithFrame:frame]) != nil) {
4596 /* Fix landscape stretching. */
4597 [self setNeedsDisplayOnBoundsChange:YES];
4601 - (void) setDelegate:(id<ContentDelegate>)delegate {
4602 delegate_ = delegate;
4605 - (void) drawRect:(CGRect)rect {
4606 [super drawRect:rect];
4607 [delegate_ drawContentRect:rect];
4611 /* Package Cell {{{ */
4612 @interface PackageCell : UITableViewCell <
4617 NSString *description_;
4623 ContentView *content_;
4629 - (PackageCell *) init;
4630 - (void) setPackage:(Package *)package;
4632 + (int) heightForPackage:(Package *)package;
4633 - (void) drawContentRect:(CGRect)rect;
4637 @implementation PackageCell
4639 - (void) clearPackage {
4650 if (description_ != nil) {
4651 [description_ release];
4655 if (source_ != nil) {
4660 if (badge_ != nil) {
4665 if (placard_ != nil) {
4675 [self clearPackage];
4682 return faded_ ? [self selectionPercent] : fade_;
4685 - (PackageCell *) init {
4686 CGRect frame(CGRectMake(0, 0, 320, 74));
4687 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4688 UIView *content([self contentView]);
4689 CGRect bounds([content bounds]);
4691 content_ = [[ContentView alloc] initWithFrame:bounds];
4692 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4693 [content addSubview:content_];
4695 [content_ setDelegate:self];
4696 [content_ setOpaque:YES];
4697 if ([self respondsToSelector:@selector(selectionPercent)])
4702 - (void) _setBackgroundColor {
4704 if (NSString *mode = [package_ mode]) {
4705 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4706 color = remove ? RemovingColor_ : InstallingColor_;
4708 color = [UIColor whiteColor];
4710 [content_ setBackgroundColor:color];
4711 [self setNeedsDisplay];
4714 - (void) setPackage:(Package *)package {
4715 [self clearPackage];
4718 Source *source = [package source];
4720 icon_ = [[package icon] retain];
4721 name_ = [[package name] retain];
4724 description_ = [package longDescription];
4725 if (description_ == nil)
4726 description_ = [package shortDescription];
4727 if (description_ != nil)
4728 description_ = [description_ retain];
4730 commercial_ = [package isCommercial];
4732 package_ = [package retain];
4734 NSString *label = nil;
4735 bool trusted = false;
4737 if (source != nil) {
4738 label = [source label];
4739 trusted = [source trusted];
4740 } else if ([[package id] isEqualToString:@"firmware"])
4741 label = UCLocalize("APPLE");
4743 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4745 NSString *from(label);
4747 NSString *section = [package simpleSection];
4748 if (section != nil && ![section isEqualToString:label]) {
4749 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4750 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4753 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4754 source_ = [from retain];
4756 if (NSString *purpose = [package primaryPurpose])
4757 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4758 badge_ = [badge_ retain];
4760 if ([package installed] != nil)
4761 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4762 placard_ = [placard_ retain];
4764 [self _setBackgroundColor];
4765 [content_ setNeedsDisplay];
4768 - (void) drawContentRect:(CGRect)rect {
4769 bool selected([self isSelected]);
4770 float width([self bounds].size.width);
4773 CGContextRef context(UIGraphicsGetCurrentContext());
4774 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4775 CGContextFillRect(context, rect);
4780 rect.size = [icon_ size];
4782 rect.size.width /= 2;
4783 rect.size.height /= 2;
4785 rect.origin.x = 25 - rect.size.width / 2;
4786 rect.origin.y = 25 - rect.size.height / 2;
4788 [icon_ drawInRect:rect];
4791 if (badge_ != nil) {
4792 CGSize size = [badge_ size];
4794 [badge_ drawAtPoint:CGPointMake(
4795 36 - size.width / 2,
4796 36 - size.height / 2
4804 UISetColor(commercial_ ? Purple_ : Black_);
4805 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4806 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4809 UISetColor(commercial_ ? Purplish_ : Gray_);
4810 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4812 if (placard_ != nil)
4813 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4816 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4817 //[self _setBackgroundColor];
4818 [super setSelected:selected animated:fade];
4819 [content_ setNeedsDisplay];
4822 + (int) heightForPackage:(Package *)package {
4828 /* Section Cell {{{ */
4829 @interface SectionCell : UITableViewCell <
4837 ContentView *content_;
4842 - (void) setSection:(Section *)section editing:(BOOL)editing;
4846 @implementation SectionCell
4848 - (void) clearSection {
4849 if (basic_ != nil) {
4854 if (section_ != nil) {
4864 if (count_ != nil) {
4871 [self clearSection];
4879 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4880 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4881 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4882 switch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4883 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4885 UIView *content([self contentView]);
4886 CGRect bounds([content bounds]);
4888 content_ = [[ContentView alloc] initWithFrame:bounds];
4889 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4890 [content addSubview:content_];
4891 [content_ setBackgroundColor:[UIColor whiteColor]];
4893 [content_ setDelegate:self];
4897 - (void) onSwitch:(id)sender {
4898 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4899 if (metadata == nil) {
4900 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4901 [Sections_ setObject:metadata forKey:basic_];
4905 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4908 - (void) setSection:(Section *)section editing:(BOOL)editing {
4909 if (editing != editing_) {
4911 [switch_ removeFromSuperview];
4913 [self addSubview:switch_];
4917 [self clearSection];
4919 if (section == nil) {
4920 name_ = [UCLocalize("ALL_PACKAGES") retain];
4923 basic_ = [section name];
4925 basic_ = [basic_ retain];
4927 section_ = [section localized];
4928 if (section_ != nil)
4929 section_ = [section_ retain];
4931 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4932 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4935 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4938 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4939 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
4941 [content_ setNeedsDisplay];
4944 - (void) setFrame:(CGRect)frame {
4945 [super setFrame:frame];
4947 CGRect rect([switch_ frame]);
4948 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4951 - (void) drawContentRect:(CGRect)rect {
4952 BOOL selected = [self isSelected];
4954 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4962 float width(rect.size.width);
4966 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4968 CGSize size = [count_ sizeWithFont:Font14_];
4972 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4978 /* File Table {{{ */
4979 @interface FileTable : CYViewController <
4980 UITableViewDataSource,
4983 _transient Database *database_;
4986 NSMutableArray *files_;
4990 - (id) initWithDatabase:(Database *)database;
4991 - (void) setPackage:(Package *)package;
4995 @implementation FileTable
4998 if (package_ != nil)
5007 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5008 return files_ == nil ? 0 : [files_ count];
5011 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5015 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5016 static NSString *reuseIdentifier = @"Cell";
5018 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5020 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5021 [cell setFont:[UIFont systemFontOfSize:16]];
5023 [cell setText:[files_ objectAtIndex:indexPath.row]];
5024 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5029 - (id) initWithDatabase:(Database *)database {
5030 if ((self = [super init]) != nil) {
5031 database_ = database;
5033 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5035 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5037 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5038 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5039 [list_ setRowHeight:24.0f];
5040 [[self view] addSubview:list_];
5042 [list_ setDataSource:self];
5043 [list_ setDelegate:self];
5047 - (void) setPackage:(Package *)package {
5048 if (package_ != nil) {
5049 [package_ autorelease];
5058 [files_ removeAllObjects];
5060 if (package != nil) {
5061 package_ = [package retain];
5062 name_ = [[package id] retain];
5064 if (NSArray *files = [package files])
5065 [files_ addObjectsFromArray:files];
5067 if ([files_ count] != 0) {
5068 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5069 [files_ removeObjectAtIndex:0];
5070 [files_ sortUsingSelector:@selector(compareByPath:)];
5072 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5073 [stack addObject:@"/"];
5075 for (int i(0), e([files_ count]); i != e; ++i) {
5076 NSString *file = [files_ objectAtIndex:i];
5077 while (![file hasPrefix:[stack lastObject]])
5078 [stack removeLastObject];
5079 NSString *directory = [stack lastObject];
5080 [stack addObject:[file stringByAppendingString:@"/"]];
5081 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5082 ([stack count] - 2) * 3, "",
5083 [file substringFromIndex:[directory length]]
5092 - (void) reloadData {
5093 [self setPackage:[database_ packageWithName:name_]];
5098 /* Package Controller {{{ */
5099 @interface PackageController : CYBrowserController <
5100 UIActionSheetDelegate
5102 _transient Database *database_;
5106 NSMutableArray *buttons_;
5107 UIBarButtonItem *button_;
5110 - (id) initWithDatabase:(Database *)database;
5111 - (void) setPackage:(Package *)package;
5115 @implementation PackageController
5118 if (package_ != nil)
5132 if ([self retainCount] == 1)
5133 [delegate_ setPackageController:self];
5137 /* XXX: this is not safe at all... localization of /fail/ */
5138 - (void) _clickButtonWithName:(NSString *)name {
5139 if ([name isEqualToString:UCLocalize("CLEAR")])
5140 [delegate_ clearPackage:package_];
5141 else if ([name isEqualToString:UCLocalize("INSTALL")])
5142 [delegate_ installPackage:package_];
5143 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5144 [delegate_ installPackage:package_];
5145 else if ([name isEqualToString:UCLocalize("REMOVE")])
5146 [delegate_ removePackage:package_];
5147 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5148 [delegate_ installPackage:package_];
5149 else _assert(false);
5152 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5153 NSString *context([sheet context]);
5155 if ([context isEqualToString:@"modify"]) {
5156 if (button != [sheet cancelButtonIndex]) {
5157 NSString *buttonName = [buttons_ objectAtIndex:button];
5158 [self _clickButtonWithName:buttonName];
5161 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5165 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5166 [super webView:view didClearWindowObject:window forFrame:frame];
5167 [window setValue:package_ forKey:@"package"];
5170 - (bool) _allowJavaScriptPanel {
5175 - (void) _customButtonClicked {
5176 int count([buttons_ count]);
5181 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5183 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5184 [buttons addObjectsFromArray:buttons_];
5186 UIActionSheet *sheet = [[[UIActionSheet alloc]
5189 cancelButtonTitle:nil
5190 destructiveButtonTitle:nil
5191 otherButtonTitles:nil
5194 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5196 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5197 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5199 [sheet setContext:@"modify"];
5201 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5205 // We don't want to allow non-commercial packages to do custom things to the install button,
5206 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5207 - (void) customButtonClicked {
5209 [super customButtonClicked];
5211 [self _customButtonClicked];
5214 - (void) reloadButtonClicked {
5215 // Don't reload a package view by clicking the button.
5218 - (void) applyLoadingTitle {
5219 // Don't show "Loading" as the title. Ever.
5222 - (UIBarButtonItem *) rightButton {
5227 - (id) initWithDatabase:(Database *)database {
5228 if ((self = [super init]) != nil) {
5229 database_ = database;
5230 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5231 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5235 - (void) setPackage:(Package *)package {
5236 if (package_ != nil) {
5237 [package_ autorelease];
5246 [buttons_ removeAllObjects];
5248 if (package != nil) {
5251 package_ = [package retain];
5252 name_ = [[package id] retain];
5253 commercial_ = [package isCommercial];
5255 if ([package_ mode] != nil)
5256 [buttons_ addObject:UCLocalize("CLEAR")];
5257 if ([package_ source] == nil);
5258 else if ([package_ upgradableAndEssential:NO])
5259 [buttons_ addObject:UCLocalize("UPGRADE")];
5260 else if ([package_ uninstalled])
5261 [buttons_ addObject:UCLocalize("INSTALL")];
5263 [buttons_ addObject:UCLocalize("REINSTALL")];
5264 if (![package_ uninstalled])
5265 [buttons_ addObject:UCLocalize("REMOVE")];
5272 switch ([buttons_ count]) {
5273 case 0: title = nil; break;
5274 case 1: title = [buttons_ objectAtIndex:0]; break;
5275 default: title = UCLocalize("MODIFY"); break;
5278 button_ = [[UIBarButtonItem alloc]
5280 style:UIBarButtonItemStylePlain
5282 action:@selector(customButtonClicked)
5286 - (bool) isLoading {
5287 return commercial_ ? [super isLoading] : false;
5290 - (void) reloadData {
5291 [self setPackage:[database_ packageWithName:name_]];
5296 /* Package Table {{{ */
5297 @interface PackageTable : UIView <
5298 UITableViewDataSource,
5301 _transient Database *database_;
5302 NSMutableArray *packages_;
5303 NSMutableArray *sections_;
5305 NSMutableArray *index_;
5306 NSMutableDictionary *indices_;
5312 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5314 - (void) setDelegate:(id)delegate;
5316 - (void) reloadData;
5317 - (void) resetCursor;
5319 - (UITableView *) list;
5321 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5323 - (void) deselectWithAnimation:(BOOL)animated;
5327 @implementation PackageTable
5330 [packages_ release];
5331 [sections_ release];
5339 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5340 NSInteger count([sections_ count]);
5341 return count == 0 ? 1 : count;
5344 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5345 if ([sections_ count] == 0)
5347 return [[sections_ objectAtIndex:section] name];
5350 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5351 if ([sections_ count] == 0)
5353 return [[sections_ objectAtIndex:section] count];
5356 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5357 Section *section([sections_ objectAtIndex:[path section]]);
5358 NSInteger row([path row]);
5359 Package *package([packages_ objectAtIndex:([section row] + row)]);
5363 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5364 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5366 cell = [[[PackageCell alloc] init] autorelease];
5367 [cell setPackage:[self packageAtIndexPath:path]];
5371 - (void) deselectWithAnimation:(BOOL)animated {
5372 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5375 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5376 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5379 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5380 Package *package([self packageAtIndexPath:path]);
5381 package = [database_ packageWithName:[package id]];
5382 [target_ performSelector:action_ withObject:package];
5386 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5387 return [packages_ count] > 20 ? index_ : nil;
5390 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5394 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5395 if ((self = [super initWithFrame:frame]) != nil) {
5396 database_ = database;
5401 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5402 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5404 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5405 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5407 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5408 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5409 [list_ setRowHeight:73.0f];
5410 [self addSubview:list_];
5412 [list_ setDataSource:self];
5413 [list_ setDelegate:self];
5417 - (void) setDelegate:(id)delegate {
5418 delegate_ = delegate;
5421 - (bool) hasPackage:(Package *)package {
5425 - (void) reloadData {
5426 NSArray *packages = [database_ packages];
5428 [packages_ removeAllObjects];
5429 [sections_ removeAllObjects];
5431 _profile(PackageTable$reloadData$Filter)
5432 for (Package *package in packages)
5433 if ([self hasPackage:package])
5434 [packages_ addObject:package];
5437 [index_ removeAllObjects];
5438 [indices_ removeAllObjects];
5440 Section *section = nil;
5442 _profile(PackageTable$reloadData$Section)
5443 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5447 _profile(PackageTable$reloadData$Section$Package)
5448 package = [packages_ objectAtIndex:offset];
5449 index = [package index];
5452 if (section == nil || [section index] != index) {
5453 _profile(PackageTable$reloadData$Section$Allocate)
5454 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5457 [index_ addObject:[section name]];
5458 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5460 _profile(PackageTable$reloadData$Section$Add)
5461 [sections_ addObject:section];
5465 [section addToCount];
5469 _profile(PackageTable$reloadData$List)
5474 - (void) resetCursor {
5475 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5478 - (UITableView *) list {
5482 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5483 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5488 /* Filtered Package Table {{{ */
5489 @interface FilteredPackageTable : PackageTable {
5495 - (void) setObject:(id)object;
5496 - (void) setObject:(id)object forFilter:(SEL)filter;
5498 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5502 @implementation FilteredPackageTable
5510 - (void) setFilter:(SEL)filter {
5513 /* XXX: this is an unsafe optimization of doomy hell */
5514 Method method(class_getInstanceMethod([Package class], filter));
5515 _assert(method != NULL);
5516 imp_ = method_getImplementation(method);
5517 _assert(imp_ != NULL);
5520 - (void) setObject:(id)object {
5526 object_ = [object retain];
5529 - (void) setObject:(id)object forFilter:(SEL)filter {
5530 [self setFilter:filter];
5531 [self setObject:object];
5534 - (bool) hasPackage:(Package *)package {
5535 _profile(FilteredPackageTable$hasPackage)
5536 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5540 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5541 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5542 [self setFilter:filter];
5543 object_ = [object retain];
5551 /* Filtered Package Controller {{{ */
5552 @interface FilteredPackageController : CYViewController {
5553 _transient Database *database_;
5554 FilteredPackageTable *packages_;
5558 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5562 @implementation FilteredPackageController
5565 [packages_ release];
5571 - (void) viewDidAppear:(BOOL)animated {
5572 [super viewDidAppear:animated];
5573 [packages_ deselectWithAnimation:animated];
5576 - (void) didSelectPackage:(Package *)package {
5577 PackageController *view([delegate_ packageController]);
5578 [view setPackage:package];
5579 [view setDelegate:delegate_];
5580 [[self navigationController] pushViewController:view animated:YES];
5583 - (NSString *) title { return title_; }
5585 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5586 if ((self = [super init]) != nil) {
5587 database_ = database;
5588 title_ = [title copy];
5589 [[self navigationItem] setTitle:title_];
5591 packages_ = [[FilteredPackageTable alloc]
5592 initWithFrame:[[self view] bounds]
5595 action:@selector(didSelectPackage:)
5600 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5601 [[self view] addSubview:packages_];
5605 - (void) reloadData {
5606 [packages_ reloadData];
5609 - (void) setDelegate:(id)delegate {
5610 [super setDelegate:delegate];
5611 [packages_ setDelegate:delegate];
5618 /* Add Source Controller {{{ */
5619 @interface AddSourceController : CYViewController {
5620 _transient Database *database_;
5623 - (id) initWithDatabase:(Database *)database;
5627 @implementation AddSourceController
5629 - (id) initWithDatabase:(Database *)database {
5630 if ((self = [super init]) != nil) {
5631 database_ = database;
5637 /* Source Cell {{{ */
5638 @interface SourceCell : UITableViewCell <
5643 NSString *description_;
5645 ContentView *content_;
5648 - (void) setSource:(Source *)source;
5652 @implementation SourceCell
5654 - (void) clearSource {
5657 [description_ release];
5666 - (void) setSource:(Source *)source {
5670 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5672 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5673 icon_ = [icon_ retain];
5675 origin_ = [[source name] retain];
5676 label_ = [[source uri] retain];
5677 description_ = [[source description] retain];
5679 [content_ setNeedsDisplay];
5688 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5689 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5690 UIView *content([self contentView]);
5691 CGRect bounds([content bounds]);
5693 content_ = [[ContentView alloc] initWithFrame:bounds];
5694 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5695 [content_ setBackgroundColor:[UIColor whiteColor]];
5696 [content addSubview:content_];
5698 [content_ setDelegate:self];
5699 [content_ setOpaque:YES];
5703 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5704 [super setSelected:selected animated:animated];
5705 [content_ setNeedsDisplay];
5708 - (void) drawContentRect:(CGRect)rect {
5709 bool selected([self isSelected]);
5710 float width(rect.size.width);
5713 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5720 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5724 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5728 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5733 /* Source Table {{{ */
5734 @interface SourceTable : CYViewController <
5735 UITableViewDataSource,
5738 _transient Database *database_;
5740 NSMutableArray *sources_;
5744 UIProgressHUD *hud_;
5747 //NSURLConnection *installer_;
5748 NSURLConnection *trivial_;
5749 NSURLConnection *trivial_bz2_;
5750 NSURLConnection *trivial_gz_;
5751 //NSURLConnection *automatic_;
5756 - (id) initWithDatabase:(Database *)database;
5758 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5762 @implementation SourceTable
5764 - (void) _deallocConnection:(NSURLConnection *)connection {
5765 if (connection != nil) {
5766 [connection cancel];
5767 //[connection setDelegate:nil];
5768 [connection release];
5780 //[self _deallocConnection:installer_];
5781 [self _deallocConnection:trivial_];
5782 [self _deallocConnection:trivial_gz_];
5783 [self _deallocConnection:trivial_bz2_];
5784 //[self _deallocConnection:automatic_];
5791 - (void) viewDidAppear:(BOOL)animated {
5792 [super viewDidAppear:animated];
5793 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5796 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5797 return offset_ == 0 ? 1 : 2;
5800 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5801 switch (section + (offset_ == 0 ? 1 : 0)) {
5802 case 0: return UCLocalize("ENTERED_BY_USER");
5803 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5809 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5810 int count = [sources_ count];
5812 case 0: return (offset_ == 0 ? count : offset_);
5813 case 1: return count - offset_;
5819 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5821 switch (indexPath.section) {
5822 case 0: idx = indexPath.row; break;
5823 case 1: idx = indexPath.row + offset_; break;
5827 return [sources_ objectAtIndex:idx];
5830 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5831 Source *source = [self sourceAtIndexPath:indexPath];
5832 return [source description] == nil ? 56 : 73;
5835 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5836 static NSString *cellIdentifier = @"SourceCell";
5838 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5839 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5840 [cell setSource:[self sourceAtIndexPath:indexPath]];
5845 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5846 return UITableViewCellAccessoryDisclosureIndicator;
5849 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5850 Source *source = [self sourceAtIndexPath:indexPath];
5852 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5853 initWithDatabase:database_
5854 title:[source label]
5855 filter:@selector(isVisibleInSource:)
5859 [packages setDelegate:delegate_];
5861 [[self navigationController] pushViewController:packages animated:YES];
5864 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5865 Source *source = [self sourceAtIndexPath:indexPath];
5866 return [source record] != nil;
5869 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5870 Source *source = [self sourceAtIndexPath:indexPath];
5871 [Sources_ removeObjectForKey:[source key]];
5872 [delegate_ syncData];
5876 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5879 @"./", @"Distribution",
5880 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5882 [delegate_ syncData];
5885 - (NSString *) getWarning {
5886 NSString *href(href_);
5887 NSRange colon([href rangeOfString:@"://"]);
5888 if (colon.location != NSNotFound)
5889 href = [href substringFromIndex:(colon.location + 3)];
5890 href = [href stringByAddingPercentEscapes];
5891 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5892 href = [href stringByCachingURLWithCurrentCDN];
5894 NSURL *url([NSURL URLWithString:href]);
5896 NSStringEncoding encoding;
5897 NSError *error(nil);
5899 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5900 return [warning length] == 0 ? nil : warning;
5904 - (void) _endConnection:(NSURLConnection *)connection {
5905 NSURLConnection **field = NULL;
5906 if (connection == trivial_)
5908 else if (connection == trivial_bz2_)
5909 field = &trivial_bz2_;
5910 else if (connection == trivial_gz_)
5911 field = &trivial_gz_;
5912 _assert(field != NULL);
5913 [connection release];
5918 trivial_bz2_ == nil &&
5924 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5927 UIAlertView *alert = [[[UIAlertView alloc]
5928 initWithTitle:UCLocalize("SOURCE_WARNING")
5931 cancelButtonTitle:UCLocalize("CANCEL")
5932 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5935 [alert setContext:@"warning"];
5936 [alert setNumberOfRows:1];
5940 } else if (error_ != nil) {
5941 UIAlertView *alert = [[[UIAlertView alloc]
5942 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5943 message:[error_ localizedDescription]
5945 cancelButtonTitle:UCLocalize("OK")
5946 otherButtonTitles:nil
5949 [alert setContext:@"urlerror"];
5952 UIAlertView *alert = [[[UIAlertView alloc]
5953 initWithTitle:UCLocalize("NOT_REPOSITORY")
5954 message:UCLocalize("NOT_REPOSITORY_EX")
5956 cancelButtonTitle:UCLocalize("OK")
5957 otherButtonTitles:nil
5960 [alert setContext:@"trivial"];
5964 [delegate_ setStatusBarShowsProgress:NO];
5965 [delegate_ removeProgressHUD:hud_];
5975 if (error_ != nil) {
5982 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5983 switch ([response statusCode]) {
5989 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5990 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5992 error_ = [error retain];
5993 [self _endConnection:connection];
5996 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5997 [self _endConnection:connection];
6000 - (NSString *) title { return UCLocalize("SOURCES"); }
6002 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6003 NSMutableURLRequest *request = [NSMutableURLRequest
6004 requestWithURL:[NSURL URLWithString:href]
6005 cachePolicy:NSURLRequestUseProtocolCachePolicy
6006 timeoutInterval:120.0
6009 [request setHTTPMethod:method];
6011 if (Machine_ != NULL)
6012 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6013 if (UniqueID_ != nil)
6014 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6016 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6018 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6021 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6022 NSString *context([alert context]);
6024 if ([context isEqualToString:@"source"]) {
6027 NSString *href = [[alert textField] text];
6029 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6031 if (![href hasSuffix:@"/"])
6032 href_ = [href stringByAppendingString:@"/"];
6035 href_ = [href_ retain];
6037 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6038 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6039 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6040 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6044 hud_ = [[delegate_ addProgressHUD] retain];
6045 [hud_ setText:UCLocalize("VERIFYING_URL")];
6054 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6055 } else if ([context isEqualToString:@"trivial"])
6056 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6057 else if ([context isEqualToString:@"urlerror"])
6058 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6059 else if ([context isEqualToString:@"warning"]) {
6074 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6078 - (id) initWithDatabase:(Database *)database {
6079 if ((self = [super init]) != nil) {
6080 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6081 [self updateButtonsForEditingStatus:NO animated:NO];
6083 database_ = database;
6084 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6086 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6087 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6088 [[self view] addSubview:list_];
6090 [list_ setDataSource:self];
6091 [list_ setDelegate:self];
6097 - (void) reloadData {
6099 if (!list.ReadMainList())
6102 [sources_ removeAllObjects];
6103 [sources_ addObjectsFromArray:[database_ sources]];
6105 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6108 int count([sources_ count]);
6110 for (int i = 0; i != count; i++) {
6111 if ([[sources_ objectAtIndex:i] record] == nil) break;
6115 [list_ setEditing:NO];
6116 [self updateButtonsForEditingStatus:NO animated:NO];
6120 - (void) addButtonClicked {
6121 /*[book_ pushPage:[[[AddSourceController alloc]
6126 UIAlertView *alert = [[[UIAlertView alloc]
6127 initWithTitle:UCLocalize("ENTER_APT_URL")
6130 cancelButtonTitle:UCLocalize("CANCEL")
6131 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6134 [alert setContext:@"source"];
6135 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6137 [alert setNumberOfRows:1];
6138 [alert addTextFieldWithValue:@"http://" label:@""];
6140 UITextInputTraits *traits = [[alert textField] textInputTraits];
6141 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6142 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6143 [traits setKeyboardType:UIKeyboardTypeURL];
6144 // XXX: UIReturnKeyDone
6145 [traits setReturnKeyType:UIReturnKeyNext];
6150 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6151 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
6152 initWithTitle:UCLocalize("ADD")
6153 style:UIBarButtonItemStylePlain
6155 action:@selector(addButtonClicked)
6157 [[self navigationItem] setLeftBarButtonItem:editing ? leftItem : [[self navigationItem] backBarButtonItem] animated:animated];
6160 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6161 initWithTitle:editing ? UCLocalize("DONE") : UCLocalize("EDIT")
6162 style:editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6164 action:@selector(editButtonClicked)
6166 [[self navigationItem] setRightBarButtonItem:rightItem animated:animated];
6167 [rightItem release];
6169 if (IsWildcat_ && !editing) {
6170 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6171 initWithTitle:UCLocalize("SETTINGS")
6172 style:UIBarButtonItemStylePlain
6174 action:@selector(settingsButtonClicked)
6176 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6177 [settingsItem release];
6181 - (void) settingsButtonClicked {
6182 [delegate_ showSettings];
6185 - (void) editButtonClicked {
6186 [list_ setEditing:![list_ isEditing] animated:YES];
6188 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6194 /* Installed Controller {{{ */
6195 @interface InstalledController : FilteredPackageController {
6199 - (id) initWithDatabase:(Database *)database;
6201 - (void) updateRoleButton;
6202 - (void) queueStatusDidChange;
6206 @implementation InstalledController
6212 - (NSString *) title { return UCLocalize("INSTALLED"); }
6214 - (id) initWithDatabase:(Database *)database {
6215 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6216 [self updateRoleButton];
6217 [self queueStatusDidChange];
6222 - (void) queueButtonClicked {
6227 - (void) queueStatusDidChange {
6230 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6231 initWithTitle:UCLocalize("QUEUE")
6232 style:UIBarButtonItemStyleDone
6234 action:@selector(queueButtonClicked)
6236 if (Queuing_) [[self navigationItem] setLeftBarButtonItem:queueItem];
6237 else [[self navigationItem] setLeftBarButtonItem:nil];
6238 [queueItem release];
6243 - (void) reloadData {
6244 [packages_ reloadData];
6247 - (void) updateRoleButton {
6248 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6249 initWithTitle:expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")
6250 style:expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6252 action:@selector(roleButtonClicked)
6254 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) [[self navigationItem] setRightBarButtonItem:rightItem];
6255 [rightItem release];
6258 - (void) roleButtonClicked {
6259 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6260 [packages_ reloadData];
6263 [self updateRoleButton];
6266 - (void) setDelegate:(id)delegate {
6267 [super setDelegate:delegate];
6268 [packages_ setDelegate:delegate];
6274 /* Home Controller {{{ */
6275 @interface HomeController : CYBrowserController {
6280 @implementation HomeController
6282 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6283 [super _setMoreHeaders:request];
6286 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6287 if (UniqueID_ != nil)
6288 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6290 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6293 - (void) aboutButtonClicked {
6294 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6296 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6297 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6298 [alert setCancelButtonIndex:0];
6301 @"Copyright (C) 2008-2010\n"
6302 "Jay Freeman (saurik)\n"
6303 "saurik@saurik.com\n"
6304 "http://www.saurik.com/"
6310 - (void) viewWillAppear:(BOOL)animated {
6311 [super viewWillAppear:animated];
6312 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6315 - (void) viewWillDisappear:(BOOL)animated {
6316 [super viewWillDisappear:animated];
6317 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6321 if ((self = [super init]) != nil) {
6322 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6323 initWithTitle:UCLocalize("ABOUT")
6324 style:UIBarButtonItemStylePlain
6326 action:@selector(aboutButtonClicked)
6333 /* Manage Controller {{{ */
6334 @interface ManageController : CYBrowserController {
6337 - (void) queueStatusDidChange;
6340 @implementation ManageController
6343 if ((self = [super init]) != nil) {
6344 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6346 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6347 initWithTitle:UCLocalize("SETTINGS")
6348 style:UIBarButtonItemStylePlain
6350 action:@selector(settingsButtonClicked)
6352 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6353 [settingsItem release];
6355 [self queueStatusDidChange];
6359 - (void) settingsButtonClicked {
6360 [delegate_ showSettings];
6364 - (void) queueButtonClicked {
6368 - (void) applyLoadingTitle {
6369 // No "Loading" title.
6372 - (void) applyRightButton {
6377 - (void) queueStatusDidChange {
6379 if (!IsWildcat_ && Queuing_) {
6380 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6381 initWithTitle:UCLocalize("QUEUE")
6382 style:UIBarButtonItemStyleDone
6384 action:@selector(queueButtonClicked)
6386 [[self navigationItem] setRightBarButtonItem:queueItem];
6388 [queueItem release];
6390 [[self navigationItem] setRightBarButtonItem:nil];
6395 - (bool) isLoading {
6402 /* Refresh Bar {{{ */
6403 @interface RefreshBar : UINavigationBar {
6404 UIProgressIndicator *indicator_;
6405 UITextLabel *prompt_;
6406 UIProgressBar *progress_;
6407 UINavigationButton *cancel_;
6412 @implementation RefreshBar
6414 - (void) positionViews {
6415 CGRect frame = [cancel_ frame];
6416 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6417 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6418 [cancel_ setFrame:frame];
6420 CGSize prgsize = {75, 100};
6422 [self frame].size.width - prgsize.width - 10,
6423 ([self frame].size.height - prgsize.height) / 2
6425 [progress_ setFrame:prgrect];
6427 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6428 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6429 CGRect indrect = {{indoffset, indoffset}, indsize};
6430 [indicator_ setFrame:indrect];
6432 CGSize prmsize = {215, indsize.height + 4};
6434 indoffset * 2 + indsize.width,
6435 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6437 [prompt_ setFrame:prmrect];
6440 - (void)setFrame:(CGRect)frame {
6441 [super setFrame:frame];
6443 [self positionViews];
6446 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6447 if ((self = [super initWithFrame:frame])) {
6448 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6450 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6451 [self setBarStyle:UIBarStyleBlack];
6453 UIBarStyle barstyle([self _barStyle:NO]);
6454 bool ugly(barstyle == UIBarStyleDefault);
6456 UIProgressIndicatorStyle style = ugly ?
6457 UIProgressIndicatorStyleMediumBrown :
6458 UIProgressIndicatorStyleMediumWhite;
6460 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6461 [indicator_ setStyle:style];
6462 [indicator_ startAnimation];
6463 [self addSubview:indicator_];
6465 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6466 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6467 [prompt_ setBackgroundColor:[UIColor clearColor]];
6468 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6469 [self addSubview:prompt_];
6471 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6472 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6473 [progress_ setStyle:0];
6474 [self addSubview:progress_];
6476 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6477 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6478 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6479 [cancel_ setBarStyle:barstyle];
6481 [self positionViews];
6486 [cancel_ removeFromSuperview];
6490 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6491 [progress_ setProgress:0];
6492 [self addSubview:cancel_];
6496 [cancel_ removeFromSuperview];
6499 - (void) setPrompt:(NSString *)prompt {
6500 [prompt_ setText:prompt];
6503 - (void) setProgress:(float)progress {
6504 [progress_ setProgress:progress];
6510 @class CYNavigationController;
6512 /* Cydia Tab Bar Controller {{{ */
6513 @interface CYTabBarController : UITabBarController {
6514 Database *database_;
6519 @implementation CYTabBarController
6521 /* XXX: some logic should probably go here related to
6522 freeing the view controllers on tab change */
6524 - (void) reloadData {
6525 size_t count([[self viewControllers] count]);
6526 for (size_t i(0); i != count; ++i) {
6527 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6532 - (id) initWithDatabase:(Database *)database {
6533 if ((self = [super init]) != nil) {
6534 database_ = database;
6541 /* Cydia Navigation Controller {{{ */
6542 @interface CYNavigationController : UINavigationController {
6543 _transient Database *database_;
6544 id<UINavigationControllerDelegate> delegate_;
6547 - (id) initWithDatabase:(Database *)database;
6548 - (void) reloadData;
6553 @implementation CYNavigationController
6555 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6556 // Inherit autorotation settings for modal parents.
6557 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6558 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6560 return [super shouldAutorotateToInterfaceOrientation:orientation];
6568 - (void) reloadData {
6569 size_t count([[self viewControllers] count]);
6570 for (size_t i(0); i != count; ++i) {
6571 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6576 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6577 delegate_ = delegate;
6580 - (id) initWithDatabase:(Database *)database {
6581 if ((self = [super init]) != nil) {
6582 database_ = database;
6588 /* Cydia:// Protocol {{{ */
6589 @interface CydiaURLProtocol : NSURLProtocol {
6594 @implementation CydiaURLProtocol
6596 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6597 NSURL *url([request URL]);
6600 NSString *scheme([[url scheme] lowercaseString]);
6601 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6606 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6610 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6611 id<NSURLProtocolClient> client([self client]);
6613 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6615 NSData *data(UIImagePNGRepresentation(icon));
6617 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6618 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6619 [client URLProtocol:self didLoadData:data];
6620 [client URLProtocolDidFinishLoading:self];
6624 - (void) startLoading {
6625 id<NSURLProtocolClient> client([self client]);
6626 NSURLRequest *request([self request]);
6628 NSURL *url([request URL]);
6629 NSString *href([url absoluteString]);
6631 NSString *path([href substringFromIndex:8]);
6632 NSRange slash([path rangeOfString:@"/"]);
6635 if (slash.location == NSNotFound) {
6639 command = [path substringToIndex:slash.location];
6640 path = [path substringFromIndex:(slash.location + 1)];
6643 Database *database([Database sharedInstance]);
6645 if ([command isEqualToString:@"package-icon"]) {
6648 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6649 Package *package([database packageWithName:path]);
6652 UIImage *icon([package icon]);
6653 [self _returnPNGWithImage:icon forRequest:request];
6654 } else if ([command isEqualToString:@"source-icon"]) {
6657 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6658 NSString *source(Simplify(path));
6659 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6661 icon = [UIImage applicationImageNamed:@"unknown.png"];
6662 [self _returnPNGWithImage:icon forRequest:request];
6663 } else if ([command isEqualToString:@"uikit-image"]) {
6666 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6667 UIImage *icon(_UIImageWithName(path));
6668 [self _returnPNGWithImage:icon forRequest:request];
6669 } else if ([command isEqualToString:@"section-icon"]) {
6672 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6673 NSString *section(Simplify(path));
6674 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6676 icon = [UIImage applicationImageNamed:@"unknown.png"];
6677 [self _returnPNGWithImage:icon forRequest:request];
6679 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6683 - (void) stopLoading {
6689 /* Sections Controller {{{ */
6690 @interface SectionsController : CYViewController <
6691 UITableViewDataSource,
6694 _transient Database *database_;
6695 NSMutableArray *sections_;
6696 NSMutableArray *filtered_;
6702 - (id) initWithDatabase:(Database *)database;
6703 - (void) reloadData;
6706 - (void) editButtonClicked;
6710 @implementation SectionsController
6713 [list_ setDataSource:nil];
6714 [list_ setDelegate:nil];
6716 [sections_ release];
6717 [filtered_ release];
6719 [accessory_ release];
6723 - (void) viewDidAppear:(BOOL)animated {
6724 [super viewDidAppear:animated];
6725 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6728 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6729 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6733 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6734 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6737 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6741 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6742 static NSString *reuseIdentifier = @"SectionCell";
6744 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6745 if (cell == nil) cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6746 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6751 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6755 Section *section = [self sectionAtIndexPath:indexPath];
6756 NSString *name = [section name];
6759 if ([indexPath row] == 0) {
6762 title = UCLocalize("ALL_PACKAGES");
6765 name = [NSString stringWithString:name];
6766 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6769 title = UCLocalize("NO_SECTION");
6773 FilteredPackageController *table = [[[FilteredPackageController alloc]
6774 initWithDatabase:database_
6776 filter:@selector(isVisibleInSection:)
6780 [table setDelegate:delegate_];
6782 [[self navigationController] pushViewController:table animated:YES];
6785 - (NSString *) title { return UCLocalize("SECTIONS"); }
6787 - (id) initWithDatabase:(Database *)database {
6788 if ((self = [super init]) != nil) {
6789 database_ = database;
6791 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6793 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6794 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6796 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6797 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6798 [list_ setRowHeight:45.0f];
6799 [[self view] addSubview:list_];
6801 [list_ setDataSource:self];
6802 [list_ setDelegate:self];
6808 - (void) reloadData {
6809 NSArray *packages = [database_ packages];
6811 [sections_ removeAllObjects];
6812 [filtered_ removeAllObjects];
6815 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6816 SectionMap sections;
6817 sections.resize(64);
6819 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6823 for (Package *package in packages) {
6824 NSString *name([package section]);
6825 NSString *key(name == nil ? @"" : name);
6830 _profile(SectionsView$reloadData$Section)
6831 section = §ions[key];
6832 if (*section == nil) {
6833 _profile(SectionsView$reloadData$Section$Allocate)
6834 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6839 [*section addToCount];
6841 _profile(SectionsView$reloadData$Filter)
6842 if (![package valid] || ![package visible])
6846 [*section addToRow];
6850 _profile(SectionsView$reloadData$Section)
6851 section = [sections objectForKey:key];
6852 if (section == nil) {
6853 _profile(SectionsView$reloadData$Section$Allocate)
6854 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6855 [sections setObject:section forKey:key];
6860 [section addToCount];
6862 _profile(SectionsView$reloadData$Filter)
6863 if (![package valid] || ![package visible])
6873 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6874 [sections_ addObject:i->second];
6876 [sections_ addObjectsFromArray:[sections allValues]];
6879 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6881 for (Section *section in sections_) {
6882 size_t count([section row]);
6886 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6887 [section setCount:count];
6888 [filtered_ addObject:section];
6891 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6892 initWithTitle:[sections_ count] == 0 ? nil : UCLocalize("EDIT")
6893 style:UIBarButtonItemStylePlain
6895 action:@selector(editButtonClicked)
6897 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] != nil];
6898 [rightItem release];
6904 - (void) resetView {
6906 [self editButtonClicked];
6909 - (void) editButtonClicked {
6910 if ((editing_ = !editing_))
6913 [delegate_ updateData];
6915 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6916 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6917 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6920 - (UIView *) accessoryView {
6926 /* Changes Controller {{{ */
6927 @interface ChangesController : CYViewController <
6928 UITableViewDataSource,
6931 _transient Database *database_;
6932 CFMutableArrayRef packages_;
6933 NSMutableArray *sections_;
6936 BOOL hasSentFirstLoad_;
6939 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6940 - (void) reloadData;
6944 @implementation ChangesController
6947 [list_ setDelegate:nil];
6948 [list_ setDataSource:nil];
6950 CFRelease(packages_);
6952 [sections_ release];
6957 - (void) viewDidAppear:(BOOL)animated {
6958 [super viewDidAppear:animated];
6959 if (!hasSentFirstLoad_) {
6960 hasSentFirstLoad_ = YES;
6961 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6963 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6967 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6968 NSInteger count([sections_ count]);
6969 return count == 0 ? 1 : count;
6972 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6973 if ([sections_ count] == 0)
6975 return [[sections_ objectAtIndex:section] name];
6978 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6979 if ([sections_ count] == 0)
6981 return [[sections_ objectAtIndex:section] count];
6984 - (Package *) packageAtIndex:(NSUInteger)index {
6985 return (Package *) CFArrayGetValueAtIndex(packages_, index);
6988 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6989 Section *section([sections_ objectAtIndex:[path section]]);
6990 NSInteger row([path row]);
6991 return [self packageAtIndex:([section row] + row)];
6994 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6995 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6997 cell = [[[PackageCell alloc] init] autorelease];
6998 [cell setPackage:[self packageAtIndexPath:path]];
7002 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7003 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7006 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7007 Package *package([self packageAtIndexPath:path]);
7008 PackageController *view([delegate_ packageController]);
7009 [view setDelegate:delegate_];
7010 [view setPackage:package];
7011 [[self navigationController] pushViewController:view animated:YES];
7015 - (void) refreshButtonClicked {
7016 [delegate_ beginUpdate];
7017 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7020 - (void) upgradeButtonClicked {
7021 [delegate_ distUpgrade];
7024 - (NSString *) title { return UCLocalize("CHANGES"); }
7026 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7027 if ((self = [super init]) != nil) {
7028 database_ = database;
7029 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7031 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7033 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7035 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7036 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7037 [list_ setRowHeight:73.0f];
7038 [[self view] addSubview:list_];
7040 [list_ setDataSource:self];
7041 [list_ setDelegate:self];
7043 delegate_ = delegate;
7047 - (void) _reloadPackages:(NSArray *)packages {
7049 for (Package *package in packages)
7051 [package uninstalled] && [package valid] && [package visible] ||
7052 [package upgradableAndEssential:YES]
7054 CFArrayAppendValue(packages_, package);
7057 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7061 - (void) reloadData {
7062 NSArray *packages = [database_ packages];
7064 CFArrayRemoveAllValues(packages_);
7066 [sections_ removeAllObjects];
7069 UIProgressHUD *hud([delegate_ addProgressHUD]);
7071 [hud setText:@"Loading Changes"];
7072 //NSLog(@"HUD:%@::%@", delegate_, hud);
7073 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7074 [delegate_ removeProgressHUD:hud];
7076 [self _reloadPackages:packages];
7079 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7080 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7081 Section *section = nil;
7085 bool unseens = false;
7087 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7089 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7090 Package *package = [self packageAtIndex:offset];
7092 BOOL uae = [package upgradableAndEssential:YES];
7098 _profile(ChangesController$reloadData$Remember)
7099 seen = [package seen];
7102 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7107 name = UCLocalize("UNKNOWN");
7109 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7113 _profile(ChangesController$reloadData$Allocate)
7114 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7115 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7116 [sections_ addObject:section];
7120 [section addToCount];
7121 } else if ([package ignored])
7122 [ignored addToCount];
7125 [upgradable addToCount];
7130 CFRelease(formatter);
7133 Section *last = [sections_ lastObject];
7134 size_t count = [last count];
7135 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7136 [sections_ removeLastObject];
7139 if ([ignored count] != 0)
7140 [sections_ insertObject:ignored atIndex:0];
7142 [sections_ insertObject:upgradable atIndex:0];
7146 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7147 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7148 style:UIBarButtonItemStylePlain
7150 action:@selector(upgradeButtonClicked)
7152 if (upgrades_ > 0) [[self navigationItem] setRightBarButtonItem:rightItem];
7153 [rightItem release];
7155 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
7156 initWithTitle:UCLocalize("REFRESH")
7157 style:UIBarButtonItemStylePlain
7159 action:@selector(refreshButtonClicked)
7161 if (![delegate_ updating]) [[self navigationItem] setLeftBarButtonItem:leftItem];
7167 /* Search Controller {{{ */
7168 @interface SearchController : FilteredPackageController <
7171 UISearchBar *search_;
7174 - (id) initWithDatabase:(Database *)database;
7175 - (void) reloadData;
7179 @implementation SearchController
7186 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7187 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7188 [search_ resignFirstResponder];
7192 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7193 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7197 - (NSString *) title { return nil; }
7199 - (id) initWithDatabase:(Database *)database {
7200 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7203 - (void)viewDidAppear:(BOOL)animated {
7204 [super viewDidAppear:animated];
7206 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7207 [search_ layoutSubviews];
7208 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7209 UITextField *textField = [search_ searchField];
7210 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7211 [search_ setDelegate:self];
7212 [textField setEnablesReturnKeyAutomatically:NO];
7213 [[self navigationItem] setTitleView:textField];
7217 - (void) _reloadData {
7220 - (void) reloadData {
7221 _profile(SearchController$reloadData)
7222 [packages_ reloadData];
7225 [packages_ resetCursor];
7228 - (void) didSelectPackage:(Package *)package {
7229 [search_ resignFirstResponder];
7230 [super didSelectPackage:package];
7235 /* Settings Controller {{{ */
7236 @interface SettingsController : CYViewController <
7237 UITableViewDataSource,
7240 _transient Database *database_;
7243 UITableView *table_;
7244 id subscribedSwitch_;
7246 UITableViewCell *subscribedCell_;
7247 UITableViewCell *ignoredCell_;
7250 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7254 @implementation SettingsController
7258 if (package_ != nil)
7261 [subscribedSwitch_ release];
7262 [ignoredSwitch_ release];
7263 [subscribedCell_ release];
7264 [ignoredCell_ release];
7269 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7270 if (package_ == nil)
7276 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7277 if (package_ == nil)
7283 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7284 return UCLocalize("SHOW_ALL_CHANGES_EX");
7287 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7288 if (package_ == nil)
7291 NSMutableDictionary *metadata([package_ metadata]);
7294 if (NSNumber *number = [metadata objectForKey:key])
7295 before = [number boolValue];
7299 if (value != before) {
7300 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7302 [delegate_ updateData];
7306 - (void) onSubscribed:(id)control {
7307 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7310 - (void) onIgnored:(id)control {
7311 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
7314 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7315 if (package_ == nil)
7318 switch ([indexPath row]) {
7319 case 0: return subscribedCell_;
7320 case 1: return ignoredCell_;
7328 - (NSString *) title { return UCLocalize("SETTINGS"); }
7330 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7331 if ((self = [super init])) {
7332 database_ = database;
7333 name_ = [package retain];
7335 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7337 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7338 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7339 [[self view] addSubview:table_];
7341 subscribedSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7342 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7343 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7345 ignoredSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7346 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7347 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7349 subscribedCell_ = [[UITableViewCell alloc] init];
7350 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7351 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7352 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7354 ignoredCell_ = [[UITableViewCell alloc] init];
7355 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7356 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7357 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7359 [table_ setDataSource:self];
7360 [table_ setDelegate:self];
7365 - (void) reloadData {
7366 if (package_ != nil)
7367 [package_ autorelease];
7368 package_ = [database_ packageWithName:name_];
7369 if (package_ != nil) {
7371 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7372 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7375 [table_ reloadData];
7380 /* Signature Controller {{{ */
7381 @interface SignatureController : CYBrowserController {
7382 _transient Database *database_;
7386 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7390 @implementation SignatureController
7397 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7399 [super webView:view didClearWindowObject:window forFrame:frame];
7402 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7403 if ((self = [super init]) != nil) {
7404 database_ = database;
7405 package_ = [package retain];
7410 - (void) reloadData {
7411 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7417 /* Role Controller {{{ */
7418 @interface RoleController : CYViewController <
7419 UITableViewDataSource,
7422 _transient Database *database_;
7424 UITableView *table_;
7425 UISegmentedControl *segment_;
7429 - (void) showDoneButton;
7430 - (void) resizeSegmentedControl;
7434 @implementation RoleController
7438 [container_ release];
7443 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7444 if ((self = [super init])) {
7445 database_ = database;
7446 roledelegate_ = delegate;
7448 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7450 NSArray *items = [NSArray arrayWithObjects:
7452 UCLocalize("HACKER"),
7453 UCLocalize("DEVELOPER"),
7455 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7456 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7457 [container_ addSubview:segment_];
7460 if ([Role_ isEqualToString:@"User"]) index = 0;
7461 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7462 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7464 [segment_ setSelectedSegmentIndex:index];
7465 [self showDoneButton];
7468 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7469 [self resizeSegmentedControl];
7471 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7472 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7473 [table_ setDelegate:self];
7474 [table_ setDataSource:self];
7475 [[self view] addSubview:table_];
7476 [table_ reloadData];
7480 - (void) resizeSegmentedControl {
7481 CGFloat width = [[self view] frame].size.width;
7482 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7485 - (void) viewWillAppear:(BOOL)animated {
7486 [super viewWillAppear:animated];
7488 [self resizeSegmentedControl];
7491 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7492 [self resizeSegmentedControl];
7495 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7496 [self resizeSegmentedControl];
7500 NSString *role(nil);
7502 switch ([segment_ selectedSegmentIndex]) {
7503 case 0: role = @"User"; break;
7504 case 1: role = @"Hacker"; break;
7505 case 2: role = @"Developer"; break;
7510 if (![role isEqualToString:Role_]) {
7511 bool rolling(Role_ == nil);
7514 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7518 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7523 [roledelegate_ loadData];
7525 [roledelegate_ updateData];
7529 - (void) segmentChanged:(UISegmentedControl *)control {
7530 [self showDoneButton];
7533 - (void) doneButtonClicked {
7535 [[self navigationController] dismissModalViewControllerAnimated:YES];
7538 - (void) showDoneButton {
7539 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7540 initWithTitle:UCLocalize("DONE")
7541 style:UIBarButtonItemStyleDone
7543 action:@selector(doneButtonClicked)
7545 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] == nil];
7546 [rightItem release];
7549 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7550 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7554 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7558 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7559 return nil; // This method is required by the protocol.
7562 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7564 return UCLocalize("ROLE_EX");
7566 return [NSString stringWithFormat:
7567 @"%@: %@\n%@: %@\n%@: %@",
7568 UCLocalize("USER"), UCLocalize("USER_EX"),
7569 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7570 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7575 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7576 if (section == 3) return 44.0f;
7580 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7581 if (section == 3) return container_;
7587 /* Stash Controller {{{ */
7588 @interface CYStashController : CYViewController {
7589 UIActivityIndicatorView *spinner_;
7595 @implementation CYStashController
7597 if ((self = [super init])) {
7598 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7600 spinner_ = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
7601 CGRect spinrect = [spinner_ frame];
7602 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7603 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7604 [spinner_ setFrame:spinrect];
7605 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7606 [[self view] addSubview:spinner_];
7608 [spinner_ startAnimating];
7611 captrect.size.width = [[self view] frame].size.width;
7612 captrect.size.height = 40.0f;
7613 captrect.origin.x = 0;
7614 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7615 caption_ = [[UILabel alloc] initWithFrame:captrect];
7616 [caption_ setText:@"Initializing Filesystem"];
7617 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7618 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7619 [caption_ setTextColor:[UIColor whiteColor]];
7620 [caption_ setBackgroundColor:[UIColor clearColor]];
7621 [caption_ setShadowColor:[UIColor blackColor]];
7622 [caption_ setTextAlignment:UITextAlignmentCenter];
7623 [[self view] addSubview:caption_];
7627 statusrect.size.width = [[self view] frame].size.width;
7628 statusrect.size.height = 30.0f;
7629 statusrect.origin.x = 0;
7630 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7631 status_ = [[UILabel alloc] initWithFrame:statusrect];
7632 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7633 [status_ setText:@"(Cydia will exit when complete.)"];
7634 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7635 [status_ setTextColor:[UIColor whiteColor]];
7636 [status_ setBackgroundColor:[UIColor clearColor]];
7637 [status_ setShadowColor:[UIColor blackColor]];
7638 [status_ setTextAlignment:UITextAlignmentCenter];
7639 [[self view] addSubview:status_];
7644 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7645 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7650 /* Cydia Container {{{ */
7651 @interface CYContainer : UIViewController <ProgressDelegate> {
7652 _transient Database *database_;
7653 RefreshBar *refreshbar_;
7658 UITabBarController *root_;
7661 - (void) setTabBarController:(UITabBarController *)controller;
7663 - (void) dropBar:(BOOL)animated;
7664 - (void) beginUpdate;
7665 - (void) raiseBar:(BOOL)animated;
7670 @implementation CYContainer
7672 - (BOOL) _reallyWantsFullScreenLayout {
7676 // NOTE: UIWindow only sends the top controller these messages,
7677 // So we have to forward them on.
7679 - (void) viewDidAppear:(BOOL)animated {
7680 [super viewDidAppear:animated];
7681 [root_ viewDidAppear:animated];
7684 - (void) viewWillAppear:(BOOL)animated {
7685 [super viewWillAppear:animated];
7686 [root_ viewWillAppear:animated];
7689 - (void) viewDidDisappear:(BOOL)animated {
7690 [super viewDidDisappear:animated];
7691 [root_ viewDidDisappear:animated];
7694 - (void) viewWillDisappear:(BOOL)animated {
7695 [super viewWillDisappear:animated];
7696 [root_ viewWillDisappear:animated];
7699 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7700 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7703 - (void) setTabBarController:(UITabBarController *)controller {
7705 [[self view] addSubview:[root_ view]];
7708 - (void) setUpdate:(NSDate *)date {
7712 - (void) beginUpdate {
7714 [refreshbar_ start];
7719 detachNewThreadSelector:@selector(performUpdate)
7725 - (void) performUpdate { _pooled
7727 status.setDelegate(self);
7728 [database_ updateWithStatus:status];
7731 performSelectorOnMainThread:@selector(completeUpdate)
7737 - (void) completeUpdate {
7738 if (!updating_) return;
7741 [self raiseBar:YES];
7743 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7746 - (void) cancelUpdate {
7748 [self raiseBar:YES];
7750 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7753 - (void) cancelPressed {
7754 [self cancelUpdate];
7761 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7762 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7765 - (void) startProgress {
7768 - (void) setProgressTitle:(NSString *)title {
7770 performSelectorOnMainThread:@selector(_setProgressTitle:)
7776 - (bool) isCancelling:(size_t)received {
7780 - (void) setProgressPercent:(float)percent {
7782 performSelectorOnMainThread:@selector(_setProgressPercent:)
7783 withObject:[NSNumber numberWithFloat:percent]
7788 - (void) addProgressOutput:(NSString *)output {
7790 performSelectorOnMainThread:@selector(_addProgressOutput:)
7796 - (void) _setProgressTitle:(NSString *)title {
7797 [refreshbar_ setPrompt:title];
7800 - (void) _setProgressPercent:(NSNumber *)percent {
7801 [refreshbar_ setProgress:[percent floatValue]];
7804 - (void) _addProgressOutput:(NSString *)output {
7807 - (void) setUpdateDelegate:(id)delegate {
7808 updatedelegate_ = delegate;
7811 - (CGFloat) statusBarHeight {
7812 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7813 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7815 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7819 - (void) dropBar:(BOOL)animated {
7820 if (dropped_) return;
7823 [[self view] addSubview:refreshbar_];
7825 CGFloat sboffset = [self statusBarHeight];
7827 CGRect barframe = [refreshbar_ frame];
7828 barframe.origin.y = sboffset;
7829 [refreshbar_ setFrame:barframe];
7831 if (animated) [UIView beginAnimations:nil context:NULL];
7832 CGRect viewframe = [[root_ view] frame];
7833 viewframe.origin.y += barframe.size.height + sboffset;
7834 viewframe.size.height -= barframe.size.height + sboffset;
7835 [[root_ view] setFrame:viewframe];
7836 if (animated) [UIView commitAnimations];
7838 // Ensure bar has the proper width for our view, it might have changed
7839 barframe.size.width = viewframe.size.width;
7840 [refreshbar_ setFrame:barframe];
7842 // XXX: fix Apple's layout bug
7843 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7846 - (void) raiseBar:(BOOL)animated {
7847 if (!dropped_) return;
7850 [refreshbar_ removeFromSuperview];
7852 CGFloat sboffset = [self statusBarHeight];
7854 if (animated) [UIView beginAnimations:nil context:NULL];
7855 CGRect barframe = [refreshbar_ frame];
7856 CGRect viewframe = [[root_ view] frame];
7857 viewframe.origin.y -= barframe.size.height + sboffset;
7858 viewframe.size.height += barframe.size.height + sboffset;
7859 [[root_ view] setFrame:viewframe];
7860 if (animated) [UIView commitAnimations];
7862 // XXX: fix Apple's layout bug
7863 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7866 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7867 // XXX: fix Apple's layout bug
7868 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7871 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7877 // XXX: fix Apple's layout bug
7878 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7881 - (void) statusBarFrameChanged:(NSNotification *)notification {
7889 [refreshbar_ release];
7890 [[NSNotificationCenter defaultCenter] removeObserver:self];
7894 - (id) initWithDatabase:(Database *)database {
7895 if ((self = [super init]) != nil) {
7896 database_ = database;
7898 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7899 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7901 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7918 @interface Cydia : UIApplication <
7919 ConfirmationControllerDelegate,
7920 ProgressControllerDelegate,
7922 UINavigationControllerDelegate
7925 CYContainer *container_;
7928 NSMutableArray *essential_;
7929 NSMutableArray *broken_;
7931 Database *database_;
7935 UIKeyboard *keyboard_;
7936 UIProgressHUD *hud_;
7938 SectionsController *sections_;
7939 ChangesController *changes_;
7940 ManageController *manage_;
7941 SearchController *search_;
7942 SourceTable *sources_;
7943 InstalledController *installed_;
7946 CYStashController *stash_;
7951 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7952 - (void) setPage:(CYViewController *)page;
7957 static _finline void _setHomePage(Cydia *self) {
7958 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7961 @implementation Cydia
7963 - (void) beginUpdate {
7964 [container_ beginUpdate];
7968 return [container_ updating];
7971 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7976 if ([broken_ count] != 0) {
7977 int count = [broken_ count];
7979 UIAlertView *alert = [[[UIAlertView alloc]
7980 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7981 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7983 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7984 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
7987 [alert setContext:@"fixhalf"];
7989 } else if (!Ignored_ && [essential_ count] != 0) {
7990 int count = [essential_ count];
7992 UIAlertView *alert = [[[UIAlertView alloc]
7993 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7994 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
7996 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
7997 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8000 [alert setContext:@"upgrade"];
8005 - (void) _saveConfig {
8008 NSString *error(nil);
8009 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8011 NSError *error(nil);
8012 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8013 NSLog(@"failure to save metadata data: %@", error);
8016 NSLog(@"failure to serialize metadata: %@", error);
8024 - (void) _updateData {
8027 /* XXX: this is just stupid */
8028 if (tag_ != 1 && sections_ != nil)
8029 [sections_ reloadData];
8030 if (tag_ != 2 && changes_ != nil)
8031 [changes_ reloadData];
8032 if (tag_ != 4 && search_ != nil)
8033 [search_ reloadData];
8035 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8038 - (int)indexOfTabWithTag:(int)tag {
8040 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8041 if ([[controller tabBarItem] tag] == tag) return i;
8048 - (void) _refreshIfPossible {
8049 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8051 bool recently = false;
8052 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8053 if (update != nil) {
8054 NSTimeInterval interval([update timeIntervalSinceNow]);
8055 if (interval <= 0 && interval > -(15*60))
8059 // Don't automatic refresh if:
8060 // - We already refreshed recently.
8061 // - We already auto-refreshed this launch.
8062 // - Auto-refresh is disabled.
8063 if (recently || loaded_ || ManualRefresh) {
8064 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8066 // If we are cancelling due to ManualRefresh or a recent refresh
8067 // we need to make sure it knows it's already loaded.
8071 // We are going to load, so remember that.
8075 SCNetworkReachabilityFlags flags; {
8076 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8077 SCNetworkReachabilityGetFlags(reachability, &flags);
8078 CFRelease(reachability);
8081 // XXX: this elaborate mess is what Apple is using to determine this? :(
8082 // XXX: do we care if the user has to intervene? maybe that's ok?
8084 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8085 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8086 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8087 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8088 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8089 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8093 // If we can reach the server, auto-refresh!
8095 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8100 - (void) refreshIfPossible {
8101 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8104 - (void) _reloadData {
8105 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8106 [hud setText:UCLocalize("RELOADING_DATA")];
8108 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8111 if (hud) [self removeProgressHUD:hud];
8115 [essential_ removeAllObjects];
8116 [broken_ removeAllObjects];
8118 NSArray *packages([database_ packages]);
8119 for (Package *package in packages) {
8121 [broken_ addObject:package];
8122 if ([package upgradableAndEssential:NO]) {
8123 if ([package essential])
8124 [essential_ addObject:package];
8129 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8131 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8132 [changesItem setBadgeValue:badge];
8133 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8135 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8136 [self setApplicationBadge:badge];
8138 [self setApplicationBadgeString:badge];
8140 [changesItem setBadgeValue:nil];
8141 [changesItem setAnimatedBadge:NO];
8143 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8144 [self removeApplicationBadge];
8145 else // XXX: maybe use setApplicationBadgeString also?
8146 [self setApplicationIconBadgeNumber:0];
8151 [self refreshIfPossible];
8154 - (void) updateData {
8155 [database_ setVisible];
8164 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8165 _assert(file != NULL);
8167 for (NSString *key in [Sources_ allKeys]) {
8168 NSDictionary *source([Sources_ objectForKey:key]);
8170 fprintf(file, "%s %s %s\n",
8171 [[source objectForKey:@"Type"] UTF8String],
8172 [[source objectForKey:@"URI"] UTF8String],
8173 [[source objectForKey:@"Distribution"] UTF8String]
8181 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8182 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8183 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8184 [container_ presentModalViewController:navigation animated:YES];
8187 detachNewThreadSelector:@selector(update_)
8190 title:UCLocalize("UPDATING_SOURCES")
8194 - (void) reloadData {
8195 @synchronized (self) {
8201 pkgProblemResolver *resolver = [database_ resolver];
8203 resolver->InstallProtect();
8204 if (!resolver->Resolve(true))
8208 - (CGRect) popUpBounds {
8209 return [[tabbar_ view] bounds];
8213 if (![database_ prepare])
8216 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8217 [page setDelegate:self];
8218 CYNavigationController *confirm_ = [[CYNavigationController alloc] initWithRootViewController:page];
8219 [confirm_ setDelegate:self];
8221 if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8222 [container_ presentModalViewController:confirm_ animated:YES];
8228 @synchronized (self) {
8233 - (void) clearPackage:(Package *)package {
8234 @synchronized (self) {
8241 - (void) installPackages:(NSArray *)packages {
8242 @synchronized (self) {
8243 for (Package *package in packages)
8250 - (void) installPackage:(Package *)package {
8251 @synchronized (self) {
8258 - (void) removePackage:(Package *)package {
8259 @synchronized (self) {
8266 - (void) distUpgrade {
8267 @synchronized (self) {
8268 if (![database_ upgrade])
8275 @synchronized (self) {
8280 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8281 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8283 if (navigation != nil) {
8284 [navigation pushViewController:progress animated:YES];
8286 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8287 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8288 [container_ presentModalViewController:navigation animated:YES];
8292 detachNewThreadSelector:@selector(perform)
8295 title:UCLocalize("RUNNING")
8299 - (void) progressControllerIsComplete:(ProgressController *)progress {
8303 - (void) setPage:(CYViewController *)page {
8304 [page setDelegate:self];
8306 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8307 [navController setViewControllers:[NSArray arrayWithObject:page]];
8308 for (CYNavigationController *page in [tabbar_ viewControllers]) {
8309 if (page != navController) [page setViewControllers:nil];
8313 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8314 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8315 [browser loadURL:url];
8319 - (SectionsController *) sectionsController {
8320 if (sections_ == nil)
8321 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8325 - (ChangesController *) changesController {
8326 if (changes_ == nil)
8327 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8331 - (ManageController *) manageController {
8332 if (manage_ == nil) {
8333 manage_ = (ManageController *) [[self
8334 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8335 withClass:[ManageController class]
8337 if (!IsWildcat_) queueDelegate_ = manage_;
8342 - (SearchController *) searchController {
8344 search_ = [[SearchController alloc] initWithDatabase:database_];
8348 - (SourceTable *) sourcesController {
8349 if (sources_ == nil)
8350 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8354 - (InstalledController *) installedController {
8355 if (installed_ == nil) {
8356 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8357 if (IsWildcat_) queueDelegate_ = installed_;
8362 - (void) tabBarController:(id)tabBarController didSelectViewController:(UIViewController *)viewController {
8363 int tag = [[viewController tabBarItem] tag];
8365 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8367 } else if (tag_ == 1) {
8368 [[self sectionsController] resetView];
8372 case kCydiaTag: _setHomePage(self); break;
8374 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8375 case kChangesTag: [self setPage:[self changesController]]; break;
8376 case kManageTag: [self setPage:[self manageController]]; break;
8377 case kInstalledTag: [self setPage:[self installedController]]; break;
8378 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8379 case kSearchTag: [self setPage:[self searchController]]; break;
8387 - (void) showSettings {
8388 RoleController *role = [[RoleController alloc] initWithDatabase:database_ delegate:self];
8389 CYNavigationController *nav = [[CYNavigationController alloc] initWithRootViewController:role];
8390 if (IsWildcat_) [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8391 [container_ presentModalViewController:nav animated:YES];
8394 - (void) setPackageController:(PackageController *)view {
8396 [view setPackage:nil];
8400 - (PackageController *) _packageController {
8401 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8404 - (PackageController *) packageController {
8405 return [self _packageController];
8408 // Returns the navigation controller for the queuing badge.
8409 - (id) queueBadgeController {
8410 int index = [self indexOfTabWithTag:kManageTag];
8411 if (index == -1) index = [self indexOfTabWithTag:kInstalledTag];
8413 return [[tabbar_ viewControllers] objectAtIndex:index];
8416 - (void) cancelAndClear:(bool)clear {
8417 @synchronized (self) {
8420 pkgCacheFile &cache([database_ cache]);
8421 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
8422 // Unmark method taken from Synaptic Package Manager.
8423 // Thanks for being sane, unlike Aptitude.
8424 if (!cache[iterator].Keep()) {
8425 cache->MarkKeep(iterator, false);
8426 cache->SetReInstall(iterator, false);
8432 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
8436 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8439 // Show the changes in the current view.
8440 [(CYNavigationController *) [tabbar_ selectedViewController] reloadData];
8441 [queueDelegate_ queueStatusDidChange];
8445 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8446 NSString *context([alert context]);
8448 if ([context isEqualToString:@"fixhalf"]) {
8449 if (button == [alert firstOtherButtonIndex]) {
8450 @synchronized (self) {
8451 for (Package *broken in broken_) {
8454 NSString *id = [broken id];
8455 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8456 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8457 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8458 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8464 } else if (button == [alert cancelButtonIndex]) {
8465 [broken_ removeAllObjects];
8469 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8470 } else if ([context isEqualToString:@"upgrade"]) {
8471 if (button == [alert firstOtherButtonIndex]) {
8472 @synchronized (self) {
8473 for (Package *essential in essential_)
8474 [essential install];
8479 } else if (button == [alert firstOtherButtonIndex] + 1) {
8481 } else if (button == [alert cancelButtonIndex]) {
8485 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8489 - (void) system:(NSString *)command { _pooled
8490 system([command UTF8String]);
8493 - (void) applicationWillSuspend {
8495 [super applicationWillSuspend];
8498 - (void) applicationSuspend:(__GSEvent *)event {
8499 // Use external process status API internally.
8500 // This is probably a really bad idea.
8501 uint64_t status = 0;
8503 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8504 notify_get_state(notify_token, &status);
8505 notify_cancel(notify_token);
8508 if (hud_ == nil && status == 0)
8509 [super applicationSuspend:event];
8512 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8514 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8517 - (void) _setSuspended:(BOOL)value {
8519 [super _setSuspended:value];
8522 - (UIProgressHUD *) addProgressHUD {
8523 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8524 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8526 [window_ setUserInteractionEnabled:NO];
8529 UIViewController *target = container_;
8530 while ([target modalViewController] != nil) target = [target modalViewController];
8531 [[target view] addSubview:hud];
8536 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8538 [hud removeFromSuperview];
8539 [window_ setUserInteractionEnabled:YES];
8542 - (CYViewController *) pageForPackage:(NSString *)name {
8543 if (Package *package = [database_ packageWithName:name]) {
8544 PackageController *view([self packageController]);
8545 [view setPackage:package];
8548 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8549 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8550 return [self _pageForURL:url withClass:[CYBrowserController class]];
8554 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8558 NSString *href([url absoluteString]);
8559 if ([href hasPrefix:@"apptapp://package/"])
8560 return [self pageForPackage:[href substringFromIndex:18]];
8562 NSString *scheme([[url scheme] lowercaseString]);
8563 if (![scheme isEqualToString:@"cydia"])
8565 NSString *path([url absoluteString]);
8566 if ([path length] < 8)
8568 path = [path substringFromIndex:8];
8569 if (![path hasPrefix:@"/"])
8570 path = [@"/" stringByAppendingString:path];
8572 if ([path isEqualToString:@"/add-source"])
8573 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8574 else if ([path isEqualToString:@"/storage"])
8575 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8576 else if ([path isEqualToString:@"/sources"])
8577 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8578 else if ([path isEqualToString:@"/packages"])
8579 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8580 else if ([path hasPrefix:@"/url/"])
8581 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8582 else if ([path hasPrefix:@"/launch/"])
8583 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8584 else if ([path hasPrefix:@"/package-settings/"])
8585 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8586 else if ([path hasPrefix:@"/package-signature/"])
8587 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8588 else if ([path hasPrefix:@"/package/"])
8589 return [self pageForPackage:[path substringFromIndex:9]];
8590 else if ([path hasPrefix:@"/files/"]) {
8591 NSString *name = [path substringFromIndex:7];
8593 if (Package *package = [database_ packageWithName:name]) {
8594 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8595 [files setPackage:package];
8603 - (void) applicationOpenURL:(NSURL *)url {
8604 [super applicationOpenURL:url];
8606 if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
8607 [self setPage:page];
8609 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8613 - (void) applicationWillResignActive:(UIApplication *)application {
8614 // Stop refreshing if you get a phone call or lock the device.
8615 if ([container_ updating]) [container_ cancelUpdate];
8617 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8618 [super applicationWillResignActive:application];
8621 - (void) addStashController {
8622 stash_ = [[CYStashController alloc] init];
8623 [window_ addSubview:[stash_ view]];
8626 - (void) removeStashController {
8627 [[stash_ view] removeFromSuperview];
8632 [self setIdleTimerDisabled:YES];
8634 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8635 [self setStatusBarShowsProgress:YES];
8636 UpdateExternalStatus(1);
8638 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8640 UpdateExternalStatus(0);
8641 [self setStatusBarShowsProgress:NO];
8643 [self removeStashController];
8645 if (ExecFork() == 0) {
8646 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8647 perror("launchctl stop");
8651 - (void) setupTabBarController {
8652 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8653 [tabbar_ setDelegate:self];
8655 NSMutableArray *items([NSMutableArray arrayWithObjects:
8656 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8657 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8658 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8659 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8663 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8664 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8666 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8669 NSMutableArray *controllers([NSMutableArray array]);
8671 for (UITabBarItem *item in items) {
8672 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8673 [controller setTabBarItem:item];
8674 [controllers addObject:controller];
8677 [tabbar_ setViewControllers:controllers];
8678 [tabbar_ setSelectedIndex:0];
8681 - (void) applicationDidFinishLaunching:(id)unused {
8682 [CYBrowserController _initialize];
8684 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8686 Font12_ = [[UIFont systemFontOfSize:12] retain];
8687 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8688 Font14_ = [[UIFont systemFontOfSize:14] retain];
8689 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8690 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8694 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8695 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8697 UIScreen *screen([UIScreen mainScreen]);
8699 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8700 [window_ orderFront:self];
8701 [window_ makeKey:self];
8702 [window_ setHidden:NO];
8705 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8706 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8707 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8708 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8709 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8710 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8711 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8712 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8713 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8716 [self addStashController];
8717 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8721 database_ = [Database sharedInstance];
8723 [self setupTabBarController];
8725 container_ = [[CYContainer alloc] initWithDatabase:database_];
8726 [container_ setUpdateDelegate:self];
8727 [container_ setTabBarController:tabbar_];
8728 [window_ addSubview:[container_ view]];
8730 // Show pinstripes while loading data.
8731 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8733 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8738 [self showSettings];
8742 [window_ setUserInteractionEnabled:NO];
8744 UIView *container = [[UIView alloc] init];
8745 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8747 UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
8748 [spinner startAnimating];
8749 [container addSubview:spinner];
8752 UILabel *label = [[UILabel alloc] init];
8753 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8754 [label setBackgroundColor:[UIColor clearColor]];
8755 [label setTextColor:[UIColor blackColor]];
8756 [label setShadowColor:[UIColor whiteColor]];
8757 [label setShadowOffset:CGSizeMake(0, 1)];
8758 [label setText:UCLocalize("LOADING_DATA")];
8759 [container addSubview:label];
8762 CGSize viewsize = [[tabbar_ view] frame].size;
8763 CGSize spinnersize = [spinner bounds].size;
8764 CGSize textsize = [[label text] sizeWithFont:[label font]];
8765 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8767 CGRect containrect = {
8768 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8769 CGSizeMake(bothwidth, spinnersize.height)
8772 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8780 [container setFrame:containrect];
8781 [spinner setFrame:spinrect];
8782 [label setFrame:textrect];
8783 [[container_ view] addSubview:container];
8784 [container release];
8789 // Show the home page
8791 [window_ setUserInteractionEnabled:YES];
8793 // XXX: does this actually slow anything down?
8794 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8795 [container removeFromSuperview];
8798 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8799 if (item != nil && IsWildcat_) {
8800 [sheet showFromBarButtonItem:item animated:YES];
8802 [sheet showInView:window_];
8809 id Alloc_(id self, SEL selector) {
8810 id object = alloc_(self, selector);
8811 lprintf("[%s]A-%p\n", self->isa->name, object);
8816 id Dealloc_(id self, SEL selector) {
8817 id object = dealloc_(self, selector);
8818 lprintf("[%s]D-%p\n", self->isa->name, object);
8822 Class $WebDefaultUIKitDelegate;
8824 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8825 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8826 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8827 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8830 static NSNumber *shouldPlayKeyboardSounds;
8834 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8836 case 1104: // Keyboard Button Clicked
8837 case 1105: // Keyboard Delete Repeated
8838 if (shouldPlayKeyboardSounds == nil) {
8839 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8840 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8843 if (![shouldPlayKeyboardSounds boolValue])
8847 _UIHardware$_playSystemSound$(self, _cmd, sound);
8851 int main(int argc, char *argv[]) { _pooled
8854 if (Class $UIDevice = objc_getClass("UIDevice")) {
8855 UIDevice *device([$UIDevice currentDevice]);
8856 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8860 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8862 /* Library Hacks {{{ */
8863 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8865 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8866 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8867 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8868 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8869 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8872 $UIHardware = objc_getClass("UIHardware");
8873 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8874 if (UIHardware$_playSystemSound$ != NULL) {
8875 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8876 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8879 /* Set Locale {{{ */
8880 Locale_ = CFLocaleCopyCurrent();
8881 Languages_ = [NSLocale preferredLanguages];
8882 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8883 //NSLog(@"%@", [Languages_ description]);
8886 if (Languages_ == nil || [Languages_ count] == 0)
8887 // XXX: consider just setting to C and then falling through?
8890 lang = [[Languages_ objectAtIndex:0] UTF8String];
8891 setenv("LANG", lang, true);
8894 //std::setlocale(LC_ALL, lang);
8895 NSLog(@"Setting Language: %s", lang);
8898 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8900 /* Parse Arguments {{{ */
8901 bool substrate(false);
8907 for (int argi(1); argi != argc; ++argi)
8908 if (strcmp(argv[argi], "--") == 0) {
8910 argv[argi] = argv[0];
8916 for (int argi(1); argi != arge; ++argi)
8917 if (strcmp(args[argi], "--substrate") == 0)
8920 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8924 App_ = [[NSBundle mainBundle] bundlePath];
8925 Home_ = NSHomeDirectory();
8931 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8932 alloc_ = alloc->method_imp;
8933 alloc->method_imp = (IMP) &Alloc_;*/
8935 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8936 dealloc_ = dealloc->method_imp;
8937 dealloc->method_imp = (IMP) &Dealloc_;*/
8939 /* System Information {{{ */
8943 size = sizeof(maxproc);
8944 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8945 perror("sysctlbyname(\"kern.maxproc\", ?)");
8946 else if (maxproc < 64) {
8948 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8949 perror("sysctlbyname(\"kern.maxproc\", #)");
8952 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8953 char *osversion = new char[size];
8954 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8955 perror("sysctlbyname(\"kern.osversion\", ?)");
8957 System_ = [NSString stringWithUTF8String:osversion];
8959 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8960 char *machine = new char[size];
8961 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8962 perror("sysctlbyname(\"hw.machine\", ?)");
8966 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8967 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8968 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8969 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8973 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8974 NSData *data((NSData *) ecid);
8975 size_t length([data length]);
8976 uint8_t bytes[length];
8977 [data getBytes:bytes];
8978 char string[length * 2 + 1];
8979 for (size_t i(0); i != length; ++i)
8980 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8981 ChipID_ = [NSString stringWithUTF8String:string];
8985 IOObjectRelease(service);
8989 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8991 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
8992 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
8993 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
8995 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
8996 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
8997 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
8999 if (mcc != NULL && mnc != NULL)
9000 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9007 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9008 Build_ = [system objectForKey:@"ProductBuildVersion"];
9009 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9010 Product_ = [info objectForKey:@"SafariProductVersion"];
9011 Safari_ = [info objectForKey:@"CFBundleVersion"];
9014 /* Load Database {{{ */
9016 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9018 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9021 if (Metadata_ == NULL)
9022 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9024 Settings_ = [Metadata_ objectForKey:@"Settings"];
9026 Packages_ = [Metadata_ objectForKey:@"Packages"];
9027 Sections_ = [Metadata_ objectForKey:@"Sections"];
9028 Sources_ = [Metadata_ objectForKey:@"Sources"];
9030 Token_ = [Metadata_ objectForKey:@"Token"];
9033 if (Settings_ != nil)
9034 Role_ = [Settings_ objectForKey:@"Role"];
9036 if (Packages_ == nil) {
9037 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
9038 [Metadata_ setObject:Packages_ forKey:@"Packages"];
9041 if (Sections_ == nil) {
9042 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9043 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9046 if (Sources_ == nil) {
9047 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9048 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9052 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9054 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9055 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9056 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9057 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9058 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9059 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9061 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9063 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9064 unlink("/tmp/.cydia.fw");
9066 } else if (access("/User", F_OK) != 0 || version < 2) {
9069 system("/usr/libexec/cydia/firmware.sh");
9073 _assert([[NSFileManager defaultManager]
9074 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9075 withIntermediateDirectories:YES
9080 if (access("/tmp/cydia.chk", F_OK) == 0) {
9081 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9082 _assert(errno == ENOENT);
9083 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9084 _assert(errno == ENOENT);
9087 /* APT Initialization {{{ */
9088 _assert(pkgInitConfig(*_config));
9089 _assert(pkgInitSystem(*_config, _system));
9092 _config->Set("APT::Acquire::Translation", lang);
9094 // XXX: this timeout might be important :(
9095 //_config->Set("Acquire::http::Timeout", 15);
9097 _config->Set("Acquire::http::MaxParallel", 3);
9099 /* Color Choices {{{ */
9100 space_ = CGColorSpaceCreateDeviceRGB();
9102 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9103 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9104 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9105 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9106 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9107 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9108 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9109 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9110 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9112 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9113 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9115 /* UIKit Configuration {{{ */
9116 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9117 if ($GSFontSetUseLegacyFontMetrics != NULL)
9118 $GSFontSetUseLegacyFontMetrics(YES);
9120 // XXX: I have a feeling this was important
9121 //UIKeyboardDisableAutomaticAppearance();
9124 Colon_ = UCLocalize("COLON_DELIMITED");
9125 Error_ = UCLocalize("ERROR");
9126 Warning_ = UCLocalize("WARNING");
9129 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9131 CGColorSpaceRelease(space_);