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 size_t size(strlen(data));
1076 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
1077 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
1080 const char *StripVersion_(const char *version) {
1081 const char *colon(strchr(version, ':'));
1083 version = colon + 1;
1087 CFStringRef StripVersion(const char *version) {
1088 const char *colon(strchr(version, ':'));
1090 version = colon + 1;
1091 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1093 return CFCString(version);
1096 NSString *LocalizeSection(NSString *section) {
1097 static Pcre title_r("^(.*?) \\((.*)\\)$");
1098 if (title_r(section)) {
1099 NSString *parent(title_r[1]);
1100 NSString *child(title_r[2]);
1102 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1103 LocalizeSection(parent),
1104 LocalizeSection(child)
1108 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1111 NSString *Simplify(NSString *title) {
1112 const char *data = [title UTF8String];
1113 size_t size = [title length];
1115 static Pcre square_r("^\\[(.*)\\]$");
1116 if (square_r(data, size))
1117 return Simplify(square_r[1]);
1119 static Pcre paren_r("^\\((.*)\\)$");
1120 if (paren_r(data, size))
1121 return Simplify(paren_r[1]);
1123 static Pcre title_r("^(.*?) \\((.*)\\)$");
1124 if (title_r(data, size))
1125 return Simplify(title_r[1]);
1131 NSString *GetLastUpdate() {
1132 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1135 return UCLocalize("NEVER_OR_UNKNOWN");
1137 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1138 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1140 CFRelease(formatter);
1142 return [(NSString *) formatted autorelease];
1145 bool isSectionVisible(NSString *section) {
1146 NSDictionary *metadata([Sections_ objectForKey:section]);
1147 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1148 return hidden == nil || ![hidden boolValue];
1153 /* Delegate Prototypes {{{ */
1157 @interface NSObject (ProgressDelegate)
1160 @protocol ProgressDelegate
1161 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1162 - (void) setProgressTitle:(NSString *)title;
1163 - (void) setProgressPercent:(float)percent;
1164 - (void) startProgress;
1165 - (void) addProgressOutput:(NSString *)output;
1166 - (bool) isCancelling:(size_t)received;
1169 @protocol ConfigurationDelegate
1170 - (void) repairWithSelector:(SEL)selector;
1171 - (void) setConfigurationData:(NSString *)data;
1174 @class PackageController;
1176 @protocol CydiaDelegate
1177 - (void) setPackageController:(PackageController *)view;
1178 - (void) clearPackage:(Package *)package;
1179 - (void) installPackage:(Package *)package;
1180 - (void) installPackages:(NSArray *)packages;
1181 - (void) removePackage:(Package *)package;
1182 - (void) beginUpdate;
1184 - (void) distUpgrade;
1186 - (void) updateData;
1188 - (void) showSettings;
1189 - (UIProgressHUD *) addProgressHUD;
1190 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1191 - (CYViewController *) pageForPackage:(NSString *)name;
1192 - (PackageController *) packageController;
1193 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1197 /* Status Delegation {{{ */
1199 public pkgAcquireStatus
1202 _transient NSObject<ProgressDelegate> *delegate_;
1210 void setDelegate(id delegate) {
1211 delegate_ = delegate;
1214 NSObject<ProgressDelegate> *getDelegate() const {
1218 virtual bool MediaChange(std::string media, std::string drive) {
1222 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1225 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1226 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1227 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1230 virtual void Done(pkgAcquire::ItemDesc &item) {
1233 virtual void Fail(pkgAcquire::ItemDesc &item) {
1235 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1236 item.Owner->Status == pkgAcquire::Item::StatDone
1240 std::string &error(item.Owner->ErrorText);
1244 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1245 NSArray *fields([description componentsSeparatedByString:@" "]);
1246 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1248 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1249 withObject:[NSArray arrayWithObjects:
1250 [NSString stringWithUTF8String:error.c_str()],
1257 virtual bool Pulse(pkgAcquire *Owner) {
1258 bool value = pkgAcquireStatus::Pulse(Owner);
1261 double(CurrentBytes + CurrentItems) /
1262 double(TotalBytes + TotalItems)
1265 [delegate_ setProgressPercent:percent];
1266 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1269 virtual void Start() {
1270 [delegate_ startProgress];
1273 virtual void Stop() {
1277 /* Progress Delegation {{{ */
1282 _transient id<ProgressDelegate> delegate_;
1286 virtual void Update() {
1287 /*if (abs(Percent - percent_) > 2)
1288 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1292 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1293 [delegate_ setProgressPercent:(Percent / 100)];*/
1303 void setDelegate(id delegate) {
1304 delegate_ = delegate;
1307 id getDelegate() const {
1311 virtual void Done() {
1313 //[delegate_ setProgressPercent:1];
1318 /* Database Interface {{{ */
1319 typedef std::map< unsigned long, _H<Source> > SourceMap;
1321 @interface Database : NSObject {
1327 pkgCacheFile cache_;
1328 pkgDepCache::Policy *policy_;
1329 pkgRecords *records_;
1330 pkgProblemResolver *resolver_;
1331 pkgAcquire *fetcher_;
1333 SPtr<pkgPackageManager> manager_;
1334 pkgSourceList *list_;
1337 CFMutableArrayRef packages_;
1339 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1348 + (Database *) sharedInstance;
1351 - (void) _readCydia:(NSNumber *)fd;
1352 - (void) _readStatus:(NSNumber *)fd;
1353 - (void) _readOutput:(NSNumber *)fd;
1357 - (Package *) packageWithName:(NSString *)name;
1359 - (pkgCacheFile &) cache;
1360 - (pkgDepCache::Policy *) policy;
1361 - (pkgRecords *) records;
1362 - (pkgProblemResolver *) resolver;
1363 - (pkgAcquire &) fetcher;
1364 - (pkgSourceList &) list;
1365 - (NSArray *) packages;
1366 - (NSArray *) sources;
1367 - (void) reloadData;
1375 - (void) setVisible;
1377 - (void) updateWithStatus:(Status &)status;
1379 - (void) setDelegate:(id)delegate;
1380 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1383 /* Delegate Helpers {{{ */
1384 @implementation NSObject (ProgressDelegate)
1386 - (void) _setProgressErrorPackage:(NSArray *)args {
1387 [self performSelector:@selector(setProgressError:forPackage:)
1388 withObject:[args objectAtIndex:0]
1389 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1393 - (void) _setProgressErrorTitle:(NSArray *)args {
1394 [self performSelector:@selector(setProgressError:withTitle:)
1395 withObject:[args objectAtIndex:0]
1396 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1400 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1401 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1402 withObject:[NSArray arrayWithObjects:error, title, nil]
1407 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1408 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1410 [self performSelector:@selector(setProgressError:withTitle:)
1412 withObject:(package == nil ? id : [package name])
1419 /* Source Class {{{ */
1420 @interface Source : NSObject {
1421 CYString depiction_;
1422 CYString description_;
1428 CYString distribution_;
1433 NSString *authority_;
1435 CYString defaultIcon_;
1437 NSDictionary *record_;
1441 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1443 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1445 - (NSString *) depictionForPackage:(NSString *)package;
1446 - (NSString *) supportForPackage:(NSString *)package;
1448 - (NSDictionary *) record;
1452 - (NSString *) distribution;
1453 - (NSString *) type;
1455 - (NSString *) host;
1457 - (NSString *) name;
1458 - (NSString *) description;
1459 - (NSString *) label;
1460 - (NSString *) origin;
1461 - (NSString *) version;
1463 - (NSString *) defaultIcon;
1467 @implementation Source
1471 distribution_.clear();
1474 description_.clear();
1480 defaultIcon_.clear();
1482 if (record_ != nil) {
1492 if (authority_ != nil) {
1493 [authority_ release];
1503 + (NSArray *) _attributeKeys {
1504 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1507 - (NSArray *) attributeKeys {
1508 return [[self class] _attributeKeys];
1511 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1512 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1515 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1518 trusted_ = index->IsTrusted();
1520 uri_.set(pool, index->GetURI());
1521 distribution_.set(pool, index->GetDist());
1522 type_.set(pool, index->GetType());
1524 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1525 if (dindex != NULL) {
1527 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1530 pkgTagFile tags(&fd);
1532 pkgTagSection section;
1539 {"default-icon", &defaultIcon_},
1540 {"depiction", &depiction_},
1541 {"description", &description_},
1543 {"origin", &origin_},
1544 {"support", &support_},
1545 {"version", &version_},
1548 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1549 const char *start, *end;
1551 if (section.Find(names[i].name_, start, end)) {
1552 CYString &value(*names[i].value_);
1553 value.set(pool, start, end - start);
1559 record_ = [Sources_ objectForKey:[self key]];
1561 record_ = [record_ retain];
1563 NSURL *url([NSURL URLWithString:uri_]);
1567 host_ = [[host_ lowercaseString] retain];
1572 authority_ = [url path];
1574 if (authority_ != nil)
1575 authority_ = [authority_ retain];
1578 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1579 if ((self = [super init]) != nil) {
1580 [self setMetaIndex:index inPool:pool];
1584 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1585 NSDictionary *lhr = [self record];
1586 NSDictionary *rhr = [source record];
1589 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1591 NSString *lhs = [self name];
1592 NSString *rhs = [source name];
1594 if ([lhs length] != 0 && [rhs length] != 0) {
1595 unichar lhc = [lhs characterAtIndex:0];
1596 unichar rhc = [rhs characterAtIndex:0];
1598 if (isalpha(lhc) && !isalpha(rhc))
1599 return NSOrderedAscending;
1600 else if (!isalpha(lhc) && isalpha(rhc))
1601 return NSOrderedDescending;
1604 return [lhs compare:rhs options:LaxCompareOptions_];
1607 - (NSString *) depictionForPackage:(NSString *)package {
1608 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1611 - (NSString *) supportForPackage:(NSString *)package {
1612 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1615 - (NSDictionary *) record {
1623 - (NSString *) uri {
1627 - (NSString *) distribution {
1628 return distribution_;
1631 - (NSString *) type {
1635 - (NSString *) key {
1636 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1639 - (NSString *) host {
1643 - (NSString *) name {
1644 return origin_.empty() ? authority_ : origin_;
1647 - (NSString *) description {
1648 return description_;
1651 - (NSString *) label {
1652 return label_.empty() ? authority_ : label_;
1655 - (NSString *) origin {
1659 - (NSString *) version {
1663 - (NSString *) defaultIcon {
1664 return defaultIcon_;
1669 /* Relationship Class {{{ */
1670 @interface Relationship : NSObject {
1675 - (NSString *) type;
1677 - (NSString *) name;
1681 @implementation Relationship
1689 - (NSString *) type {
1697 - (NSString *) name {
1704 /* Package Class {{{ */
1705 @interface Package : NSObject {
1709 pkgCache::VerIterator version_;
1710 pkgCache::PkgIterator iterator_;
1711 _transient Database *database_;
1712 pkgCache::VerFileIterator file_;
1719 NSString *section$_;
1726 CYString installed_;
1732 CYString depiction_;
1743 NSMutableArray *tags_;
1746 NSArray *relationships_;
1748 NSMutableDictionary *metadata_;
1749 _transient NSDate *firstSeen_;
1750 _transient NSDate *lastSeen_;
1754 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1755 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1757 - (pkgCache::PkgIterator) iterator;
1760 - (NSString *) section;
1761 - (NSString *) simpleSection;
1763 - (NSString *) longSection;
1764 - (NSString *) shortSection;
1768 - (Address *) maintainer;
1770 - (NSString *) longDescription;
1771 - (NSString *) shortDescription;
1774 - (NSMutableDictionary *) metadata;
1776 - (BOOL) subscribed;
1779 - (NSString *) latest;
1780 - (NSString *) installed;
1781 - (BOOL) uninstalled;
1784 - (BOOL) upgradableAndEssential:(BOOL)essential;
1787 - (BOOL) unfiltered;
1791 - (BOOL) halfConfigured;
1792 - (BOOL) halfInstalled;
1794 - (NSString *) mode;
1796 - (void) setVisible;
1799 - (NSString *) name;
1801 - (NSString *) homepage;
1802 - (NSString *) depiction;
1803 - (Address *) author;
1805 - (NSString *) support;
1807 - (NSArray *) files;
1808 - (NSArray *) relationships;
1809 - (NSArray *) warnings;
1810 - (NSArray *) applications;
1812 - (Source *) source;
1813 - (NSString *) role;
1815 - (BOOL) matches:(NSString *)text;
1817 - (bool) hasSupportingRole;
1818 - (BOOL) hasTag:(NSString *)tag;
1819 - (NSString *) primaryPurpose;
1820 - (NSArray *) purposes;
1821 - (bool) isCommercial;
1823 - (CYString &) cyname;
1825 - (uint32_t) compareBySection:(NSArray *)sections;
1827 - (uint32_t) compareForChanges;
1832 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1833 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1834 - (bool) isInstalledAndVisible:(NSNumber *)number;
1835 - (bool) isVisibleInSection:(NSString *)section;
1836 - (bool) isVisibleInSource:(Source *)source;
1840 uint32_t PackageChangesRadix(Package *self, void *) {
1845 uint32_t timestamp : 30;
1846 uint32_t ignored : 1;
1847 uint32_t upgradable : 1;
1851 bool upgradable([self upgradableAndEssential:YES]);
1852 value.bits.upgradable = upgradable ? 1 : 0;
1855 value.bits.timestamp = 0;
1856 value.bits.ignored = [self ignored] ? 0 : 1;
1857 value.bits.upgradable = 1;
1859 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1860 value.bits.ignored = 0;
1861 value.bits.upgradable = 0;
1864 return _not(uint32_t) - value.key;
1867 _finline static void Stifle(uint8_t &value) {
1870 uint32_t PackagePrefixRadix(Package *self, void *context) {
1871 size_t offset(reinterpret_cast<size_t>(context));
1872 CYString &name([self cyname]);
1874 size_t size(name.size());
1877 char *text(name.data());
1880 if (!isdigit(text[0]))
1884 while (size != digits && isdigit(text[digits]))
1894 if (offset == 0 && zeros != 0) {
1895 memset(data, '0', zeros);
1896 memcpy(data + zeros, text, 4 - zeros);
1898 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1899 if (size <= offset - zeros)
1902 text += offset - zeros;
1903 size -= offset - zeros;
1906 memcpy(data, text, 4);
1908 memcpy(data, text, size);
1909 memset(data + size, 0, 4 - size);
1912 for (size_t i(0); i != 4; ++i)
1913 if (isalpha(data[i]))
1921 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1923 /* XXX: ntohl may be more honest */
1924 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1927 CYString &(*PackageName)(Package *self, SEL sel);
1929 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1930 _profile(PackageNameCompare)
1931 CYString &lhi(PackageName(lhs, @selector(cyname)));
1932 CYString &rhi(PackageName(rhs, @selector(cyname)));
1933 CFStringRef lhn(lhi), rhn(rhi);
1936 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1937 else if (rhn == NULL)
1938 return NSOrderedDescending;
1940 _profile(PackageNameCompare$NumbersLast)
1941 if (!lhi.empty() && !rhi.empty()) {
1942 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1943 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1944 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1945 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1946 return lha ? NSOrderedAscending : NSOrderedDescending;
1950 CFIndex length = CFStringGetLength(lhn);
1952 _profile(PackageNameCompare$Compare)
1953 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1958 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1959 return PackageNameCompare(*lhs, *rhs, context);
1962 struct PackageNameOrdering :
1963 std::binary_function<Package *, Package *, bool>
1965 _finline bool operator ()(Package *lhs, Package *rhs) const {
1966 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1970 @implementation Package
1972 - (NSString *) description {
1973 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1979 if (section$_ != nil)
1980 [section$_ release];
1985 if (sponsor$_ != nil)
1986 [sponsor$_ release];
1987 if (author$_ != nil)
1994 if (relationships_ != nil)
1995 [relationships_ release];
1996 if (metadata_ != nil)
1997 [metadata_ release];
2002 + (NSString *) webScriptNameForSelector:(SEL)selector {
2003 if (selector == @selector(hasTag:))
2009 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2010 return [self webScriptNameForSelector:selector] == nil;
2013 + (NSArray *) _attributeKeys {
2014 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];
2017 - (NSArray *) attributeKeys {
2018 return [[self class] _attributeKeys];
2021 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2022 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2032 _profile(Package$parse)
2033 pkgRecords::Parser *parser;
2035 _profile(Package$parse$Lookup)
2036 parser = &[database_ records]->Lookup(file_);
2041 _profile(Package$parse$Find)
2047 {"depiction", &depiction_},
2048 {"homepage", &homepage_},
2049 {"website", &website},
2051 {"support", &support_},
2052 {"sponsor", &sponsor_},
2053 {"author", &author_},
2056 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2057 const char *start, *end;
2059 if (parser->Find(names[i].name_, start, end)) {
2060 CYString &value(*names[i].value_);
2061 _profile(Package$parse$Value)
2062 value.set(pool_, start, end - start);
2068 _profile(Package$parse$Tagline)
2069 const char *start, *end;
2070 if (parser->ShortDesc(start, end)) {
2071 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2074 while (stop != start && stop[-1] == '\r')
2076 tagline_.set(pool_, start, stop - start);
2080 _profile(Package$parse$Retain)
2081 if (homepage_.empty())
2082 homepage_ = website;
2083 if (homepage_ == depiction_)
2089 - (void) setVisible {
2090 visible_ = required_ && [self unfiltered];
2093 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2094 if ((self = [super init]) != nil) {
2095 _profile(Package$initWithVersion)
2096 era_ = [database era];
2100 iterator_ = version.ParentPkg();
2101 database_ = database;
2103 _profile(Package$initWithVersion$Latest)
2104 latest_ = (NSString *) StripVersion(version_.VerStr());
2107 pkgCache::VerIterator current;
2108 _profile(Package$initWithVersion$Versions)
2109 current = iterator_.CurrentVer();
2111 installed_.set(pool_, StripVersion_(current.VerStr()));
2113 if (!version_.end())
2114 file_ = version_.FileList();
2116 pkgCache &cache([database_ cache]);
2117 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2121 _profile(Package$initWithVersion$Name)
2122 id_.set(pool_, iterator_.Name());
2123 name_.set(pool, iterator_.Display());
2126 _profile(Package$lowercaseString)
2127 char *data(id_.data());
2128 for (size_t i(0), e(id_.size()); i != e; ++i)
2129 // XXX: do not use tolower() as this is not locale-specific? :(
2134 _profile(Package$initWithVersion$Source)
2135 source_ = [database_ getSource:file_.File()];
2144 _profile(Package$initWithVersion$Tags)
2145 pkgCache::TagIterator tag(iterator_.TagList());
2147 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2149 const char *name(tag.Name());
2150 [tags_ addObject:(NSString *)CFCString(name)];
2151 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2152 role_ = (NSString *) CFCString(name + 6);
2153 if (required_ && strncmp(name, "require::", 9) == 0 && (
2158 } while (!tag.end());
2162 bool changed(false);
2164 _profile(Package$initWithVersion$Metadata)
2165 metadata_ = [Packages_ objectForKey:id_];
2167 if (metadata_ == nil) {
2170 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2171 firstSeen_, @"FirstSeen",
2172 latest_, @"LastVersion",
2177 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2178 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2180 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2181 subscribed_ = [subscribed boolValue];
2183 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2185 if (firstSeen_ == nil) {
2186 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2187 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2191 if (version == nil) {
2192 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2194 } else if (![version isEqualToString:latest_]) {
2195 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2197 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2202 metadata_ = [metadata_ retain];
2205 [Packages_ setObject:metadata_ forKey:id_];
2210 _profile(Package$initWithVersion$Section)
2211 section_.set(pool_, iterator_.Section());
2214 obsolete_ = [self hasTag:@"cydia::obsolete"];
2215 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2220 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2221 pkgCache::VerIterator version;
2223 _profile(Package$packageWithIterator$GetCandidateVer)
2224 version = [database policy]->GetCandidateVer(iterator);
2230 return [[[Package alloc]
2231 initWithVersion:version
2238 - (pkgCache::PkgIterator) iterator {
2242 - (NSString *) section {
2243 if (section$_ == nil) {
2244 if (section_.empty())
2247 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2248 NSString *name(section_);
2251 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2252 if (NSString *rename = [value objectForKey:@"Rename"]) {
2257 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2261 - (NSString *) simpleSection {
2262 if (NSString *section = [self section])
2263 return Simplify(section);
2268 - (NSString *) longSection {
2269 return LocalizeSection([self section]);
2272 - (NSString *) shortSection {
2273 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2276 - (NSString *) uri {
2279 pkgIndexFile *index;
2280 pkgCache::PkgFileIterator file(file_.File());
2281 if (![database_ list].FindIndex(file, index))
2283 return [NSString stringWithUTF8String:iterator_->Path];
2284 //return [NSString stringWithUTF8String:file.Site()];
2285 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2289 - (Address *) maintainer {
2292 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2293 const std::string &maintainer(parser->Maintainer());
2294 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2298 return version_.end() ? 0 : version_->InstalledSize;
2301 - (NSString *) longDescription {
2302 @synchronized (database_) {
2303 if ([database_ era] != era_ || file_.end())
2306 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2307 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2309 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2310 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2311 if ([lines count] < 2)
2314 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2315 for (size_t i(1), e([lines count]); i != e; ++i) {
2316 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2317 [trimmed addObject:trim];
2320 return [trimmed componentsJoinedByString:@"\n"];
2323 - (NSString *) shortDescription {
2328 _profile(Package$index)
2329 CFStringRef name((CFStringRef) [self name]);
2330 if (CFStringGetLength(name) == 0)
2332 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2333 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2335 return toupper(character);
2339 - (NSMutableDictionary *) metadata {
2344 if (subscribed_ && lastSeen_ != nil)
2349 - (BOOL) subscribed {
2354 NSDictionary *metadata([self metadata]);
2355 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2356 return [ignored boolValue];
2361 - (NSString *) latest {
2365 - (NSString *) installed {
2369 - (BOOL) uninstalled {
2370 return installed_.empty();
2374 return !version_.end();
2377 - (BOOL) upgradableAndEssential:(BOOL)essential {
2378 _profile(Package$upgradableAndEssential)
2379 pkgCache::VerIterator current(iterator_.CurrentVer());
2381 return essential && essential_ && visible_;
2383 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2387 - (BOOL) essential {
2392 return [database_ cache][iterator_].InstBroken();
2395 - (BOOL) unfiltered {
2396 NSString *section([self section]);
2397 return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
2405 unsigned char current(iterator_->CurrentState);
2406 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2409 - (BOOL) halfConfigured {
2410 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2413 - (BOOL) halfInstalled {
2414 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2418 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2419 return state.Mode != pkgDepCache::ModeKeep;
2422 - (NSString *) mode {
2423 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2425 switch (state.Mode) {
2426 case pkgDepCache::ModeDelete:
2427 if ((state.iFlags & pkgDepCache::Purge) != 0)
2431 case pkgDepCache::ModeKeep:
2432 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2433 return @"REINSTALL";
2434 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2438 case pkgDepCache::ModeInstall:
2439 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2440 return @"REINSTALL";
2441 else*/ switch (state.Status) {
2443 return @"DOWNGRADE";
2449 return @"NEW_INSTALL";
2460 - (NSString *) name {
2461 return name_.empty() ? id_ : name_;
2464 - (UIImage *) icon {
2465 NSString *section = [self simpleSection];
2469 if ([static_cast<id>(icon_) hasPrefix:@"file:///"])
2470 // XXX: correct escaping
2471 icon = [UIImage imageAtPath:[static_cast<id>(icon_) substringFromIndex:7]];
2472 if (icon == nil) if (section != nil)
2473 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2474 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2475 if ([dicon hasPrefix:@"file:///"])
2476 // XXX: correct escaping
2477 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2479 icon = [UIImage applicationImageNamed:@"unknown.png"];
2483 - (NSString *) homepage {
2487 - (NSString *) depiction {
2488 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2491 - (Address *) sponsor {
2492 if (sponsor$_ == nil) {
2493 if (sponsor_.empty())
2495 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2499 - (Address *) author {
2500 if (author$_ == nil) {
2501 if (author_.empty())
2503 author$_ = [[Address addressWithString:author_] retain];
2507 - (NSString *) support {
2508 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2511 - (NSArray *) files {
2512 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2513 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2516 fin.open([path UTF8String]);
2521 while (std::getline(fin, line))
2522 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2527 - (NSArray *) relationships {
2528 return relationships_;
2531 - (NSArray *) warnings {
2532 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2533 const char *name(iterator_.Name());
2535 size_t length(strlen(name));
2536 if (length < 2) invalid:
2537 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2538 else for (size_t i(0); i != length; ++i)
2540 /* XXX: technically this is not allowed */
2541 (name[i] < 'A' || name[i] > 'Z') &&
2542 (name[i] < 'a' || name[i] > 'z') &&
2543 (name[i] < '0' || name[i] > '9') &&
2544 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2547 if (strcmp(name, "cydia") != 0) {
2550 bool _private = false;
2553 bool repository = [[self section] isEqualToString:@"Repositories"];
2555 if (NSArray *files = [self files])
2556 for (NSString *file in files)
2557 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2559 else if (!user && [file isEqualToString:@"/User"])
2561 else if (!_private && [file isEqualToString:@"/private"])
2563 else if (!stash && [file isEqualToString:@"/var/stash"])
2566 /* XXX: this is not sensitive enough. only some folders are valid. */
2567 if (cydia && !repository)
2568 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2570 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2572 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2574 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2577 return [warnings count] == 0 ? nil : warnings;
2580 - (NSArray *) applications {
2581 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2583 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2585 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2586 if (NSArray *files = [self files])
2587 for (NSString *file in files)
2588 if (application_r(file)) {
2589 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2590 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2591 if ([id isEqualToString:me])
2594 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2596 display = application_r[1];
2598 NSString *bundle([file stringByDeletingLastPathComponent]);
2599 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2600 if (icon == nil || [icon length] == 0)
2602 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2604 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2605 [applications addObject:application];
2607 [application addObject:id];
2608 [application addObject:display];
2609 [application addObject:url];
2612 return [applications count] == 0 ? nil : applications;
2615 - (Source *) source {
2617 @synchronized (database_) {
2618 if ([database_ era] != era_ || file_.end())
2621 source_ = [database_ getSource:file_.File()];
2633 - (NSString *) role {
2637 - (BOOL) matches:(NSString *)text {
2643 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2644 if (range.location != NSNotFound)
2647 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2648 if (range.location != NSNotFound)
2651 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2652 if (range.location != NSNotFound)
2658 - (bool) hasSupportingRole {
2661 if ([role_ isEqualToString:@"enduser"])
2663 if ([Role_ isEqualToString:@"User"])
2665 if ([role_ isEqualToString:@"hacker"])
2667 if ([Role_ isEqualToString:@"Hacker"])
2669 if ([role_ isEqualToString:@"developer"])
2671 if ([Role_ isEqualToString:@"Developer"])
2676 - (BOOL) hasTag:(NSString *)tag {
2677 return tags_ == nil ? NO : [tags_ containsObject:tag];
2680 - (NSString *) primaryPurpose {
2681 for (NSString *tag in tags_)
2682 if ([tag hasPrefix:@"purpose::"])
2683 return [tag substringFromIndex:9];
2687 - (NSArray *) purposes {
2688 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2689 for (NSString *tag in tags_)
2690 if ([tag hasPrefix:@"purpose::"])
2691 [purposes addObject:[tag substringFromIndex:9]];
2692 return [purposes count] == 0 ? nil : purposes;
2695 - (bool) isCommercial {
2696 return [self hasTag:@"cydia::commercial"];
2699 - (CYString &) cyname {
2700 return name_.empty() ? id_ : name_;
2703 - (uint32_t) compareBySection:(NSArray *)sections {
2704 NSString *section([self section]);
2705 for (size_t i(0), e([sections count]); i != e; ++i) {
2706 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2710 return _not(uint32_t);
2713 - (uint32_t) compareForChanges {
2718 uint32_t timestamp : 30;
2719 uint32_t ignored : 1;
2720 uint32_t upgradable : 1;
2724 bool upgradable([self upgradableAndEssential:YES]);
2725 value.bits.upgradable = upgradable ? 1 : 0;
2728 value.bits.timestamp = 0;
2729 value.bits.ignored = [self ignored] ? 0 : 1;
2730 value.bits.upgradable = 1;
2732 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2733 value.bits.ignored = 0;
2734 value.bits.upgradable = 0;
2737 return _not(uint32_t) - value.key;
2741 pkgProblemResolver *resolver = [database_ resolver];
2742 resolver->Clear(iterator_);
2743 resolver->Protect(iterator_);
2747 pkgProblemResolver *resolver = [database_ resolver];
2748 resolver->Clear(iterator_);
2749 resolver->Protect(iterator_);
2750 pkgCacheFile &cache([database_ cache]);
2751 cache->MarkInstall(iterator_, false);
2752 pkgDepCache::StateCache &state((*cache)[iterator_]);
2753 if (!state.Install())
2754 cache->SetReInstall(iterator_, true);
2758 pkgProblemResolver *resolver = [database_ resolver];
2759 resolver->Clear(iterator_);
2760 resolver->Protect(iterator_);
2761 resolver->Remove(iterator_);
2762 [database_ cache]->MarkDelete(iterator_, true);
2765 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2766 _profile(Package$isUnfilteredAndSearchedForBy)
2769 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2770 value &= [self unfiltered];
2773 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2774 value &= [self matches:search];
2781 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2782 if ([search length] == 0)
2785 _profile(Package$isUnfilteredAndSelectedForBy)
2788 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2789 value &= [self unfiltered];
2792 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2793 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2800 - (bool) isInstalledAndVisible:(NSNumber *)number {
2801 return (![number boolValue] || [self visible]) && ![self uninstalled];
2804 - (bool) isVisibleInSection:(NSString *)name {
2805 NSString *section = [self section];
2810 section == nil && [name length] == 0 ||
2811 [name isEqualToString:section]
2815 - (bool) isVisibleInSource:(Source *)source {
2816 return [self source] == source && [self visible];
2821 /* Section Class {{{ */
2822 @interface Section : NSObject {
2827 NSString *localized_;
2830 - (NSComparisonResult) compareByLocalized:(Section *)section;
2831 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2832 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2833 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2834 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2835 - (NSString *) name;
2842 - (void) addToCount;
2844 - (void) setCount:(size_t)count;
2845 - (NSString *) localized;
2849 @implementation Section
2853 if (localized_ != nil)
2854 [localized_ release];
2858 - (NSComparisonResult) compareByLocalized:(Section *)section {
2859 NSString *lhs(localized_);
2860 NSString *rhs([section localized]);
2862 /*if ([lhs length] != 0 && [rhs length] != 0) {
2863 unichar lhc = [lhs characterAtIndex:0];
2864 unichar rhc = [rhs characterAtIndex:0];
2866 if (isalpha(lhc) && !isalpha(rhc))
2867 return NSOrderedAscending;
2868 else if (!isalpha(lhc) && isalpha(rhc))
2869 return NSOrderedDescending;
2872 return [lhs compare:rhs options:LaxCompareOptions_];
2875 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2876 if ((self = [self initWithName:name localize:NO]) != nil) {
2877 if (localized != nil)
2878 localized_ = [localized retain];
2882 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2883 return [self initWithName:name row:0 localize:localize];
2886 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2887 if ((self = [super init]) != nil) {
2888 name_ = [name retain];
2892 localized_ = [LocalizeSection(name_) retain];
2896 /* XXX: localize the index thingees */
2897 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2898 if ((self = [super init]) != nil) {
2899 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2905 - (NSString *) name {
2925 - (void) addToCount {
2929 - (void) setCount:(size_t)count {
2933 - (NSString *) localized {
2940 static NSString *Colon_;
2941 static NSString *Error_;
2942 static NSString *Warning_;
2944 /* Database Implementation {{{ */
2945 @implementation Database
2947 + (Database *) sharedInstance {
2948 static Database *instance;
2949 if (instance == nil)
2950 instance = [[Database alloc] init];
2960 NSRecycleZone(zone_);
2961 // XXX: malloc_destroy_zone(zone_);
2962 apr_pool_destroy(pool_);
2966 - (void) _readCydia:(NSNumber *)fd { _pooled
2967 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2968 std::istream is(&ib);
2971 static Pcre finish_r("^finish:([^:]*)$");
2973 while (std::getline(is, line)) {
2974 const char *data(line.c_str());
2975 size_t size = line.size();
2976 lprintf("C:%s\n", data);
2978 if (finish_r(data, size)) {
2979 NSString *finish = finish_r[1];
2980 int index = [Finishes_ indexOfObject:finish];
2981 if (index != INT_MAX && index > Finish_)
2989 - (void) _readStatus:(NSNumber *)fd { _pooled
2990 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2991 std::istream is(&ib);
2994 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2995 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2997 while (std::getline(is, line)) {
2998 const char *data(line.c_str());
2999 size_t size(line.size());
3000 lprintf("S:%s\n", data);
3002 if (conffile_r(data, size)) {
3003 [delegate_ setConfigurationData:conffile_r[1]];
3004 } else if (strncmp(data, "status: ", 8) == 0) {
3005 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3006 [delegate_ setProgressTitle:string];
3007 } else if (pmstatus_r(data, size)) {
3008 std::string type([pmstatus_r[1] UTF8String]);
3009 NSString *id = pmstatus_r[2];
3011 float percent([pmstatus_r[3] floatValue]);
3012 [delegate_ setProgressPercent:(percent / 100)];
3014 NSString *string = pmstatus_r[4];
3016 if (type == "pmerror")
3017 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3018 withObject:[NSArray arrayWithObjects:string, id, nil]
3021 else if (type == "pmstatus") {
3022 [delegate_ setProgressTitle:string];
3023 } else if (type == "pmconffile")
3024 [delegate_ setConfigurationData:string];
3026 lprintf("E:unknown pmstatus\n");
3028 lprintf("E:unknown status\n");
3034 - (void) _readOutput:(NSNumber *)fd { _pooled
3035 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3036 std::istream is(&ib);
3039 while (std::getline(is, line)) {
3040 lprintf("O:%s\n", line.c_str());
3041 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3051 - (Package *) packageWithName:(NSString *)name {
3052 @synchronized (self) {
3053 if (static_cast<pkgDepCache *>(cache_) == NULL)
3055 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3056 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3060 if ((self = [super init]) != nil) {
3067 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3068 apr_pool_create(&pool_, NULL);
3070 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
3074 _assert(pipe(fds) != -1);
3077 _config->Set("APT::Keep-Fds::", cydiafd_);
3078 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3081 detachNewThreadSelector:@selector(_readCydia:)
3083 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3086 _assert(pipe(fds) != -1);
3090 detachNewThreadSelector:@selector(_readStatus:)
3092 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3095 _assert(pipe(fds) != -1);
3096 _assert(dup2(fds[0], 0) != -1);
3097 _assert(close(fds[0]) != -1);
3099 input_ = fdopen(fds[1], "a");
3101 _assert(pipe(fds) != -1);
3102 _assert(dup2(fds[1], 1) != -1);
3103 _assert(close(fds[1]) != -1);
3106 detachNewThreadSelector:@selector(_readOutput:)
3108 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3113 - (pkgCacheFile &) cache {
3117 - (pkgDepCache::Policy *) policy {
3121 - (pkgRecords *) records {
3125 - (pkgProblemResolver *) resolver {
3129 - (pkgAcquire &) fetcher {
3133 - (pkgSourceList &) list {
3137 - (NSArray *) packages {
3138 return (NSArray *) packages_;
3141 - (NSArray *) sources {
3142 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3143 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3144 [sources addObject:i->second];
3148 - (NSArray *) issues {
3149 if (cache_->BrokenCount() == 0)
3152 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3154 for (Package *package in [self packages]) {
3155 if (![package broken])
3157 pkgCache::PkgIterator pkg([package iterator]);
3159 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3160 [entry addObject:[package name]];
3161 [issues addObject:entry];
3163 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3167 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3168 pkgCache::DepIterator start;
3169 pkgCache::DepIterator end;
3170 dep.GlobOr(start, end); // ++dep
3172 if (!cache_->IsImportantDep(end))
3174 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3177 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3178 [entry addObject:failure];
3179 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3181 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3182 if (Package *package = [self packageWithName:name])
3183 name = [package name];
3184 [failure addObject:name];
3186 pkgCache::PkgIterator target(start.TargetPkg());
3187 if (target->ProvidesList != 0)
3188 [failure addObject:@"?"];
3190 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3192 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3193 else if (!cache_[target].CandidateVerIter(cache_).end())
3194 [failure addObject:@"-"];
3195 else if (target->ProvidesList == 0)
3196 [failure addObject:@"!"];
3198 [failure addObject:@"%"];
3202 if (start.TargetVer() != 0)
3203 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3214 - (bool) popErrorWithTitle:(NSString *)title {
3216 std::string message;
3218 while (!_error->empty()) {
3220 bool warning(!_error->PopMessage(error));
3224 size_t size(error.size());
3225 if (size == 0 || error[size - 1] != '\n')
3227 error.resize(size - 1);
3229 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3231 if (!message.empty())
3236 if (fatal && !message.empty())
3237 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3242 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3243 return [self popErrorWithTitle:title] || !success;
3246 - (void) reloadData { CYPoolStart() {
3247 @synchronized (self) {
3250 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3251 CFArrayRemoveAllValues(packages_);
3278 apr_pool_clear(pool_);
3279 NSRecycleZone(zone_);
3281 int chk(creat("/tmp/cydia.chk", 0644));
3285 NSString *title(UCLocalize("DATABASE"));
3288 if (!cache_.Open(progress_, true)) { pop:
3290 bool warning(!_error->PopMessage(error));
3291 lprintf("cache_.Open():[%s]\n", error.c_str());
3293 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3294 [delegate_ repairWithSelector:@selector(configure)];
3295 else if (error == "The package lists or status file could not be parsed or opened.")
3296 [delegate_ repairWithSelector:@selector(update)];
3297 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3298 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3299 // else if (error == "The list of sources could not be read.")
3301 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3310 unlink("/tmp/cydia.chk");
3312 now_ = [[NSDate date] retain];
3314 policy_ = new pkgDepCache::Policy();
3315 records_ = new pkgRecords(cache_);
3316 resolver_ = new pkgProblemResolver(cache_);
3317 fetcher_ = new pkgAcquire(&status_);
3320 list_ = new pkgSourceList();
3321 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3324 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3325 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3329 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3332 if (cache_->BrokenCount() != 0) {
3333 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3336 if (cache_->BrokenCount() != 0) {
3337 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3341 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3345 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3346 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3347 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3348 // XXX: this could be more intelligent
3349 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3350 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3352 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];
3399 } } CYPoolEnd() _trace(); }
3401 - (void) configure {
3402 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3403 system([dpkg UTF8String]);
3407 // XXX: I don't remember this condition
3412 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3414 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3416 if ([self popErrorWithTitle:title])
3420 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3423 public pkgArchiveCleaner
3426 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3431 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3438 fetcher_->Shutdown();
3440 pkgRecords records(cache_);
3442 lock_ = new FileFd();
3443 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3445 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3447 if ([self popErrorWithTitle:title])
3451 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3454 manager_ = (_system->CreatePM(cache_));
3455 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3462 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3464 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3466 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3468 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3469 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3472 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3477 bool failed = false;
3478 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3479 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3481 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3484 std::string uri = (*item)->DescURI();
3485 std::string error = (*item)->ErrorText;
3487 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3490 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3491 withObject:[NSArray arrayWithObjects:
3492 [NSString stringWithUTF8String:error.c_str()],
3504 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3506 if (_error->PendingError()) {
3511 if (result == pkgPackageManager::Failed) {
3516 if (result != pkgPackageManager::Completed) {
3521 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3523 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3525 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3526 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3529 if (![before isEqualToArray:after])
3534 NSString *title(UCLocalize("UPGRADE"));
3535 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3541 [self updateWithStatus:status_];
3544 - (void) setVisible {
3545 for (Package *package in [self packages])
3546 [package setVisible];
3549 - (void) updateWithStatus:(Status &)status {
3550 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3551 NSString *title(UCLocalize("REFRESHING_DATA"));
3554 if (!list.ReadMainList())
3555 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3558 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3559 if ([self popErrorWithTitle:title])
3562 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3563 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3564 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3566 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3570 - (void) setDelegate:(id)delegate {
3571 delegate_ = delegate;
3572 status_.setDelegate(delegate);
3573 progress_.setDelegate(delegate);
3576 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3577 SourceMap::const_iterator i(sources_.find(file->ID));
3578 return i == sources_.end() ? nil : i->second;
3584 /* Confirmation Controller {{{ */
3585 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3586 if (!iterator.end())
3587 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3588 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3590 pkgCache::PkgIterator package(dep.TargetPkg());
3593 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3601 /* Web Scripting {{{ */
3602 @interface CydiaObject : NSObject {
3607 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3610 @implementation CydiaObject
3613 [indirect_ release];
3617 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3618 if ((self = [super init]) != nil) {
3619 indirect_ = [indirect retain];
3623 - (void) setDelegate:(id)delegate {
3624 delegate_ = delegate;
3627 + (NSArray *) _attributeKeys {
3628 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3631 - (NSArray *) attributeKeys {
3632 return [[self class] _attributeKeys];
3635 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3636 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3639 - (NSString *) device {
3640 return [[UIDevice currentDevice] uniqueIdentifier];
3643 #if 0 // XXX: implement!
3644 - (NSString *) mac {
3645 if (![indirect_ promptForSensitive:@"Mac Address"])
3649 - (NSString *) serial {
3650 if (![indirect_ promptForSensitive:@"Serial #"])
3654 - (NSString *) firewire {
3655 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3659 - (NSString *) imei {
3660 if (![indirect_ promptForSensitive:@"IMEI"])
3665 + (NSString *) webScriptNameForSelector:(SEL)selector {
3666 if (selector == @selector(close))
3668 else if (selector == @selector(getInstalledPackages))
3669 return @"getInstalledPackages";
3670 else if (selector == @selector(getPackageById:))
3671 return @"getPackageById";
3672 else if (selector == @selector(installPackages:))
3673 return @"installPackages";
3674 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3675 return @"setButtonImage";
3676 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3677 return @"setButtonTitle";
3678 else if (selector == @selector(setPopupHook:))
3679 return @"setPopupHook";
3680 else if (selector == @selector(setSpecial:))
3681 return @"setSpecial";
3682 else if (selector == @selector(setToken:))
3684 else if (selector == @selector(setViewportWidth:))
3685 return @"setViewportWidth";
3686 else if (selector == @selector(supports:))
3688 else if (selector == @selector(stringWithFormat:arguments:))
3690 else if (selector == @selector(localizedStringForKey:value:table:))
3692 else if (selector == @selector(du:))
3694 else if (selector == @selector(statfs:))
3700 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3701 return [self webScriptNameForSelector:selector] == nil;
3704 - (BOOL) supports:(NSString *)feature {
3705 return [feature isEqualToString:@"window.open"];
3708 - (NSArray *) getInstalledPackages {
3709 NSArray *packages([[Database sharedInstance] packages]);
3710 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3711 for (Package *package in packages)
3712 if ([package installed] != nil)
3713 [installed addObject:package];
3717 - (Package *) getPackageById:(NSString *)id {
3718 Package *package([[Database sharedInstance] packageWithName:id]);
3723 - (NSArray *) statfs:(NSString *)path {
3726 if (path == nil || statfs([path UTF8String], &stat) == -1)
3729 return [NSArray arrayWithObjects:
3730 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3731 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3732 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3736 - (NSNumber *) du:(NSString *)path {
3737 NSNumber *value(nil);
3740 _assert(pipe(fds) != -1);
3742 pid_t pid(ExecFork());
3744 _assert(dup2(fds[1], 1) != -1);
3745 _assert(close(fds[0]) != -1);
3746 _assert(close(fds[1]) != -1);
3747 /* XXX: this should probably not use du */
3748 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3753 _assert(close(fds[1]) != -1);
3755 if (FILE *du = fdopen(fds[0], "r")) {
3757 while (fgets(line, sizeof(line), du) != NULL) {
3758 size_t length(strlen(line));
3759 while (length != 0 && line[length - 1] == '\n')
3760 line[--length] = '\0';
3761 if (char *tab = strchr(line, '\t')) {
3763 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3768 } else _assert(close(fds[0]));
3772 if (waitpid(pid, &status, 0) == -1)
3775 else _assert(false);
3784 - (void) installPackages:(NSArray *)packages {
3785 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3788 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3789 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3792 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3793 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3796 - (void) setSpecial:(id)function {
3797 [indirect_ setSpecial:function];
3800 - (void) setToken:(NSString *)token {
3803 Token_ = [token retain];
3805 [Metadata_ setObject:Token_ forKey:@"Token"];
3809 - (void) setPopupHook:(id)function {
3810 [indirect_ setPopupHook:function];
3813 - (void) setViewportWidth:(float)width {
3814 [indirect_ setViewportWidth:width];
3817 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3818 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3819 unsigned count([arguments count]);
3821 for (unsigned i(0); i != count; ++i)
3822 values[i] = [arguments objectAtIndex:i];
3823 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3826 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3827 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3829 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3831 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3837 /* Cydia Browser Controller {{{ */
3838 @interface CYBrowserController : BrowserController {
3839 CydiaObject *cydia_;
3844 @implementation CYBrowserController
3851 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3854 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3855 [super webView:view didClearWindowObject:window forFrame:frame];
3857 WebDataSource *source([frame dataSource]);
3858 NSURLResponse *response([source response]);
3859 NSURL *url([response URL]);
3860 NSString *scheme([url scheme]);
3862 NSHTTPURLResponse *http;
3863 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3864 http = (NSHTTPURLResponse *) response;
3868 NSDictionary *headers([http allHeaderFields]);
3869 NSString *host([url host]);
3870 [self setHeaders:headers forHost:host];
3873 [host isEqualToString:@"cydia.saurik.com"] ||
3874 [host hasSuffix:@".cydia.saurik.com"] ||
3875 [scheme isEqualToString:@"file"]
3877 [window setValue:cydia_ forKey:@"cydia"];
3880 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3881 if (System_ != NULL)
3882 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3883 if (Machine_ != NULL)
3884 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3886 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3888 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3891 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3892 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3893 [self _setMoreHeaders:copy];
3897 - (void) setDelegate:(id)delegate {
3898 [super setDelegate:delegate];
3899 [cydia_ setDelegate:delegate];
3903 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3904 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3906 WebView *webview([[webview_ _documentView] webView]);
3908 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3910 NSString *application = package == nil ? @"Cydia" : [NSString
3911 stringWithFormat:@"Cydia/%@",
3916 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3918 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3919 if (Product_ != nil)
3920 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3922 [webview setApplicationNameForUserAgent:application];
3929 /* Confirmation {{{ */
3930 @protocol ConfirmationControllerDelegate
3931 - (void) cancelAndClear:(bool)clear;
3932 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3936 @interface ConfirmationController : CYBrowserController {
3937 _transient Database *database_;
3938 UIAlertView *essential_;
3945 - (id) initWithDatabase:(Database *)database;
3949 @implementation ConfirmationController
3956 if (essential_ != nil)
3957 [essential_ release];
3961 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3962 NSString *context([alert context]);
3964 if ([context isEqualToString:@"remove"]) {
3965 if (button == [alert cancelButtonIndex]) {
3966 [self dismissModalViewControllerAnimated:YES];
3967 } else if (button == [alert firstOtherButtonIndex]) {
3970 [delegate_ confirmWithNavigationController:[self navigationController]];
3973 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3974 } else if ([context isEqualToString:@"unable"]) {
3975 [self dismissModalViewControllerAnimated:YES];
3976 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3978 [super alertView:alert clickedButtonAtIndex:button];
3982 - (void) _doContinue {
3983 [self dismissModalViewControllerAnimated:YES];
3984 [delegate_ cancelAndClear:NO];
3987 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
3988 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
3992 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3993 [super webView:view didClearWindowObject:window forFrame:frame];
3994 [window setValue:changes_ forKey:@"changes"];
3995 [window setValue:issues_ forKey:@"issues"];
3996 [window setValue:sizes_ forKey:@"sizes"];
3997 [window setValue:self forKey:@"queue"];
4000 - (id) initWithDatabase:(Database *)database {
4001 if ((self = [super init]) != nil) {
4002 database_ = database;
4004 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4006 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4007 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4008 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4009 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4010 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4014 pkgDepCache::Policy *policy([database_ policy]);
4016 pkgCacheFile &cache([database_ cache]);
4017 NSArray *packages = [database_ packages];
4018 for (Package *package in packages) {
4019 pkgCache::PkgIterator iterator = [package iterator];
4020 pkgDepCache::StateCache &state(cache[iterator]);
4022 NSString *name([package name]);
4024 if (state.NewInstall())
4025 [installing addObject:name];
4026 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4027 [reinstalling addObject:name];
4028 else if (state.Upgrade())
4029 [upgrading addObject:name];
4030 else if (state.Downgrade())
4031 [downgrading addObject:name];
4032 else if (state.Delete()) {
4033 if ([package essential])
4035 [removing addObject:name];
4038 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4039 substrate_ |= DepSubstrate(iterator.CurrentVer());
4044 else if (Advanced_) {
4045 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4047 essential_ = [[UIAlertView alloc]
4048 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4049 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4051 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4052 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4055 [essential_ setContext:@"remove"];
4057 essential_ = [[UIAlertView alloc]
4058 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4059 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4061 cancelButtonTitle:UCLocalize("OKAY")
4062 otherButtonTitles:nil
4065 [essential_ setContext:@"unable"];
4068 changes_ = [[NSArray alloc] initWithObjects:
4076 issues_ = [database_ issues];
4078 issues_ = [issues_ retain];
4080 sizes_ = [[NSArray alloc] initWithObjects:
4081 SizeString([database_ fetcher].FetchNeeded()),
4082 SizeString([database_ fetcher].PartialPresent()),
4085 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4087 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
4088 initWithTitle:UCLocalize("CANCEL")
4089 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4090 style:UIBarButtonItemStylePlain
4092 action:@selector(cancelButtonClicked)
4094 [[self navigationItem] setLeftBarButtonItem:leftItem];
4099 - (void) applyRightButton {
4100 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
4101 initWithTitle:UCLocalize("CONFIRM")
4102 style:UIBarButtonItemStylePlain
4104 action:@selector(confirmButtonClicked)
4106 #if !AlwaysReload && !IgnoreInstall
4107 if (issues_ == nil && ![self isLoading]) [[self navigationItem] setRightBarButtonItem:rightItem];
4108 else [super applyRightButton];
4110 [[self navigationItem] setRightBarButtonItem:nil];
4112 [rightItem release];
4115 - (void) cancelButtonClicked {
4116 [self dismissModalViewControllerAnimated:YES];
4117 [delegate_ cancelAndClear:YES];
4121 - (void) confirmButtonClicked {
4125 if (essential_ != nil)
4130 [delegate_ confirmWithNavigationController:[self navigationController]];
4138 /* Progress Data {{{ */
4139 @interface ProgressData : NSObject {
4145 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4152 @implementation ProgressData
4154 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4155 if ((self = [super init]) != nil) {
4156 selector_ = selector;
4176 /* Progress Controller {{{ */
4177 @interface ProgressController : CYViewController <
4178 ConfigurationDelegate,
4181 _transient Database *database_;
4182 UIProgressBar *progress_;
4183 UITextView *output_;
4184 UITextLabel *status_;
4185 UIPushButton *close_;
4187 SHA1SumValue springlist_;
4188 SHA1SumValue notifyconf_;
4192 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4194 - (void) _retachThread;
4195 - (void) _detachNewThreadData:(ProgressData *)data;
4196 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4202 @protocol ProgressControllerDelegate
4203 - (void) progressControllerIsComplete:(ProgressController *)sender;
4206 @implementation ProgressController
4209 [database_ setDelegate:nil];
4210 [progress_ release];
4219 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4220 if ((self = [super init]) != nil) {
4221 database_ = database;
4222 [database_ setDelegate:self];
4223 delegate_ = delegate;
4225 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4227 progress_ = [[UIProgressBar alloc] init];
4228 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4229 [progress_ setStyle:0];
4231 status_ = [[UITextLabel alloc] init];
4232 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4233 [status_ setColor:[UIColor whiteColor]];
4234 [status_ setBackgroundColor:[UIColor clearColor]];
4235 [status_ setCentersHorizontally:YES];
4236 //[status_ setFont:font];
4238 output_ = [[UITextView alloc] init];
4240 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4241 //[output_ setTextFont:@"Courier New"];
4242 [output_ setFont:[[output_ font] fontWithSize:12]];
4243 [output_ setTextColor:[UIColor whiteColor]];
4244 [output_ setBackgroundColor:[UIColor clearColor]];
4245 [output_ setMarginTop:0];
4246 [output_ setAllowsRubberBanding:YES];
4247 [output_ setEditable:NO];
4248 [[self view] addSubview:output_];
4250 close_ = [[UIPushButton alloc] init];
4251 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4252 [close_ setAutosizesToFit:NO];
4253 [close_ setDrawsShadow:YES];
4254 [close_ setStretchBackground:YES];
4255 [close_ setEnabled:YES];
4256 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4257 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4258 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4259 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4263 - (void) positionViews {
4264 CGRect bounds = [[self view] bounds];
4265 CGSize prgsize = [UIProgressBar defaultSize];
4268 (bounds.size.width - prgsize.width) / 2,
4269 bounds.size.height - prgsize.height - 20
4272 float closewidth = bounds.size.width - 20;
4273 if (closewidth > 300) closewidth = 300;
4275 [progress_ setFrame:prgrect];
4276 [status_ setFrame:CGRectMake(
4278 bounds.size.height - prgsize.height - 50,
4279 bounds.size.width - 20,
4282 [output_ setFrame:CGRectMake(
4285 bounds.size.width - 20,
4286 bounds.size.height - 62
4288 [close_ setFrame:CGRectMake(
4289 (bounds.size.width - closewidth) / 2,
4290 bounds.size.height - prgsize.height - 50,
4296 - (void) viewWillAppear:(BOOL)animated {
4297 [super viewDidAppear:animated];
4298 [[self navigationItem] setHidesBackButton:YES];
4299 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4301 [self positionViews];
4304 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4305 [self positionViews];
4308 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4309 NSString *context([alert context]);
4311 if ([context isEqualToString:@"conffile"]) {
4312 FILE *input = [database_ input];
4313 if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
4314 else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
4319 - (void) closeButtonPushed {
4322 UpdateExternalStatus(0);
4326 [self dismissModalViewControllerAnimated:YES];
4330 [delegate_ terminateWithSuccess];
4331 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4332 [delegate_ suspendWithAnimation:YES];
4334 [delegate_ suspend];*/
4338 system("launchctl stop com.apple.SpringBoard");
4342 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4351 - (void) _retachThread {
4352 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4354 [[self view] addSubview:close_];
4355 [progress_ removeFromSuperview];
4356 [status_ removeFromSuperview];
4358 [database_ popErrorWithTitle:title_];
4359 [delegate_ progressControllerIsComplete:self];
4363 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4366 MMap mmap(file, MMap::ReadOnly);
4368 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4369 if (!(notifyconf_ == sha1.Result()))
4376 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4379 MMap mmap(file, MMap::ReadOnly);
4381 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4382 if (!(springlist_ == sha1.Result()))
4388 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4389 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4390 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4391 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4392 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4395 system("su -c /usr/bin/uicache mobile");
4397 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4399 [delegate_ setStatusBarShowsProgress:NO];
4402 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4403 [[data target] performSelector:[data selector] withObject:[data object]];
4406 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4409 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4410 UpdateExternalStatus(1);
4417 title_ = [title retain];
4419 [[self navigationItem] setTitle:title_];
4421 [status_ setText:nil];
4422 [output_ setText:@""];
4423 [progress_ setProgress:0];
4425 [close_ removeFromSuperview];
4426 [[self view] addSubview:progress_];
4427 [[self view] addSubview:status_];
4429 [delegate_ setStatusBarShowsProgress:YES];
4434 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4437 MMap mmap(file, MMap::ReadOnly);
4439 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4440 notifyconf_ = sha1.Result();
4446 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4449 MMap mmap(file, MMap::ReadOnly);
4451 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4452 springlist_ = sha1.Result();
4457 detachNewThreadSelector:@selector(_detachNewThreadData:)
4459 withObject:[[ProgressData alloc]
4460 initWithSelector:selector
4467 - (void) repairWithSelector:(SEL)selector {
4469 detachNewThreadSelector:selector
4472 title:UCLocalize("REPAIRING")
4476 - (void) setConfigurationData:(NSString *)data {
4478 performSelectorOnMainThread:@selector(_setConfigurationData:)
4484 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4485 CYActionSheet *sheet([[[CYActionSheet alloc]
4487 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4488 defaultButtonIndex:0
4491 [sheet setMessage:error];
4492 [sheet yieldToPopupAlertAnimated:YES];
4496 - (void) setProgressTitle:(NSString *)title {
4498 performSelectorOnMainThread:@selector(_setProgressTitle:)
4504 - (void) setProgressPercent:(float)percent {
4506 performSelectorOnMainThread:@selector(_setProgressPercent:)
4507 withObject:[NSNumber numberWithFloat:percent]
4512 - (void) startProgress {
4515 - (void) addProgressOutput:(NSString *)output {
4517 performSelectorOnMainThread:@selector(_addProgressOutput:)
4523 - (bool) isCancelling:(size_t)received {
4527 - (void) _setConfigurationData:(NSString *)data {
4528 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4530 if (!conffile_r(data)) {
4531 lprintf("E:invalid conffile\n");
4535 NSString *ofile = conffile_r[1];
4536 //NSString *nfile = conffile_r[2];
4538 UIAlertView *alert = [[[UIAlertView alloc]
4539 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4540 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4542 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4543 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4544 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4548 [alert setContext:@"conffile"];
4552 - (void) _setProgressTitle:(NSString *)title {
4553 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4554 for (size_t i(0), e([words count]); i != e; ++i) {
4555 NSString *word([words objectAtIndex:i]);
4556 if (Package *package = [database_ packageWithName:word])
4557 [words replaceObjectAtIndex:i withObject:[package name]];
4560 [status_ setText:[words componentsJoinedByString:@" "]];
4563 - (void) _setProgressPercent:(NSNumber *)percent {
4564 [progress_ setProgress:[percent floatValue]];
4567 - (void) _addProgressOutput:(NSString *)output {
4568 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4569 CGSize size = [output_ contentSize];
4570 CGRect rect = {{0, size.height}, {size.width, 0}};
4571 [output_ scrollRectToVisible:rect animated:YES];
4574 - (BOOL) isRunning {
4581 /* Cell Content View {{{ */
4582 @protocol ContentDelegate
4583 - (void) drawContentRect:(CGRect)rect;
4586 @interface ContentView : UIView {
4587 _transient id<ContentDelegate> delegate_;
4592 @implementation ContentView
4593 - (id) initWithFrame:(CGRect)frame {
4594 if ((self = [super initWithFrame:frame]) != nil) {
4595 /* Fix landscape stretching. */
4596 [self setNeedsDisplayOnBoundsChange:YES];
4600 - (void) setDelegate:(id<ContentDelegate>)delegate {
4601 delegate_ = delegate;
4604 - (void) drawRect:(CGRect)rect {
4605 [super drawRect:rect];
4606 [delegate_ drawContentRect:rect];
4610 /* Package Cell {{{ */
4611 @interface PackageCell : UITableViewCell <
4616 NSString *description_;
4622 ContentView *content_;
4628 - (PackageCell *) init;
4629 - (void) setPackage:(Package *)package;
4631 + (int) heightForPackage:(Package *)package;
4632 - (void) drawContentRect:(CGRect)rect;
4636 @implementation PackageCell
4638 - (void) clearPackage {
4649 if (description_ != nil) {
4650 [description_ release];
4654 if (source_ != nil) {
4659 if (badge_ != nil) {
4664 if (placard_ != nil) {
4674 [self clearPackage];
4681 return faded_ ? [self selectionPercent] : fade_;
4684 - (PackageCell *) init {
4685 CGRect frame(CGRectMake(0, 0, 320, 74));
4686 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4687 UIView *content([self contentView]);
4688 CGRect bounds([content bounds]);
4690 content_ = [[ContentView alloc] initWithFrame:bounds];
4691 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4692 [content addSubview:content_];
4694 [content_ setDelegate:self];
4695 [content_ setOpaque:YES];
4696 if ([self respondsToSelector:@selector(selectionPercent)])
4701 - (void) _setBackgroundColor {
4703 if (NSString *mode = [package_ mode]) {
4704 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4705 color = remove ? RemovingColor_ : InstallingColor_;
4707 color = [UIColor whiteColor];
4709 [content_ setBackgroundColor:color];
4710 [self setNeedsDisplay];
4713 - (void) setPackage:(Package *)package {
4714 [self clearPackage];
4717 Source *source = [package source];
4719 icon_ = [[package icon] retain];
4720 name_ = [[package name] retain];
4723 description_ = [package longDescription];
4724 if (description_ == nil)
4725 description_ = [package shortDescription];
4726 if (description_ != nil)
4727 description_ = [description_ retain];
4729 commercial_ = [package isCommercial];
4731 package_ = [package retain];
4733 NSString *label = nil;
4734 bool trusted = false;
4736 if (source != nil) {
4737 label = [source label];
4738 trusted = [source trusted];
4739 } else if ([[package id] isEqualToString:@"firmware"])
4740 label = UCLocalize("APPLE");
4742 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4744 NSString *from(label);
4746 NSString *section = [package simpleSection];
4747 if (section != nil && ![section isEqualToString:label]) {
4748 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4749 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4752 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4753 source_ = [from retain];
4755 if (NSString *purpose = [package primaryPurpose])
4756 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4757 badge_ = [badge_ retain];
4759 if ([package installed] != nil)
4760 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4761 placard_ = [placard_ retain];
4763 [self _setBackgroundColor];
4764 [content_ setNeedsDisplay];
4767 - (void) drawContentRect:(CGRect)rect {
4768 bool selected([self isSelected]);
4769 float width([self bounds].size.width);
4772 CGContextRef context(UIGraphicsGetCurrentContext());
4773 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4774 CGContextFillRect(context, rect);
4779 rect.size = [icon_ size];
4781 rect.size.width /= 2;
4782 rect.size.height /= 2;
4784 rect.origin.x = 25 - rect.size.width / 2;
4785 rect.origin.y = 25 - rect.size.height / 2;
4787 [icon_ drawInRect:rect];
4790 if (badge_ != nil) {
4791 CGSize size = [badge_ size];
4793 [badge_ drawAtPoint:CGPointMake(
4794 36 - size.width / 2,
4795 36 - size.height / 2
4803 UISetColor(commercial_ ? Purple_ : Black_);
4804 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4805 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4808 UISetColor(commercial_ ? Purplish_ : Gray_);
4809 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4811 if (placard_ != nil)
4812 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4815 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4816 //[self _setBackgroundColor];
4817 [super setSelected:selected animated:fade];
4818 [content_ setNeedsDisplay];
4821 + (int) heightForPackage:(Package *)package {
4827 /* Section Cell {{{ */
4828 @interface SectionCell : UITableViewCell <
4836 ContentView *content_;
4841 - (void) setSection:(Section *)section editing:(BOOL)editing;
4845 @implementation SectionCell
4847 - (void) clearSection {
4848 if (basic_ != nil) {
4853 if (section_ != nil) {
4863 if (count_ != nil) {
4870 [self clearSection];
4878 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4879 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4880 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4881 switch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4882 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4884 UIView *content([self contentView]);
4885 CGRect bounds([content bounds]);
4887 content_ = [[ContentView alloc] initWithFrame:bounds];
4888 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4889 [content addSubview:content_];
4890 [content_ setBackgroundColor:[UIColor whiteColor]];
4892 [content_ setDelegate:self];
4896 - (void) onSwitch:(id)sender {
4897 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4898 if (metadata == nil) {
4899 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4900 [Sections_ setObject:metadata forKey:basic_];
4904 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4907 - (void) setSection:(Section *)section editing:(BOOL)editing {
4908 if (editing != editing_) {
4910 [switch_ removeFromSuperview];
4912 [self addSubview:switch_];
4916 [self clearSection];
4918 if (section == nil) {
4919 name_ = [UCLocalize("ALL_PACKAGES") retain];
4922 basic_ = [section name];
4924 basic_ = [basic_ retain];
4926 section_ = [section localized];
4927 if (section_ != nil)
4928 section_ = [section_ retain];
4930 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4931 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4934 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4937 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4938 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
4940 [content_ setNeedsDisplay];
4943 - (void) setFrame:(CGRect)frame {
4944 [super setFrame:frame];
4946 CGRect rect([switch_ frame]);
4947 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4950 - (void) drawContentRect:(CGRect)rect {
4951 BOOL selected = [self isSelected];
4953 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4961 float width(rect.size.width);
4965 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4967 CGSize size = [count_ sizeWithFont:Font14_];
4971 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4977 /* File Table {{{ */
4978 @interface FileTable : CYViewController <
4979 UITableViewDataSource,
4982 _transient Database *database_;
4985 NSMutableArray *files_;
4989 - (id) initWithDatabase:(Database *)database;
4990 - (void) setPackage:(Package *)package;
4994 @implementation FileTable
4997 if (package_ != nil)
5006 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5007 return files_ == nil ? 0 : [files_ count];
5010 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5014 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5015 static NSString *reuseIdentifier = @"Cell";
5017 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5019 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5020 [cell setFont:[UIFont systemFontOfSize:16]];
5022 [cell setText:[files_ objectAtIndex:indexPath.row]];
5023 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5028 - (id) initWithDatabase:(Database *)database {
5029 if ((self = [super init]) != nil) {
5030 database_ = database;
5032 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5034 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5036 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5037 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5038 [list_ setRowHeight:24.0f];
5039 [[self view] addSubview:list_];
5041 [list_ setDataSource:self];
5042 [list_ setDelegate:self];
5046 - (void) setPackage:(Package *)package {
5047 if (package_ != nil) {
5048 [package_ autorelease];
5057 [files_ removeAllObjects];
5059 if (package != nil) {
5060 package_ = [package retain];
5061 name_ = [[package id] retain];
5063 if (NSArray *files = [package files])
5064 [files_ addObjectsFromArray:files];
5066 if ([files_ count] != 0) {
5067 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5068 [files_ removeObjectAtIndex:0];
5069 [files_ sortUsingSelector:@selector(compareByPath:)];
5071 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5072 [stack addObject:@"/"];
5074 for (int i(0), e([files_ count]); i != e; ++i) {
5075 NSString *file = [files_ objectAtIndex:i];
5076 while (![file hasPrefix:[stack lastObject]])
5077 [stack removeLastObject];
5078 NSString *directory = [stack lastObject];
5079 [stack addObject:[file stringByAppendingString:@"/"]];
5080 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5081 ([stack count] - 2) * 3, "",
5082 [file substringFromIndex:[directory length]]
5091 - (void) reloadData {
5092 [self setPackage:[database_ packageWithName:name_]];
5097 /* Package Controller {{{ */
5098 @interface PackageController : CYBrowserController <
5099 UIActionSheetDelegate
5101 _transient Database *database_;
5105 NSMutableArray *buttons_;
5106 UIBarButtonItem *button_;
5109 - (id) initWithDatabase:(Database *)database;
5110 - (void) setPackage:(Package *)package;
5114 @implementation PackageController
5117 if (package_ != nil)
5131 if ([self retainCount] == 1)
5132 [delegate_ setPackageController:self];
5136 /* XXX: this is not safe at all... localization of /fail/ */
5137 - (void) _clickButtonWithName:(NSString *)name {
5138 if ([name isEqualToString:UCLocalize("CLEAR")])
5139 [delegate_ clearPackage:package_];
5140 else if ([name isEqualToString:UCLocalize("INSTALL")])
5141 [delegate_ installPackage:package_];
5142 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5143 [delegate_ installPackage:package_];
5144 else if ([name isEqualToString:UCLocalize("REMOVE")])
5145 [delegate_ removePackage:package_];
5146 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5147 [delegate_ installPackage:package_];
5148 else _assert(false);
5151 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5152 NSString *context([sheet context]);
5154 if ([context isEqualToString:@"modify"]) {
5155 if (button != [sheet cancelButtonIndex]) {
5156 NSString *buttonName = [buttons_ objectAtIndex:button];
5157 [self _clickButtonWithName:buttonName];
5160 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5164 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5165 [super webView:view didClearWindowObject:window forFrame:frame];
5166 [window setValue:package_ forKey:@"package"];
5169 - (bool) _allowJavaScriptPanel {
5174 - (void) _customButtonClicked {
5175 int count([buttons_ count]);
5180 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5182 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5183 [buttons addObjectsFromArray:buttons_];
5185 UIActionSheet *sheet = [[[UIActionSheet alloc]
5188 cancelButtonTitle:nil
5189 destructiveButtonTitle:nil
5190 otherButtonTitles:nil
5193 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5195 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5196 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5198 [sheet setContext:@"modify"];
5200 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5204 // We don't want to allow non-commercial packages to do custom things to the install button,
5205 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5206 - (void) customButtonClicked {
5208 [super customButtonClicked];
5210 [self _customButtonClicked];
5213 - (void) reloadButtonClicked {
5214 // Don't reload a package view by clicking the button.
5217 - (void) applyLoadingTitle {
5218 // Don't show "Loading" as the title. Ever.
5221 - (UIBarButtonItem *) rightButton {
5226 - (id) initWithDatabase:(Database *)database {
5227 if ((self = [super init]) != nil) {
5228 database_ = database;
5229 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5230 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5234 - (void) setPackage:(Package *)package {
5235 if (package_ != nil) {
5236 [package_ autorelease];
5245 [buttons_ removeAllObjects];
5247 if (package != nil) {
5250 package_ = [package retain];
5251 name_ = [[package id] retain];
5252 commercial_ = [package isCommercial];
5254 if ([package_ mode] != nil)
5255 [buttons_ addObject:UCLocalize("CLEAR")];
5256 if ([package_ source] == nil);
5257 else if ([package_ upgradableAndEssential:NO])
5258 [buttons_ addObject:UCLocalize("UPGRADE")];
5259 else if ([package_ uninstalled])
5260 [buttons_ addObject:UCLocalize("INSTALL")];
5262 [buttons_ addObject:UCLocalize("REINSTALL")];
5263 if (![package_ uninstalled])
5264 [buttons_ addObject:UCLocalize("REMOVE")];
5271 switch ([buttons_ count]) {
5272 case 0: title = nil; break;
5273 case 1: title = [buttons_ objectAtIndex:0]; break;
5274 default: title = UCLocalize("MODIFY"); break;
5277 button_ = [[UIBarButtonItem alloc]
5279 style:UIBarButtonItemStylePlain
5281 action:@selector(customButtonClicked)
5285 - (bool) isLoading {
5286 return commercial_ ? [super isLoading] : false;
5289 - (void) reloadData {
5290 [self setPackage:[database_ packageWithName:name_]];
5295 /* Package Table {{{ */
5296 @interface PackageTable : UIView <
5297 UITableViewDataSource,
5300 _transient Database *database_;
5301 NSMutableArray *packages_;
5302 NSMutableArray *sections_;
5304 NSMutableArray *index_;
5305 NSMutableDictionary *indices_;
5311 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5313 - (void) setDelegate:(id)delegate;
5315 - (void) reloadData;
5316 - (void) resetCursor;
5318 - (UITableView *) list;
5320 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5322 - (void) deselectWithAnimation:(BOOL)animated;
5326 @implementation PackageTable
5329 [packages_ release];
5330 [sections_ release];
5338 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5339 NSInteger count([sections_ count]);
5340 return count == 0 ? 1 : count;
5343 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5344 if ([sections_ count] == 0)
5346 return [[sections_ objectAtIndex:section] name];
5349 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5350 if ([sections_ count] == 0)
5352 return [[sections_ objectAtIndex:section] count];
5355 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5356 Section *section([sections_ objectAtIndex:[path section]]);
5357 NSInteger row([path row]);
5358 Package *package([packages_ objectAtIndex:([section row] + row)]);
5362 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5363 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5365 cell = [[[PackageCell alloc] init] autorelease];
5366 [cell setPackage:[self packageAtIndexPath:path]];
5370 - (void) deselectWithAnimation:(BOOL)animated {
5371 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5374 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5375 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5378 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5379 Package *package([self packageAtIndexPath:path]);
5380 package = [database_ packageWithName:[package id]];
5381 [target_ performSelector:action_ withObject:package];
5385 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5386 return [packages_ count] > 20 ? index_ : nil;
5389 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5393 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5394 if ((self = [super initWithFrame:frame]) != nil) {
5395 database_ = database;
5400 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5401 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5403 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5404 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5406 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5407 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5408 [list_ setRowHeight:73.0f];
5409 [self addSubview:list_];
5411 [list_ setDataSource:self];
5412 [list_ setDelegate:self];
5416 - (void) setDelegate:(id)delegate {
5417 delegate_ = delegate;
5420 - (bool) hasPackage:(Package *)package {
5424 - (void) reloadData {
5425 NSArray *packages = [database_ packages];
5427 [packages_ removeAllObjects];
5428 [sections_ removeAllObjects];
5430 _profile(PackageTable$reloadData$Filter)
5431 for (Package *package in packages)
5432 if ([self hasPackage:package])
5433 [packages_ addObject:package];
5436 [index_ removeAllObjects];
5437 [indices_ removeAllObjects];
5439 Section *section = nil;
5441 _profile(PackageTable$reloadData$Section)
5442 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5446 _profile(PackageTable$reloadData$Section$Package)
5447 package = [packages_ objectAtIndex:offset];
5448 index = [package index];
5451 if (section == nil || [section index] != index) {
5452 _profile(PackageTable$reloadData$Section$Allocate)
5453 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5456 [index_ addObject:[section name]];
5457 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5459 _profile(PackageTable$reloadData$Section$Add)
5460 [sections_ addObject:section];
5464 [section addToCount];
5468 _profile(PackageTable$reloadData$List)
5473 - (void) resetCursor {
5474 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5477 - (UITableView *) list {
5481 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5482 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5487 /* Filtered Package Table {{{ */
5488 @interface FilteredPackageTable : PackageTable {
5494 - (void) setObject:(id)object;
5495 - (void) setObject:(id)object forFilter:(SEL)filter;
5497 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5501 @implementation FilteredPackageTable
5509 - (void) setFilter:(SEL)filter {
5512 /* XXX: this is an unsafe optimization of doomy hell */
5513 Method method(class_getInstanceMethod([Package class], filter));
5514 _assert(method != NULL);
5515 imp_ = method_getImplementation(method);
5516 _assert(imp_ != NULL);
5519 - (void) setObject:(id)object {
5525 object_ = [object retain];
5528 - (void) setObject:(id)object forFilter:(SEL)filter {
5529 [self setFilter:filter];
5530 [self setObject:object];
5533 - (bool) hasPackage:(Package *)package {
5534 _profile(FilteredPackageTable$hasPackage)
5535 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5539 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5540 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5541 [self setFilter:filter];
5542 object_ = [object retain];
5550 /* Filtered Package Controller {{{ */
5551 @interface FilteredPackageController : CYViewController {
5552 _transient Database *database_;
5553 FilteredPackageTable *packages_;
5557 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5561 @implementation FilteredPackageController
5564 [packages_ release];
5570 - (void) viewDidAppear:(BOOL)animated {
5571 [super viewDidAppear:animated];
5572 [packages_ deselectWithAnimation:animated];
5575 - (void) didSelectPackage:(Package *)package {
5576 PackageController *view([delegate_ packageController]);
5577 [view setPackage:package];
5578 [view setDelegate:delegate_];
5579 [[self navigationController] pushViewController:view animated:YES];
5582 - (NSString *) title { return title_; }
5584 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5585 if ((self = [super init]) != nil) {
5586 database_ = database;
5587 title_ = [title copy];
5588 [[self navigationItem] setTitle:title_];
5590 packages_ = [[FilteredPackageTable alloc]
5591 initWithFrame:[[self view] bounds]
5594 action:@selector(didSelectPackage:)
5599 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5600 [[self view] addSubview:packages_];
5604 - (void) reloadData {
5605 [packages_ reloadData];
5608 - (void) setDelegate:(id)delegate {
5609 [super setDelegate:delegate];
5610 [packages_ setDelegate:delegate];
5617 /* Add Source Controller {{{ */
5618 @interface AddSourceController : CYViewController {
5619 _transient Database *database_;
5622 - (id) initWithDatabase:(Database *)database;
5626 @implementation AddSourceController
5628 - (id) initWithDatabase:(Database *)database {
5629 if ((self = [super init]) != nil) {
5630 database_ = database;
5636 /* Source Cell {{{ */
5637 @interface SourceCell : UITableViewCell <
5642 NSString *description_;
5644 ContentView *content_;
5647 - (void) setSource:(Source *)source;
5651 @implementation SourceCell
5653 - (void) clearSource {
5656 [description_ release];
5665 - (void) setSource:(Source *)source {
5669 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5671 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5672 icon_ = [icon_ retain];
5674 origin_ = [[source name] retain];
5675 label_ = [[source uri] retain];
5676 description_ = [[source description] retain];
5678 [content_ setNeedsDisplay];
5687 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5688 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5689 UIView *content([self contentView]);
5690 CGRect bounds([content bounds]);
5692 content_ = [[ContentView alloc] initWithFrame:bounds];
5693 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5694 [content_ setBackgroundColor:[UIColor whiteColor]];
5695 [content addSubview:content_];
5697 [content_ setDelegate:self];
5698 [content_ setOpaque:YES];
5702 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5703 [super setSelected:selected animated:animated];
5704 [content_ setNeedsDisplay];
5707 - (void) drawContentRect:(CGRect)rect {
5708 bool selected([self isSelected]);
5709 float width(rect.size.width);
5712 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5719 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5723 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5727 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5732 /* Source Table {{{ */
5733 @interface SourceTable : CYViewController <
5734 UITableViewDataSource,
5737 _transient Database *database_;
5739 NSMutableArray *sources_;
5743 UIProgressHUD *hud_;
5746 //NSURLConnection *installer_;
5747 NSURLConnection *trivial_;
5748 NSURLConnection *trivial_bz2_;
5749 NSURLConnection *trivial_gz_;
5750 //NSURLConnection *automatic_;
5755 - (id) initWithDatabase:(Database *)database;
5757 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5761 @implementation SourceTable
5763 - (void) _deallocConnection:(NSURLConnection *)connection {
5764 if (connection != nil) {
5765 [connection cancel];
5766 //[connection setDelegate:nil];
5767 [connection release];
5779 //[self _deallocConnection:installer_];
5780 [self _deallocConnection:trivial_];
5781 [self _deallocConnection:trivial_gz_];
5782 [self _deallocConnection:trivial_bz2_];
5783 //[self _deallocConnection:automatic_];
5790 - (void) viewDidAppear:(BOOL)animated {
5791 [super viewDidAppear:animated];
5792 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5795 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5796 return offset_ == 0 ? 1 : 2;
5799 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5800 switch (section + (offset_ == 0 ? 1 : 0)) {
5801 case 0: return UCLocalize("ENTERED_BY_USER");
5802 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5808 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5809 int count = [sources_ count];
5811 case 0: return (offset_ == 0 ? count : offset_);
5812 case 1: return count - offset_;
5818 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5820 switch (indexPath.section) {
5821 case 0: idx = indexPath.row; break;
5822 case 1: idx = indexPath.row + offset_; break;
5826 return [sources_ objectAtIndex:idx];
5829 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5830 Source *source = [self sourceAtIndexPath:indexPath];
5831 return [source description] == nil ? 56 : 73;
5834 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5835 static NSString *cellIdentifier = @"SourceCell";
5837 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5838 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5839 [cell setSource:[self sourceAtIndexPath:indexPath]];
5844 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5845 return UITableViewCellAccessoryDisclosureIndicator;
5848 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5849 Source *source = [self sourceAtIndexPath:indexPath];
5851 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5852 initWithDatabase:database_
5853 title:[source label]
5854 filter:@selector(isVisibleInSource:)
5858 [packages setDelegate:delegate_];
5860 [[self navigationController] pushViewController:packages animated:YES];
5863 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5864 Source *source = [self sourceAtIndexPath:indexPath];
5865 return [source record] != nil;
5868 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5869 Source *source = [self sourceAtIndexPath:indexPath];
5870 [Sources_ removeObjectForKey:[source key]];
5871 [delegate_ syncData];
5875 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5878 @"./", @"Distribution",
5879 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5881 [delegate_ syncData];
5884 - (NSString *) getWarning {
5885 NSString *href(href_);
5886 NSRange colon([href rangeOfString:@"://"]);
5887 if (colon.location != NSNotFound)
5888 href = [href substringFromIndex:(colon.location + 3)];
5889 href = [href stringByAddingPercentEscapes];
5890 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5891 href = [href stringByCachingURLWithCurrentCDN];
5893 NSURL *url([NSURL URLWithString:href]);
5895 NSStringEncoding encoding;
5896 NSError *error(nil);
5898 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5899 return [warning length] == 0 ? nil : warning;
5903 - (void) _endConnection:(NSURLConnection *)connection {
5904 NSURLConnection **field = NULL;
5905 if (connection == trivial_)
5907 else if (connection == trivial_bz2_)
5908 field = &trivial_bz2_;
5909 else if (connection == trivial_gz_)
5910 field = &trivial_gz_;
5911 _assert(field != NULL);
5912 [connection release];
5917 trivial_bz2_ == nil &&
5923 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5926 UIAlertView *alert = [[[UIAlertView alloc]
5927 initWithTitle:UCLocalize("SOURCE_WARNING")
5930 cancelButtonTitle:UCLocalize("CANCEL")
5931 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5934 [alert setContext:@"warning"];
5935 [alert setNumberOfRows:1];
5939 } else if (error_ != nil) {
5940 UIAlertView *alert = [[[UIAlertView alloc]
5941 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5942 message:[error_ localizedDescription]
5944 cancelButtonTitle:UCLocalize("OK")
5945 otherButtonTitles:nil
5948 [alert setContext:@"urlerror"];
5951 UIAlertView *alert = [[[UIAlertView alloc]
5952 initWithTitle:UCLocalize("NOT_REPOSITORY")
5953 message:UCLocalize("NOT_REPOSITORY_EX")
5955 cancelButtonTitle:UCLocalize("OK")
5956 otherButtonTitles:nil
5959 [alert setContext:@"trivial"];
5963 [delegate_ setStatusBarShowsProgress:NO];
5964 [delegate_ removeProgressHUD:hud_];
5974 if (error_ != nil) {
5981 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5982 switch ([response statusCode]) {
5988 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5989 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5991 error_ = [error retain];
5992 [self _endConnection:connection];
5995 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5996 [self _endConnection:connection];
5999 - (NSString *) title { return UCLocalize("SOURCES"); }
6001 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6002 NSMutableURLRequest *request = [NSMutableURLRequest
6003 requestWithURL:[NSURL URLWithString:href]
6004 cachePolicy:NSURLRequestUseProtocolCachePolicy
6005 timeoutInterval:120.0
6008 [request setHTTPMethod:method];
6010 if (Machine_ != NULL)
6011 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6012 if (UniqueID_ != nil)
6013 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6015 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6017 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6020 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6021 NSString *context([alert context]);
6023 if ([context isEqualToString:@"source"]) {
6026 NSString *href = [[alert textField] text];
6028 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6030 if (![href hasSuffix:@"/"])
6031 href_ = [href stringByAppendingString:@"/"];
6034 href_ = [href_ retain];
6036 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6037 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6038 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6039 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6043 hud_ = [[delegate_ addProgressHUD] retain];
6044 [hud_ setText:UCLocalize("VERIFYING_URL")];
6053 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6054 } else if ([context isEqualToString:@"trivial"])
6055 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6056 else if ([context isEqualToString:@"urlerror"])
6057 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6058 else if ([context isEqualToString:@"warning"]) {
6073 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6077 - (id) initWithDatabase:(Database *)database {
6078 if ((self = [super init]) != nil) {
6079 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6080 [self updateButtonsForEditingStatus:NO animated:NO];
6082 database_ = database;
6083 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6085 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6086 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6087 [[self view] addSubview:list_];
6089 [list_ setDataSource:self];
6090 [list_ setDelegate:self];
6096 - (void) reloadData {
6098 if (!list.ReadMainList())
6101 [sources_ removeAllObjects];
6102 [sources_ addObjectsFromArray:[database_ sources]];
6104 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6107 int count([sources_ count]);
6109 for (int i = 0; i != count; i++) {
6110 if ([[sources_ objectAtIndex:i] record] == nil) break;
6114 [list_ setEditing:NO];
6115 [self updateButtonsForEditingStatus:NO animated:NO];
6119 - (void) addButtonClicked {
6120 /*[book_ pushPage:[[[AddSourceController alloc]
6125 UIAlertView *alert = [[[UIAlertView alloc]
6126 initWithTitle:UCLocalize("ENTER_APT_URL")
6129 cancelButtonTitle:UCLocalize("CANCEL")
6130 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6133 [alert setContext:@"source"];
6134 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6136 [alert setNumberOfRows:1];
6137 [alert addTextFieldWithValue:@"http://" label:@""];
6139 UITextInputTraits *traits = [[alert textField] textInputTraits];
6140 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6141 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6142 [traits setKeyboardType:UIKeyboardTypeURL];
6143 // XXX: UIReturnKeyDone
6144 [traits setReturnKeyType:UIReturnKeyNext];
6149 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6150 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
6151 initWithTitle:UCLocalize("ADD")
6152 style:UIBarButtonItemStylePlain
6154 action:@selector(addButtonClicked)
6156 [[self navigationItem] setLeftBarButtonItem:editing ? leftItem : [[self navigationItem] backBarButtonItem] animated:animated];
6159 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6160 initWithTitle:editing ? UCLocalize("DONE") : UCLocalize("EDIT")
6161 style:editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6163 action:@selector(editButtonClicked)
6165 [[self navigationItem] setRightBarButtonItem:rightItem animated:animated];
6166 [rightItem release];
6168 if (IsWildcat_ && !editing) {
6169 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6170 initWithTitle:UCLocalize("SETTINGS")
6171 style:UIBarButtonItemStylePlain
6173 action:@selector(settingsButtonClicked)
6175 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6176 [settingsItem release];
6180 - (void) settingsButtonClicked {
6181 [delegate_ showSettings];
6184 - (void) editButtonClicked {
6185 [list_ setEditing:![list_ isEditing] animated:YES];
6187 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6193 /* Installed Controller {{{ */
6194 @interface InstalledController : FilteredPackageController {
6198 - (id) initWithDatabase:(Database *)database;
6200 - (void) updateRoleButton;
6201 - (void) queueStatusDidChange;
6205 @implementation InstalledController
6211 - (NSString *) title { return UCLocalize("INSTALLED"); }
6213 - (id) initWithDatabase:(Database *)database {
6214 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6215 [self updateRoleButton];
6216 [self queueStatusDidChange];
6221 - (void) queueButtonClicked {
6226 - (void) queueStatusDidChange {
6229 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6230 initWithTitle:UCLocalize("QUEUE")
6231 style:UIBarButtonItemStyleDone
6233 action:@selector(queueButtonClicked)
6235 if (Queuing_) [[self navigationItem] setLeftBarButtonItem:queueItem];
6236 else [[self navigationItem] setLeftBarButtonItem:nil];
6237 [queueItem release];
6242 - (void) reloadData {
6243 [packages_ reloadData];
6246 - (void) updateRoleButton {
6247 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6248 initWithTitle:expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")
6249 style:expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6251 action:@selector(roleButtonClicked)
6253 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) [[self navigationItem] setRightBarButtonItem:rightItem];
6254 [rightItem release];
6257 - (void) roleButtonClicked {
6258 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6259 [packages_ reloadData];
6262 [self updateRoleButton];
6265 - (void) setDelegate:(id)delegate {
6266 [super setDelegate:delegate];
6267 [packages_ setDelegate:delegate];
6273 /* Home Controller {{{ */
6274 @interface HomeController : CYBrowserController {
6279 @implementation HomeController
6281 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6282 [super _setMoreHeaders:request];
6285 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6286 if (UniqueID_ != nil)
6287 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6289 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6292 - (void) aboutButtonClicked {
6293 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6295 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6296 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6297 [alert setCancelButtonIndex:0];
6300 @"Copyright (C) 2008-2010\n"
6301 "Jay Freeman (saurik)\n"
6302 "saurik@saurik.com\n"
6303 "http://www.saurik.com/"
6309 - (void) viewWillAppear:(BOOL)animated {
6310 [super viewWillAppear:animated];
6311 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6314 - (void) viewWillDisappear:(BOOL)animated {
6315 [super viewWillDisappear:animated];
6316 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6320 if ((self = [super init]) != nil) {
6321 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6322 initWithTitle:UCLocalize("ABOUT")
6323 style:UIBarButtonItemStylePlain
6325 action:@selector(aboutButtonClicked)
6332 /* Manage Controller {{{ */
6333 @interface ManageController : CYBrowserController {
6336 - (void) queueStatusDidChange;
6339 @implementation ManageController
6342 if ((self = [super init]) != nil) {
6343 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6345 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6346 initWithTitle:UCLocalize("SETTINGS")
6347 style:UIBarButtonItemStylePlain
6349 action:@selector(settingsButtonClicked)
6351 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6352 [settingsItem release];
6354 [self queueStatusDidChange];
6358 - (void) settingsButtonClicked {
6359 [delegate_ showSettings];
6363 - (void) queueButtonClicked {
6367 - (void) applyLoadingTitle {
6368 // No "Loading" title.
6371 - (void) applyRightButton {
6376 - (void) queueStatusDidChange {
6378 if (!IsWildcat_ && Queuing_) {
6379 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6380 initWithTitle:UCLocalize("QUEUE")
6381 style:UIBarButtonItemStyleDone
6383 action:@selector(queueButtonClicked)
6385 [[self navigationItem] setRightBarButtonItem:queueItem];
6387 [queueItem release];
6389 [[self navigationItem] setRightBarButtonItem:nil];
6394 - (bool) isLoading {
6401 /* Refresh Bar {{{ */
6402 @interface RefreshBar : UINavigationBar {
6403 UIProgressIndicator *indicator_;
6404 UITextLabel *prompt_;
6405 UIProgressBar *progress_;
6406 UINavigationButton *cancel_;
6411 @implementation RefreshBar
6413 - (void) positionViews {
6414 CGRect frame = [cancel_ frame];
6415 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6416 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6417 [cancel_ setFrame:frame];
6419 CGSize prgsize = {75, 100};
6421 [self frame].size.width - prgsize.width - 10,
6422 ([self frame].size.height - prgsize.height) / 2
6424 [progress_ setFrame:prgrect];
6426 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6427 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6428 CGRect indrect = {{indoffset, indoffset}, indsize};
6429 [indicator_ setFrame:indrect];
6431 CGSize prmsize = {215, indsize.height + 4};
6433 indoffset * 2 + indsize.width,
6434 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6436 [prompt_ setFrame:prmrect];
6439 - (void)setFrame:(CGRect)frame {
6440 [super setFrame:frame];
6442 [self positionViews];
6445 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6446 if ((self = [super initWithFrame:frame])) {
6447 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6449 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6450 [self setBarStyle:UIBarStyleBlack];
6452 UIBarStyle barstyle([self _barStyle:NO]);
6453 bool ugly(barstyle == UIBarStyleDefault);
6455 UIProgressIndicatorStyle style = ugly ?
6456 UIProgressIndicatorStyleMediumBrown :
6457 UIProgressIndicatorStyleMediumWhite;
6459 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6460 [indicator_ setStyle:style];
6461 [indicator_ startAnimation];
6462 [self addSubview:indicator_];
6464 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6465 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6466 [prompt_ setBackgroundColor:[UIColor clearColor]];
6467 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6468 [self addSubview:prompt_];
6470 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6471 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6472 [progress_ setStyle:0];
6473 [self addSubview:progress_];
6475 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6476 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6477 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6478 [cancel_ setBarStyle:barstyle];
6480 [self positionViews];
6485 [cancel_ removeFromSuperview];
6489 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6490 [progress_ setProgress:0];
6491 [self addSubview:cancel_];
6495 [cancel_ removeFromSuperview];
6498 - (void) setPrompt:(NSString *)prompt {
6499 [prompt_ setText:prompt];
6502 - (void) setProgress:(float)progress {
6503 [progress_ setProgress:progress];
6509 @class CYNavigationController;
6511 /* Cydia Tab Bar Controller {{{ */
6512 @interface CYTabBarController : UITabBarController {
6513 Database *database_;
6518 @implementation CYTabBarController
6520 /* XXX: some logic should probably go here related to
6521 freeing the view controllers on tab change */
6523 - (void) reloadData {
6524 size_t count([[self viewControllers] count]);
6525 for (size_t i(0); i != count; ++i) {
6526 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6531 - (id) initWithDatabase:(Database *)database {
6532 if ((self = [super init]) != nil) {
6533 database_ = database;
6540 /* Cydia Navigation Controller {{{ */
6541 @interface CYNavigationController : UINavigationController {
6542 _transient Database *database_;
6543 id<UINavigationControllerDelegate> delegate_;
6546 - (id) initWithDatabase:(Database *)database;
6547 - (void) reloadData;
6552 @implementation CYNavigationController
6554 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6555 // Inherit autorotation settings for modal parents.
6556 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6557 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6559 return [super shouldAutorotateToInterfaceOrientation:orientation];
6567 - (void) reloadData {
6568 size_t count([[self viewControllers] count]);
6569 for (size_t i(0); i != count; ++i) {
6570 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6575 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6576 delegate_ = delegate;
6579 - (id) initWithDatabase:(Database *)database {
6580 if ((self = [super init]) != nil) {
6581 database_ = database;
6587 /* Cydia:// Protocol {{{ */
6588 @interface CydiaURLProtocol : NSURLProtocol {
6593 @implementation CydiaURLProtocol
6595 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6596 NSURL *url([request URL]);
6599 NSString *scheme([[url scheme] lowercaseString]);
6600 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6605 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6609 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6610 id<NSURLProtocolClient> client([self client]);
6612 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6614 NSData *data(UIImagePNGRepresentation(icon));
6616 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6617 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6618 [client URLProtocol:self didLoadData:data];
6619 [client URLProtocolDidFinishLoading:self];
6623 - (void) startLoading {
6624 id<NSURLProtocolClient> client([self client]);
6625 NSURLRequest *request([self request]);
6627 NSURL *url([request URL]);
6628 NSString *href([url absoluteString]);
6630 NSString *path([href substringFromIndex:8]);
6631 NSRange slash([path rangeOfString:@"/"]);
6634 if (slash.location == NSNotFound) {
6638 command = [path substringToIndex:slash.location];
6639 path = [path substringFromIndex:(slash.location + 1)];
6642 Database *database([Database sharedInstance]);
6644 if ([command isEqualToString:@"package-icon"]) {
6647 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6648 Package *package([database packageWithName:path]);
6651 UIImage *icon([package icon]);
6652 [self _returnPNGWithImage:icon forRequest:request];
6653 } else if ([command isEqualToString:@"source-icon"]) {
6656 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6657 NSString *source(Simplify(path));
6658 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6660 icon = [UIImage applicationImageNamed:@"unknown.png"];
6661 [self _returnPNGWithImage:icon forRequest:request];
6662 } else if ([command isEqualToString:@"uikit-image"]) {
6665 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6666 UIImage *icon(_UIImageWithName(path));
6667 [self _returnPNGWithImage:icon forRequest:request];
6668 } else if ([command isEqualToString:@"section-icon"]) {
6671 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6672 NSString *section(Simplify(path));
6673 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6675 icon = [UIImage applicationImageNamed:@"unknown.png"];
6676 [self _returnPNGWithImage:icon forRequest:request];
6678 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6682 - (void) stopLoading {
6688 /* Sections Controller {{{ */
6689 @interface SectionsController : CYViewController <
6690 UITableViewDataSource,
6693 _transient Database *database_;
6694 NSMutableArray *sections_;
6695 NSMutableArray *filtered_;
6701 - (id) initWithDatabase:(Database *)database;
6702 - (void) reloadData;
6705 - (void) editButtonClicked;
6709 @implementation SectionsController
6712 [list_ setDataSource:nil];
6713 [list_ setDelegate:nil];
6715 [sections_ release];
6716 [filtered_ release];
6718 [accessory_ release];
6722 - (void) viewDidAppear:(BOOL)animated {
6723 [super viewDidAppear:animated];
6724 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6727 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6728 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6732 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6733 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6736 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6740 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6741 static NSString *reuseIdentifier = @"SectionCell";
6743 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6744 if (cell == nil) cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6745 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6750 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6754 Section *section = [self sectionAtIndexPath:indexPath];
6755 NSString *name = [section name];
6758 if ([indexPath row] == 0) {
6761 title = UCLocalize("ALL_PACKAGES");
6764 name = [NSString stringWithString:name];
6765 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6768 title = UCLocalize("NO_SECTION");
6772 FilteredPackageController *table = [[[FilteredPackageController alloc]
6773 initWithDatabase:database_
6775 filter:@selector(isVisibleInSection:)
6779 [table setDelegate:delegate_];
6781 [[self navigationController] pushViewController:table animated:YES];
6784 - (NSString *) title { return UCLocalize("SECTIONS"); }
6786 - (id) initWithDatabase:(Database *)database {
6787 if ((self = [super init]) != nil) {
6788 database_ = database;
6790 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6792 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6793 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6795 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6796 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6797 [list_ setRowHeight:45.0f];
6798 [[self view] addSubview:list_];
6800 [list_ setDataSource:self];
6801 [list_ setDelegate:self];
6807 - (void) reloadData {
6808 NSArray *packages = [database_ packages];
6810 [sections_ removeAllObjects];
6811 [filtered_ removeAllObjects];
6814 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6815 SectionMap sections;
6816 sections.resize(64);
6818 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6822 for (Package *package in packages) {
6823 NSString *name([package section]);
6824 NSString *key(name == nil ? @"" : name);
6829 _profile(SectionsView$reloadData$Section)
6830 section = §ions[key];
6831 if (*section == nil) {
6832 _profile(SectionsView$reloadData$Section$Allocate)
6833 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6838 [*section addToCount];
6840 _profile(SectionsView$reloadData$Filter)
6841 if (![package valid] || ![package visible])
6845 [*section addToRow];
6849 _profile(SectionsView$reloadData$Section)
6850 section = [sections objectForKey:key];
6851 if (section == nil) {
6852 _profile(SectionsView$reloadData$Section$Allocate)
6853 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6854 [sections setObject:section forKey:key];
6859 [section addToCount];
6861 _profile(SectionsView$reloadData$Filter)
6862 if (![package valid] || ![package visible])
6872 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6873 [sections_ addObject:i->second];
6875 [sections_ addObjectsFromArray:[sections allValues]];
6878 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6880 for (Section *section in sections_) {
6881 size_t count([section row]);
6885 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6886 [section setCount:count];
6887 [filtered_ addObject:section];
6890 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6891 initWithTitle:[sections_ count] == 0 ? nil : UCLocalize("EDIT")
6892 style:UIBarButtonItemStylePlain
6894 action:@selector(editButtonClicked)
6896 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] != nil];
6897 [rightItem release];
6903 - (void) resetView {
6905 [self editButtonClicked];
6908 - (void) editButtonClicked {
6909 if ((editing_ = !editing_))
6912 [delegate_ updateData];
6914 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6915 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6916 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6919 - (UIView *) accessoryView {
6925 /* Changes Controller {{{ */
6926 @interface ChangesController : CYViewController <
6927 UITableViewDataSource,
6930 _transient Database *database_;
6931 CFMutableArrayRef packages_;
6932 NSMutableArray *sections_;
6935 BOOL hasSentFirstLoad_;
6938 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6939 - (void) reloadData;
6943 @implementation ChangesController
6946 [list_ setDelegate:nil];
6947 [list_ setDataSource:nil];
6949 CFRelease(packages_);
6951 [sections_ release];
6956 - (void) viewDidAppear:(BOOL)animated {
6957 [super viewDidAppear:animated];
6958 if (!hasSentFirstLoad_) {
6959 hasSentFirstLoad_ = YES;
6960 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6962 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6966 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6967 NSInteger count([sections_ count]);
6968 return count == 0 ? 1 : count;
6971 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6972 if ([sections_ count] == 0)
6974 return [[sections_ objectAtIndex:section] name];
6977 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6978 if ([sections_ count] == 0)
6980 return [[sections_ objectAtIndex:section] count];
6983 - (Package *) packageAtIndex:(NSUInteger)index {
6984 return (Package *) CFArrayGetValueAtIndex(packages_, index);
6987 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6988 Section *section([sections_ objectAtIndex:[path section]]);
6989 NSInteger row([path row]);
6990 return [self packageAtIndex:([section row] + row)];
6993 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6994 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6996 cell = [[[PackageCell alloc] init] autorelease];
6997 [cell setPackage:[self packageAtIndexPath:path]];
7001 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7002 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7005 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7006 Package *package([self packageAtIndexPath:path]);
7007 PackageController *view([delegate_ packageController]);
7008 [view setDelegate:delegate_];
7009 [view setPackage:package];
7010 [[self navigationController] pushViewController:view animated:YES];
7014 - (void) refreshButtonClicked {
7015 [delegate_ beginUpdate];
7016 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7019 - (void) upgradeButtonClicked {
7020 [delegate_ distUpgrade];
7023 - (NSString *) title { return UCLocalize("CHANGES"); }
7025 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7026 if ((self = [super init]) != nil) {
7027 database_ = database;
7028 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7030 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7032 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7034 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7035 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7036 [list_ setRowHeight:73.0f];
7037 [[self view] addSubview:list_];
7039 [list_ setDataSource:self];
7040 [list_ setDelegate:self];
7042 delegate_ = delegate;
7046 - (void) _reloadPackages:(NSArray *)packages {
7048 for (Package *package in packages)
7050 [package uninstalled] && [package valid] && [package visible] ||
7051 [package upgradableAndEssential:YES]
7053 CFArrayAppendValue(packages_, package);
7056 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7060 - (void) reloadData {
7061 NSArray *packages = [database_ packages];
7063 CFArrayRemoveAllValues(packages_);
7065 [sections_ removeAllObjects];
7068 UIProgressHUD *hud([delegate_ addProgressHUD]);
7070 [hud setText:@"Loading Changes"];
7071 //NSLog(@"HUD:%@::%@", delegate_, hud);
7072 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7073 [delegate_ removeProgressHUD:hud];
7075 [self _reloadPackages:packages];
7078 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7079 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7080 Section *section = nil;
7084 bool unseens = false;
7086 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7088 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7089 Package *package = [self packageAtIndex:offset];
7091 BOOL uae = [package upgradableAndEssential:YES];
7097 _profile(ChangesController$reloadData$Remember)
7098 seen = [package seen];
7101 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7106 name = UCLocalize("UNKNOWN");
7108 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7112 _profile(ChangesController$reloadData$Allocate)
7113 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7114 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7115 [sections_ addObject:section];
7119 [section addToCount];
7120 } else if ([package ignored])
7121 [ignored addToCount];
7124 [upgradable addToCount];
7129 CFRelease(formatter);
7132 Section *last = [sections_ lastObject];
7133 size_t count = [last count];
7134 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7135 [sections_ removeLastObject];
7138 if ([ignored count] != 0)
7139 [sections_ insertObject:ignored atIndex:0];
7141 [sections_ insertObject:upgradable atIndex:0];
7145 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7146 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7147 style:UIBarButtonItemStylePlain
7149 action:@selector(upgradeButtonClicked)
7151 if (upgrades_ > 0) [[self navigationItem] setRightBarButtonItem:rightItem];
7152 [rightItem release];
7154 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
7155 initWithTitle:UCLocalize("REFRESH")
7156 style:UIBarButtonItemStylePlain
7158 action:@selector(refreshButtonClicked)
7160 if (![delegate_ updating]) [[self navigationItem] setLeftBarButtonItem:leftItem];
7166 /* Search Controller {{{ */
7167 @interface SearchController : FilteredPackageController <
7170 UISearchBar *search_;
7173 - (id) initWithDatabase:(Database *)database;
7174 - (void) reloadData;
7178 @implementation SearchController
7185 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7186 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7187 [search_ resignFirstResponder];
7191 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7192 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7196 - (NSString *) title { return nil; }
7198 - (id) initWithDatabase:(Database *)database {
7199 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7202 - (void)viewDidAppear:(BOOL)animated {
7203 [super viewDidAppear:animated];
7205 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7206 [search_ layoutSubviews];
7207 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7208 UITextField *textField = [search_ searchField];
7209 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7210 [search_ setDelegate:self];
7211 [textField setEnablesReturnKeyAutomatically:NO];
7212 [[self navigationItem] setTitleView:textField];
7216 - (void) _reloadData {
7219 - (void) reloadData {
7220 _profile(SearchController$reloadData)
7221 [packages_ reloadData];
7224 [packages_ resetCursor];
7227 - (void) didSelectPackage:(Package *)package {
7228 [search_ resignFirstResponder];
7229 [super didSelectPackage:package];
7234 /* Settings Controller {{{ */
7235 @interface SettingsController : CYViewController <
7236 UITableViewDataSource,
7239 _transient Database *database_;
7242 UITableView *table_;
7243 id subscribedSwitch_;
7245 UITableViewCell *subscribedCell_;
7246 UITableViewCell *ignoredCell_;
7249 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7253 @implementation SettingsController
7257 if (package_ != nil)
7260 [subscribedSwitch_ release];
7261 [ignoredSwitch_ release];
7262 [subscribedCell_ release];
7263 [ignoredCell_ release];
7268 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7269 if (package_ == nil)
7275 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7276 if (package_ == nil)
7282 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7283 return UCLocalize("SHOW_ALL_CHANGES_EX");
7286 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7287 if (package_ == nil)
7290 NSMutableDictionary *metadata([package_ metadata]);
7293 if (NSNumber *number = [metadata objectForKey:key])
7294 before = [number boolValue];
7298 if (value != before) {
7299 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7301 [delegate_ updateData];
7305 - (void) onSubscribed:(id)control {
7306 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7309 - (void) onIgnored:(id)control {
7310 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
7313 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7314 if (package_ == nil)
7317 switch ([indexPath row]) {
7318 case 0: return subscribedCell_;
7319 case 1: return ignoredCell_;
7327 - (NSString *) title { return UCLocalize("SETTINGS"); }
7329 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7330 if ((self = [super init])) {
7331 database_ = database;
7332 name_ = [package retain];
7334 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7336 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7337 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7338 [[self view] addSubview:table_];
7340 subscribedSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7341 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7342 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7344 ignoredSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7345 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7346 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7348 subscribedCell_ = [[UITableViewCell alloc] init];
7349 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7350 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7351 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7353 ignoredCell_ = [[UITableViewCell alloc] init];
7354 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7355 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7356 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7358 [table_ setDataSource:self];
7359 [table_ setDelegate:self];
7364 - (void) reloadData {
7365 if (package_ != nil)
7366 [package_ autorelease];
7367 package_ = [database_ packageWithName:name_];
7368 if (package_ != nil) {
7370 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7371 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7374 [table_ reloadData];
7379 /* Signature Controller {{{ */
7380 @interface SignatureController : CYBrowserController {
7381 _transient Database *database_;
7385 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7389 @implementation SignatureController
7396 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7398 [super webView:view didClearWindowObject:window forFrame:frame];
7401 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7402 if ((self = [super init]) != nil) {
7403 database_ = database;
7404 package_ = [package retain];
7409 - (void) reloadData {
7410 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7416 /* Role Controller {{{ */
7417 @interface RoleController : CYViewController <
7418 UITableViewDataSource,
7421 _transient Database *database_;
7423 UITableView *table_;
7424 UISegmentedControl *segment_;
7428 - (void) showDoneButton;
7429 - (void) resizeSegmentedControl;
7433 @implementation RoleController
7437 [container_ release];
7442 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7443 if ((self = [super init])) {
7444 database_ = database;
7445 roledelegate_ = delegate;
7447 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7449 NSArray *items = [NSArray arrayWithObjects:
7451 UCLocalize("HACKER"),
7452 UCLocalize("DEVELOPER"),
7454 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7455 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7456 [container_ addSubview:segment_];
7459 if ([Role_ isEqualToString:@"User"]) index = 0;
7460 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7461 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7463 [segment_ setSelectedSegmentIndex:index];
7464 [self showDoneButton];
7467 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7468 [self resizeSegmentedControl];
7470 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7471 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7472 [table_ setDelegate:self];
7473 [table_ setDataSource:self];
7474 [[self view] addSubview:table_];
7475 [table_ reloadData];
7479 - (void) resizeSegmentedControl {
7480 CGFloat width = [[self view] frame].size.width;
7481 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7484 - (void) viewWillAppear:(BOOL)animated {
7485 [super viewWillAppear:animated];
7487 [self resizeSegmentedControl];
7490 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7491 [self resizeSegmentedControl];
7494 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7495 [self resizeSegmentedControl];
7499 NSString *role(nil);
7501 switch ([segment_ selectedSegmentIndex]) {
7502 case 0: role = @"User"; break;
7503 case 1: role = @"Hacker"; break;
7504 case 2: role = @"Developer"; break;
7509 if (![role isEqualToString:Role_]) {
7510 bool rolling(Role_ == nil);
7513 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7517 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7522 [roledelegate_ loadData];
7524 [roledelegate_ updateData];
7528 - (void) segmentChanged:(UISegmentedControl *)control {
7529 [self showDoneButton];
7532 - (void) doneButtonClicked {
7534 [[self navigationController] dismissModalViewControllerAnimated:YES];
7537 - (void) showDoneButton {
7538 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7539 initWithTitle:UCLocalize("DONE")
7540 style:UIBarButtonItemStyleDone
7542 action:@selector(doneButtonClicked)
7544 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] == nil];
7545 [rightItem release];
7548 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7549 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7553 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7557 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7558 return nil; // This method is required by the protocol.
7561 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7563 return UCLocalize("ROLE_EX");
7565 return [NSString stringWithFormat:
7566 @"%@: %@\n%@: %@\n%@: %@",
7567 UCLocalize("USER"), UCLocalize("USER_EX"),
7568 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7569 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7574 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7575 if (section == 3) return 44.0f;
7579 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7580 if (section == 3) return container_;
7586 /* Stash Controller {{{ */
7587 @interface CYStashController : CYViewController {
7588 UIActivityIndicatorView *spinner_;
7594 @implementation CYStashController
7596 if ((self = [super init])) {
7597 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7599 spinner_ = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
7600 CGRect spinrect = [spinner_ frame];
7601 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7602 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7603 [spinner_ setFrame:spinrect];
7604 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7605 [[self view] addSubview:spinner_];
7607 [spinner_ startAnimating];
7610 captrect.size.width = [[self view] frame].size.width;
7611 captrect.size.height = 40.0f;
7612 captrect.origin.x = 0;
7613 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7614 caption_ = [[UILabel alloc] initWithFrame:captrect];
7615 [caption_ setText:@"Initializing Filesystem"];
7616 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7617 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7618 [caption_ setTextColor:[UIColor whiteColor]];
7619 [caption_ setBackgroundColor:[UIColor clearColor]];
7620 [caption_ setShadowColor:[UIColor blackColor]];
7621 [caption_ setTextAlignment:UITextAlignmentCenter];
7622 [[self view] addSubview:caption_];
7626 statusrect.size.width = [[self view] frame].size.width;
7627 statusrect.size.height = 30.0f;
7628 statusrect.origin.x = 0;
7629 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7630 status_ = [[UILabel alloc] initWithFrame:statusrect];
7631 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7632 [status_ setText:@"(Cydia will exit when complete.)"];
7633 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7634 [status_ setTextColor:[UIColor whiteColor]];
7635 [status_ setBackgroundColor:[UIColor clearColor]];
7636 [status_ setShadowColor:[UIColor blackColor]];
7637 [status_ setTextAlignment:UITextAlignmentCenter];
7638 [[self view] addSubview:status_];
7643 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7644 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7649 /* Cydia Container {{{ */
7650 @interface CYContainer : UIViewController <ProgressDelegate> {
7651 _transient Database *database_;
7652 RefreshBar *refreshbar_;
7657 UITabBarController *root_;
7660 - (void) setTabBarController:(UITabBarController *)controller;
7662 - (void) dropBar:(BOOL)animated;
7663 - (void) beginUpdate;
7664 - (void) raiseBar:(BOOL)animated;
7669 @implementation CYContainer
7671 - (BOOL) _reallyWantsFullScreenLayout {
7675 // NOTE: UIWindow only sends the top controller these messages,
7676 // So we have to forward them on.
7678 - (void) viewDidAppear:(BOOL)animated {
7679 [super viewDidAppear:animated];
7680 [root_ viewDidAppear:animated];
7683 - (void) viewWillAppear:(BOOL)animated {
7684 [super viewWillAppear:animated];
7685 [root_ viewWillAppear:animated];
7688 - (void) viewDidDisappear:(BOOL)animated {
7689 [super viewDidDisappear:animated];
7690 [root_ viewDidDisappear:animated];
7693 - (void) viewWillDisappear:(BOOL)animated {
7694 [super viewWillDisappear:animated];
7695 [root_ viewWillDisappear:animated];
7698 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7699 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7702 - (void) setTabBarController:(UITabBarController *)controller {
7704 [[self view] addSubview:[root_ view]];
7707 - (void) setUpdate:(NSDate *)date {
7711 - (void) beginUpdate {
7713 [refreshbar_ start];
7718 detachNewThreadSelector:@selector(performUpdate)
7724 - (void) performUpdate { _pooled
7726 status.setDelegate(self);
7727 [database_ updateWithStatus:status];
7730 performSelectorOnMainThread:@selector(completeUpdate)
7736 - (void) completeUpdate {
7737 if (!updating_) return;
7740 [self raiseBar:YES];
7742 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7745 - (void) cancelUpdate {
7747 [self raiseBar:YES];
7749 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7752 - (void) cancelPressed {
7753 [self cancelUpdate];
7760 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7761 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7764 - (void) startProgress {
7767 - (void) setProgressTitle:(NSString *)title {
7769 performSelectorOnMainThread:@selector(_setProgressTitle:)
7775 - (bool) isCancelling:(size_t)received {
7779 - (void) setProgressPercent:(float)percent {
7781 performSelectorOnMainThread:@selector(_setProgressPercent:)
7782 withObject:[NSNumber numberWithFloat:percent]
7787 - (void) addProgressOutput:(NSString *)output {
7789 performSelectorOnMainThread:@selector(_addProgressOutput:)
7795 - (void) _setProgressTitle:(NSString *)title {
7796 [refreshbar_ setPrompt:title];
7799 - (void) _setProgressPercent:(NSNumber *)percent {
7800 [refreshbar_ setProgress:[percent floatValue]];
7803 - (void) _addProgressOutput:(NSString *)output {
7806 - (void) setUpdateDelegate:(id)delegate {
7807 updatedelegate_ = delegate;
7810 - (CGFloat) statusBarHeight {
7811 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7812 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7814 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7818 - (void) dropBar:(BOOL)animated {
7819 if (dropped_) return;
7822 [[self view] addSubview:refreshbar_];
7824 CGFloat sboffset = [self statusBarHeight];
7826 CGRect barframe = [refreshbar_ frame];
7827 barframe.origin.y = sboffset;
7828 [refreshbar_ setFrame:barframe];
7830 if (animated) [UIView beginAnimations:nil context:NULL];
7831 CGRect viewframe = [[root_ view] frame];
7832 viewframe.origin.y += barframe.size.height + sboffset;
7833 viewframe.size.height -= barframe.size.height + sboffset;
7834 [[root_ view] setFrame:viewframe];
7835 if (animated) [UIView commitAnimations];
7837 // Ensure bar has the proper width for our view, it might have changed
7838 barframe.size.width = viewframe.size.width;
7839 [refreshbar_ setFrame:barframe];
7841 // XXX: fix Apple's layout bug
7842 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7845 - (void) raiseBar:(BOOL)animated {
7846 if (!dropped_) return;
7849 [refreshbar_ removeFromSuperview];
7851 CGFloat sboffset = [self statusBarHeight];
7853 if (animated) [UIView beginAnimations:nil context:NULL];
7854 CGRect barframe = [refreshbar_ frame];
7855 CGRect viewframe = [[root_ view] frame];
7856 viewframe.origin.y -= barframe.size.height + sboffset;
7857 viewframe.size.height += barframe.size.height + sboffset;
7858 [[root_ view] setFrame:viewframe];
7859 if (animated) [UIView commitAnimations];
7861 // XXX: fix Apple's layout bug
7862 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7865 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7866 // XXX: fix Apple's layout bug
7867 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7870 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7876 // XXX: fix Apple's layout bug
7877 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7880 - (void) statusBarFrameChanged:(NSNotification *)notification {
7888 [refreshbar_ release];
7889 [[NSNotificationCenter defaultCenter] removeObserver:self];
7893 - (id) initWithDatabase:(Database *)database {
7894 if ((self = [super init]) != nil) {
7895 database_ = database;
7897 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7898 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7900 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7917 @interface Cydia : UIApplication <
7918 ConfirmationControllerDelegate,
7919 ProgressControllerDelegate,
7921 UINavigationControllerDelegate
7924 CYContainer *container_;
7927 NSMutableArray *essential_;
7928 NSMutableArray *broken_;
7930 Database *database_;
7934 UIKeyboard *keyboard_;
7935 UIProgressHUD *hud_;
7937 SectionsController *sections_;
7938 ChangesController *changes_;
7939 ManageController *manage_;
7940 SearchController *search_;
7941 SourceTable *sources_;
7942 InstalledController *installed_;
7945 CYStashController *stash_;
7950 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7951 - (void) setPage:(CYViewController *)page;
7956 static _finline void _setHomePage(Cydia *self) {
7957 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7960 @implementation Cydia
7962 - (void) beginUpdate {
7963 [container_ beginUpdate];
7967 return [container_ updating];
7970 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7975 if ([broken_ count] != 0) {
7976 int count = [broken_ count];
7978 UIAlertView *alert = [[[UIAlertView alloc]
7979 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7980 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7982 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7983 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
7986 [alert setContext:@"fixhalf"];
7988 } else if (!Ignored_ && [essential_ count] != 0) {
7989 int count = [essential_ count];
7991 UIAlertView *alert = [[[UIAlertView alloc]
7992 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7993 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
7995 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
7996 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
7999 [alert setContext:@"upgrade"];
8004 - (void) _saveConfig {
8007 NSString *error(nil);
8008 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8010 NSError *error(nil);
8011 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8012 NSLog(@"failure to save metadata data: %@", error);
8015 NSLog(@"failure to serialize metadata: %@", error);
8023 - (void) _updateData {
8026 /* XXX: this is just stupid */
8027 if (tag_ != 1 && sections_ != nil)
8028 [sections_ reloadData];
8029 if (tag_ != 2 && changes_ != nil)
8030 [changes_ reloadData];
8031 if (tag_ != 4 && search_ != nil)
8032 [search_ reloadData];
8034 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8037 - (int)indexOfTabWithTag:(int)tag {
8039 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8040 if ([[controller tabBarItem] tag] == tag) return i;
8047 - (void) _refreshIfPossible {
8048 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8050 bool recently = false;
8051 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8052 if (update != nil) {
8053 NSTimeInterval interval([update timeIntervalSinceNow]);
8054 if (interval <= 0 && interval > -(15*60))
8058 // Don't automatic refresh if:
8059 // - We already refreshed recently.
8060 // - We already auto-refreshed this launch.
8061 // - Auto-refresh is disabled.
8062 if (recently || loaded_ || ManualRefresh) {
8063 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8065 // If we are cancelling due to ManualRefresh or a recent refresh
8066 // we need to make sure it knows it's already loaded.
8070 // We are going to load, so remember that.
8074 SCNetworkReachabilityFlags flags; {
8075 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8076 SCNetworkReachabilityGetFlags(reachability, &flags);
8077 CFRelease(reachability);
8080 // XXX: this elaborate mess is what Apple is using to determine this? :(
8081 // XXX: do we care if the user has to intervene? maybe that's ok?
8083 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8084 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8085 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8086 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8087 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8088 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8092 // If we can reach the server, auto-refresh!
8094 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8099 - (void) refreshIfPossible {
8100 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8103 - (void) _reloadData {
8104 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8105 [hud setText:UCLocalize("RELOADING_DATA")];
8107 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8109 if (hud) [self removeProgressHUD:hud];
8113 [essential_ removeAllObjects];
8114 [broken_ removeAllObjects];
8116 NSArray *packages([database_ packages]);
8117 for (Package *package in packages) {
8119 [broken_ addObject:package];
8120 if ([package upgradableAndEssential:NO]) {
8121 if ([package essential])
8122 [essential_ addObject:package];
8127 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8129 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8130 [changesItem setBadgeValue:badge];
8131 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8133 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8134 [self setApplicationBadge:badge];
8136 [self setApplicationBadgeString:badge];
8138 [changesItem setBadgeValue:nil];
8139 [changesItem setAnimatedBadge:NO];
8141 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8142 [self removeApplicationBadge];
8143 else // XXX: maybe use setApplicationBadgeString also?
8144 [self setApplicationIconBadgeNumber:0];
8149 [self refreshIfPossible];
8152 - (void) updateData {
8153 [database_ setVisible];
8162 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8163 _assert(file != NULL);
8165 for (NSString *key in [Sources_ allKeys]) {
8166 NSDictionary *source([Sources_ objectForKey:key]);
8168 fprintf(file, "%s %s %s\n",
8169 [[source objectForKey:@"Type"] UTF8String],
8170 [[source objectForKey:@"URI"] UTF8String],
8171 [[source objectForKey:@"Distribution"] UTF8String]
8179 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8180 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8181 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8182 [container_ presentModalViewController:navigation animated:YES];
8185 detachNewThreadSelector:@selector(update_)
8188 title:UCLocalize("UPDATING_SOURCES")
8192 - (void) reloadData {
8193 @synchronized (self) {
8199 pkgProblemResolver *resolver = [database_ resolver];
8201 resolver->InstallProtect();
8202 if (!resolver->Resolve(true))
8206 - (CGRect) popUpBounds {
8207 return [[tabbar_ view] bounds];
8211 if (![database_ prepare])
8214 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8215 [page setDelegate:self];
8216 CYNavigationController *confirm_ = [[CYNavigationController alloc] initWithRootViewController:page];
8217 [confirm_ setDelegate:self];
8219 if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8220 [container_ presentModalViewController:confirm_ animated:YES];
8226 @synchronized (self) {
8231 - (void) clearPackage:(Package *)package {
8232 @synchronized (self) {
8239 - (void) installPackages:(NSArray *)packages {
8240 @synchronized (self) {
8241 for (Package *package in packages)
8248 - (void) installPackage:(Package *)package {
8249 @synchronized (self) {
8256 - (void) removePackage:(Package *)package {
8257 @synchronized (self) {
8264 - (void) distUpgrade {
8265 @synchronized (self) {
8266 if (![database_ upgrade])
8273 @synchronized (self) {
8278 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8279 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8281 if (navigation != nil) {
8282 [navigation pushViewController:progress animated:YES];
8284 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8285 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8286 [container_ presentModalViewController:navigation animated:YES];
8290 detachNewThreadSelector:@selector(perform)
8293 title:UCLocalize("RUNNING")
8297 - (void) progressControllerIsComplete:(ProgressController *)progress {
8301 - (void) setPage:(CYViewController *)page {
8302 [page setDelegate:self];
8304 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8305 [navController setViewControllers:[NSArray arrayWithObject:page]];
8306 for (CYNavigationController *page in [tabbar_ viewControllers]) {
8307 if (page != navController) [page setViewControllers:nil];
8311 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8312 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8313 [browser loadURL:url];
8317 - (SectionsController *) sectionsController {
8318 if (sections_ == nil)
8319 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8323 - (ChangesController *) changesController {
8324 if (changes_ == nil)
8325 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8329 - (ManageController *) manageController {
8330 if (manage_ == nil) {
8331 manage_ = (ManageController *) [[self
8332 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8333 withClass:[ManageController class]
8335 if (!IsWildcat_) queueDelegate_ = manage_;
8340 - (SearchController *) searchController {
8342 search_ = [[SearchController alloc] initWithDatabase:database_];
8346 - (SourceTable *) sourcesController {
8347 if (sources_ == nil)
8348 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8352 - (InstalledController *) installedController {
8353 if (installed_ == nil) {
8354 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8355 if (IsWildcat_) queueDelegate_ = installed_;
8360 - (void) tabBarController:(id)tabBarController didSelectViewController:(UIViewController *)viewController {
8361 int tag = [[viewController tabBarItem] tag];
8363 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8365 } else if (tag_ == 1) {
8366 [[self sectionsController] resetView];
8370 case kCydiaTag: _setHomePage(self); break;
8372 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8373 case kChangesTag: [self setPage:[self changesController]]; break;
8374 case kManageTag: [self setPage:[self manageController]]; break;
8375 case kInstalledTag: [self setPage:[self installedController]]; break;
8376 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8377 case kSearchTag: [self setPage:[self searchController]]; break;
8385 - (void) showSettings {
8386 RoleController *role = [[RoleController alloc] initWithDatabase:database_ delegate:self];
8387 CYNavigationController *nav = [[CYNavigationController alloc] initWithRootViewController:role];
8388 if (IsWildcat_) [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8389 [container_ presentModalViewController:nav animated:YES];
8392 - (void) setPackageController:(PackageController *)view {
8394 [view setPackage:nil];
8398 - (PackageController *) _packageController {
8399 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8402 - (PackageController *) packageController {
8403 return [self _packageController];
8406 // Returns the navigation controller for the queuing badge.
8407 - (id) queueBadgeController {
8408 int index = [self indexOfTabWithTag:kManageTag];
8409 if (index == -1) index = [self indexOfTabWithTag:kInstalledTag];
8411 return [[tabbar_ viewControllers] objectAtIndex:index];
8414 - (void) cancelAndClear:(bool)clear {
8415 @synchronized (self) {
8418 pkgCacheFile &cache([database_ cache]);
8419 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
8420 // Unmark method taken from Synaptic Package Manager.
8421 // Thanks for being sane, unlike Aptitude.
8422 if (!cache[iterator].Keep()) {
8423 cache->MarkKeep(iterator, false);
8424 cache->SetReInstall(iterator, false);
8430 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
8434 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8437 // Show the changes in the current view.
8438 [(CYNavigationController *) [tabbar_ selectedViewController] reloadData];
8439 [queueDelegate_ queueStatusDidChange];
8443 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8444 NSString *context([alert context]);
8446 if ([context isEqualToString:@"fixhalf"]) {
8447 if (button == [alert firstOtherButtonIndex]) {
8448 @synchronized (self) {
8449 for (Package *broken in broken_) {
8452 NSString *id = [broken id];
8453 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8454 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8455 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8456 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8462 } else if (button == [alert cancelButtonIndex]) {
8463 [broken_ removeAllObjects];
8467 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8468 } else if ([context isEqualToString:@"upgrade"]) {
8469 if (button == [alert firstOtherButtonIndex]) {
8470 @synchronized (self) {
8471 for (Package *essential in essential_)
8472 [essential install];
8477 } else if (button == [alert firstOtherButtonIndex] + 1) {
8479 } else if (button == [alert cancelButtonIndex]) {
8483 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8487 - (void) system:(NSString *)command { _pooled
8488 system([command UTF8String]);
8491 - (void) applicationWillSuspend {
8493 [super applicationWillSuspend];
8496 - (void) applicationSuspend:(__GSEvent *)event {
8497 // Use external process status API internally.
8498 // This is probably a really bad idea.
8499 uint64_t status = 0;
8501 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8502 notify_get_state(notify_token, &status);
8503 notify_cancel(notify_token);
8506 if (hud_ == nil && status == 0)
8507 [super applicationSuspend:event];
8510 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8512 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8515 - (void) _setSuspended:(BOOL)value {
8517 [super _setSuspended:value];
8520 - (UIProgressHUD *) addProgressHUD {
8521 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8522 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8524 [window_ setUserInteractionEnabled:NO];
8527 UIViewController *target = container_;
8528 while ([target modalViewController] != nil) target = [target modalViewController];
8529 [[target view] addSubview:hud];
8534 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8536 [hud removeFromSuperview];
8537 [window_ setUserInteractionEnabled:YES];
8540 - (CYViewController *) pageForPackage:(NSString *)name {
8541 if (Package *package = [database_ packageWithName:name]) {
8542 PackageController *view([self packageController]);
8543 [view setPackage:package];
8546 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8547 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8548 return [self _pageForURL:url withClass:[CYBrowserController class]];
8552 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8556 NSString *href([url absoluteString]);
8557 if ([href hasPrefix:@"apptapp://package/"])
8558 return [self pageForPackage:[href substringFromIndex:18]];
8560 NSString *scheme([[url scheme] lowercaseString]);
8561 if (![scheme isEqualToString:@"cydia"])
8563 NSString *path([url absoluteString]);
8564 if ([path length] < 8)
8566 path = [path substringFromIndex:8];
8567 if (![path hasPrefix:@"/"])
8568 path = [@"/" stringByAppendingString:path];
8570 if ([path isEqualToString:@"/add-source"])
8571 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8572 else if ([path isEqualToString:@"/storage"])
8573 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8574 else if ([path isEqualToString:@"/sources"])
8575 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8576 else if ([path isEqualToString:@"/packages"])
8577 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8578 else if ([path hasPrefix:@"/url/"])
8579 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8580 else if ([path hasPrefix:@"/launch/"])
8581 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8582 else if ([path hasPrefix:@"/package-settings/"])
8583 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8584 else if ([path hasPrefix:@"/package-signature/"])
8585 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8586 else if ([path hasPrefix:@"/package/"])
8587 return [self pageForPackage:[path substringFromIndex:9]];
8588 else if ([path hasPrefix:@"/files/"]) {
8589 NSString *name = [path substringFromIndex:7];
8591 if (Package *package = [database_ packageWithName:name]) {
8592 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8593 [files setPackage:package];
8601 - (void) applicationOpenURL:(NSURL *)url {
8602 [super applicationOpenURL:url];
8604 if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
8605 [self setPage:page];
8607 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8611 - (void) applicationWillResignActive:(UIApplication *)application {
8612 // Stop refreshing if you get a phone call or lock the device.
8613 if ([container_ updating]) [container_ cancelUpdate];
8615 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8616 [super applicationWillResignActive:application];
8619 - (void) addStashController {
8620 stash_ = [[CYStashController alloc] init];
8621 [window_ addSubview:[stash_ view]];
8624 - (void) removeStashController {
8625 [[stash_ view] removeFromSuperview];
8630 [self setIdleTimerDisabled:YES];
8632 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8633 [self setStatusBarShowsProgress:YES];
8634 UpdateExternalStatus(1);
8636 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8638 UpdateExternalStatus(0);
8639 [self setStatusBarShowsProgress:NO];
8641 [self removeStashController];
8643 if (ExecFork() == 0) {
8644 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8645 perror("launchctl stop");
8649 - (void) setupTabBarController {
8650 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8651 [tabbar_ setDelegate:self];
8653 NSMutableArray *items([NSMutableArray arrayWithObjects:
8654 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8655 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8656 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8657 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8661 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8662 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8664 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8667 NSMutableArray *controllers([NSMutableArray array]);
8669 for (UITabBarItem *item in items) {
8670 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8671 [controller setTabBarItem:item];
8672 [controllers addObject:controller];
8675 [tabbar_ setViewControllers:controllers];
8678 - (void) applicationDidFinishLaunching:(id)unused {
8679 [CYBrowserController _initialize];
8681 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8683 Font12_ = [[UIFont systemFontOfSize:12] retain];
8684 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8685 Font14_ = [[UIFont systemFontOfSize:14] retain];
8686 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8687 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8691 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8692 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8694 UIScreen *screen([UIScreen mainScreen]);
8696 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8697 [window_ orderFront:self];
8698 [window_ makeKey:self];
8699 [window_ setHidden:NO];
8702 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8703 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8704 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8705 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8706 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8707 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8708 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8709 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8710 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8713 [self addStashController];
8714 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8718 database_ = [Database sharedInstance];
8720 [self setupTabBarController];
8722 container_ = [[CYContainer alloc] initWithDatabase:database_];
8723 [container_ setUpdateDelegate:self];
8724 [container_ setTabBarController:tabbar_];
8725 [window_ addSubview:[container_ view]];
8727 // Show pinstripes while loading data.
8728 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8730 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8737 [self showSettings];
8741 [window_ setUserInteractionEnabled:NO];
8743 UIView *container = [[UIView alloc] init];
8744 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8746 UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
8747 [spinner startAnimating];
8748 [container addSubview:spinner];
8751 UILabel *label = [[UILabel alloc] init];
8752 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8753 [label setBackgroundColor:[UIColor clearColor]];
8754 [label setTextColor:[UIColor blackColor]];
8755 [label setShadowColor:[UIColor whiteColor]];
8756 [label setShadowOffset:CGSizeMake(0, 1)];
8757 [label setText:UCLocalize("LOADING_DATA")];
8758 [container addSubview:label];
8761 CGSize viewsize = [[tabbar_ view] frame].size;
8762 CGSize spinnersize = [spinner bounds].size;
8763 CGSize textsize = [[label text] sizeWithFont:[label font]];
8764 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8766 CGRect containrect = {
8767 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8768 CGSizeMake(bothwidth, spinnersize.height)
8771 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8779 [container setFrame:containrect];
8780 [spinner setFrame:spinrect];
8781 [label setFrame:textrect];
8782 [[container_ view] addSubview:container];
8783 [container release];
8788 // Show the home page
8789 [tabbar_ setSelectedIndex:0];
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];
9020 if (Metadata_ == NULL)
9021 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9023 Settings_ = [Metadata_ objectForKey:@"Settings"];
9025 Packages_ = [Metadata_ objectForKey:@"Packages"];
9026 Sections_ = [Metadata_ objectForKey:@"Sections"];
9027 Sources_ = [Metadata_ objectForKey:@"Sources"];
9029 Token_ = [Metadata_ objectForKey:@"Token"];
9032 if (Settings_ != nil)
9033 Role_ = [Settings_ objectForKey:@"Role"];
9035 if (Packages_ == nil) {
9036 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
9037 [Metadata_ setObject:Packages_ forKey:@"Packages"];
9040 if (Sections_ == nil) {
9041 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9042 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9045 if (Sources_ == nil) {
9046 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9047 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9051 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9053 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9054 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9055 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9056 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9057 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9058 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9060 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9062 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9063 unlink("/tmp/.cydia.fw");
9065 } else if (access("/User", F_OK) != 0 || version < 2) {
9068 system("/usr/libexec/cydia/firmware.sh");
9072 _assert([[NSFileManager defaultManager]
9073 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9074 withIntermediateDirectories:YES
9079 if (access("/tmp/cydia.chk", F_OK) == 0) {
9080 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9081 _assert(errno == ENOENT);
9082 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9083 _assert(errno == ENOENT);
9086 /* APT Initialization {{{ */
9087 _assert(pkgInitConfig(*_config));
9088 _assert(pkgInitSystem(*_config, _system));
9091 _config->Set("APT::Acquire::Translation", lang);
9093 // XXX: this timeout might be important :(
9094 //_config->Set("Acquire::http::Timeout", 15);
9096 _config->Set("Acquire::http::MaxParallel", 3);
9098 /* Color Choices {{{ */
9099 space_ = CGColorSpaceCreateDeviceRGB();
9101 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9102 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9103 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9104 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9105 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9106 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9107 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9108 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9109 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9111 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9112 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9114 /* UIKit Configuration {{{ */
9115 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9116 if ($GSFontSetUseLegacyFontMetrics != NULL)
9117 $GSFontSetUseLegacyFontMetrics(YES);
9119 // XXX: I have a feeling this was important
9120 //UIKeyboardDisableAutomaticAppearance();
9123 Colon_ = UCLocalize("COLON_DELIMITED");
9124 Error_ = UCLocalize("ERROR");
9125 Warning_ = UCLocalize("WARNING");
9128 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9130 CGColorSpaceRelease(space_);