1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2010 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "UICaboodle/UCPlatform.h"
45 #include "UICaboodle/UCLocalize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
111 #include <mach-o/nlist.h>
121 #include <ext/hash_map>
123 #include "UICaboodle/BrowserView.h"
125 #include "substrate.h"
132 #define _timestamp ({ \
134 gettimeofday(&tv, NULL); \
135 tv.tv_sec * 1000000 + tv.tv_usec; \
138 typedef std::vector<class ProfileTime *> TimeList;
148 ProfileTime(const char *name) :
152 times_.push_back(this);
155 void AddTime(uint64_t time) {
162 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
174 ProfileTimer(ProfileTime &time) :
181 time_.AddTime(_timestamp - start_);
186 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
188 std::cerr << "========" << std::endl;
191 #define _profile(name) { \
192 static ProfileTime name(#name); \
193 ProfileTimer _ ## name(name);
198 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
200 #define CYPoolStart() \
201 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
203 #define CYPoolEnd() \
207 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
209 void NSLogPoint(const char *fix, const CGPoint &point) {
210 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
213 void NSLogRect(const char *fix, const CGRect &rect) {
214 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
217 static _finline NSString *CydiaURL(NSString *path) {
219 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
220 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
221 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
222 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
223 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
224 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
227 static _finline void UpdateExternalStatus(uint64_t newStatus) {
229 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
230 notify_set_state(notify_token, newStatus);
231 notify_cancel(notify_token);
233 notify_post("com.saurik.Cydia.status");
236 /* [NSObject yieldToSelector:(withObject:)] {{{*/
237 @interface NSObject (Cydia)
238 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
239 - (id) yieldToSelector:(SEL)selector;
242 @implementation NSObject (Cydia)
247 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
248 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
249 id object([[context objectAtIndex:1] nonretainedObjectValue]);
250 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
252 /* XXX: deal with exceptions */
253 id value([self performSelector:selector withObject:object]);
255 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
256 [context removeAllObjects];
257 if ([signature methodReturnLength] != 0 && value != nil)
258 [context addObject:value];
263 performSelectorOnMainThread:@selector(doNothing)
269 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
270 /*return [self performSelector:selector withObject:object];*/
272 volatile bool stopped(false);
274 NSMutableArray *context([NSMutableArray arrayWithObjects:
275 [NSValue valueWithPointer:selector],
276 [NSValue valueWithNonretainedObject:object],
277 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
280 NSThread *thread([[[NSThread alloc]
282 selector:@selector(_yieldToContext:)
288 NSRunLoop *loop([NSRunLoop currentRunLoop]);
289 NSDate *future([NSDate distantFuture]);
291 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
293 return [context count] == 0 ? nil : [context objectAtIndex:0];
296 - (id) yieldToSelector:(SEL)selector {
297 return [self yieldToSelector:selector withObject:nil];
303 /* Cydia Action Sheet {{{ */
304 @interface CYActionSheet : UIAlertView {
308 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
311 @implementation CYActionSheet
313 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
314 if ((self = [super init])) {
315 [self setTitle:title];
316 [self setDelegate:self];
317 for (NSString *button in buttons) [self addButtonWithTitle:button];
318 [self setCancelButtonIndex:index];
322 - (void) _updateFrameForDisplay {
323 [super _updateFrameForDisplay];
324 if ([self cancelButtonIndex] == -1) {
325 NSArray *buttons = [self buttons];
326 if ([buttons count]) {
327 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
328 for (UIThreePartButton *button in buttons)
329 [button setBackground:background forState:0];
334 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
335 button_ = buttonIndex + 1;
339 [self dismissWithClickedButtonIndex:-1 animated:YES];
342 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
343 [self setRunsModal:YES];
352 /* NSForcedOrderingSearch doesn't work on the iPhone */
353 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
354 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
355 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
357 /* Information Dictionaries {{{ */
358 @interface NSMutableArray (Cydia)
359 - (void) addInfoDictionary:(NSDictionary *)info;
362 @implementation NSMutableArray (Cydia)
364 - (void) addInfoDictionary:(NSDictionary *)info {
365 [self addObject:info];
370 @interface NSMutableDictionary (Cydia)
371 - (void) addInfoDictionary:(NSDictionary *)info;
374 @implementation NSMutableDictionary (Cydia)
376 - (void) addInfoDictionary:(NSDictionary *)info {
377 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
383 #define lprintf(args...) fprintf(stderr, args)
386 #define TraceLogging (1 && !ForRelease)
387 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
388 #define ProfileTimes (0 && !ForRelease)
389 #define ForSaurik (0 && !ForRelease)
390 #define LogBrowser (0 && !ForRelease)
391 #define TrackResize (0 && !ForRelease)
392 #define ManualRefresh (1 && !ForRelease)
393 #define ShowInternals (0 && !ForRelease)
394 #define IgnoreInstall (0 && !ForRelease)
395 #define AlwaysReload (0 && !ForRelease)
399 #define _trace(args...)
404 #define _profile(name) {
407 #define PrintTimes() do {} while (false)
411 typedef uint32_t (*SKRadixFunction)(id, void *);
413 @interface NSMutableArray (Radix)
414 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
422 @implementation NSMutableArray (Radix)
424 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
425 size_t count([self count]);
426 struct RadixItem_ *swap(new RadixItem_[count * 2]);
428 for (size_t i(0); i != count; ++i) {
429 RadixItem_ &item(swap[i]);
432 id object([self objectAtIndex:i]);
433 item.key = function(object, argument);
436 struct RadixItem_ *lhs(swap), *rhs(swap + count);
438 static const size_t width = 32;
439 static const size_t bits = 11;
440 static const size_t slots = 1 << bits;
441 static const size_t passes = (width + (bits - 1)) / bits;
443 size_t *hist(new size_t[slots]);
445 for (size_t pass(0); pass != passes; ++pass) {
446 memset(hist, 0, sizeof(size_t) * slots);
448 for (size_t i(0); i != count; ++i) {
449 uint32_t key(lhs[i].key);
451 key &= _not(uint32_t) >> width - bits;
456 for (size_t i(0); i != slots; ++i) {
457 size_t local(offset);
462 for (size_t i(0); i != count; ++i) {
463 uint32_t key(lhs[i].key);
465 key &= _not(uint32_t) >> width - bits;
466 rhs[hist[key]++] = lhs[i];
469 RadixItem_ *tmp(lhs);
476 const void **values(new const void *[count]);
477 for (size_t i(0); i != count; ++i)
478 values[i] = [self objectAtIndex:lhs[i].index];
479 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
487 /* Insertion Sort {{{ */
489 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
490 const char *ptr = (const char *)list;
492 CFIndex half = count / 2;
493 const char *probe = ptr + elementSize * half;
494 CFComparisonResult cr = comparator(element, probe, context);
495 if (0 == cr) return (probe - (const char *)list) / elementSize;
496 ptr = (cr < 0) ? ptr : probe + elementSize;
497 count = (cr < 0) ? half : (half + (count & 1) - 1);
499 return (ptr - (const char *)list) / elementSize;
502 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
503 const char *ptr = (const char *)list;
505 CFIndex half = count / 2;
506 const char *probe = ptr + elementSize * half;
507 CFComparisonResult cr = comparator(element, probe, context);
508 if (0 == cr) return (probe - (const char *)list) / elementSize;
509 ptr = (cr < 0) ? ptr : probe + elementSize;
510 count = (cr < 0) ? half : (half + (count & 1) - 1);
512 return (ptr - (const char *)list) / elementSize;
515 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
516 if (range.length == 0)
518 const void **values(new const void *[range.length]);
519 CFArrayGetValues(array, range, values);
521 #if HistogramInsertionSort > 0
522 uint32_t total(0), *offsets(new uint32_t[range.length]);
525 for (CFIndex index(1); index != range.length; ++index) {
526 const void *value(values[index]);
527 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
528 CFIndex correct(index);
529 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
530 #if HistogramInsertionSort > 1
531 NSLog(@"%@ < %@", value, values[correct - 1]);
536 if (correct != index) {
537 size_t offset(index - correct);
538 #if HistogramInsertionSort
542 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
544 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
545 values[correct] = value;
549 CFArrayReplaceValues(array, range, values, range.length);
552 #if HistogramInsertionSort > 0
553 for (CFIndex index(0); index != range.length; ++index)
554 if (offsets[index] != 0)
555 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
556 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
563 /* Apple Bug Fixes {{{ */
564 @implementation UIWebDocumentView (Cydia)
566 - (void) _setScrollerOffset:(CGPoint)offset {
567 UIScroller *scroller([self _scroller]);
569 CGSize size([scroller contentSize]);
570 CGSize bounds([scroller bounds].size);
573 max.x = size.width - bounds.width;
574 max.y = size.height - bounds.height;
582 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
583 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
585 [scroller setOffset:offset];
591 @implementation WebScriptObject (NSFastEnumeration)
593 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
594 size_t length([self count] - state->state);
597 else if (length > count)
599 for (size_t i(0); i != length; ++i)
600 objects[i] = [self objectAtIndex:state->state++];
601 state->itemsPtr = objects;
602 state->mutationsPtr = (unsigned long *) self;
608 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
609 size_t length([self length] - state->state);
612 else if (length > count)
614 for (size_t i(0); i != length; ++i)
615 objects[i] = [self item:state->state++];
616 state->itemsPtr = objects;
617 state->mutationsPtr = (unsigned long *) self;
621 /* Cydia NSString Additions {{{ */
622 @interface NSString (Cydia)
623 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
624 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
625 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
626 - (NSComparisonResult) compareByPath:(NSString *)other;
627 - (NSString *) stringByCachingURLWithCurrentCDN;
628 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
631 @implementation NSString (Cydia)
633 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
634 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
637 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
638 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
639 memcpy(data, bytes, length);
640 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
643 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
644 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
647 - (NSComparisonResult) compareByPath:(NSString *)other {
648 NSString *prefix = [self commonPrefixWithString:other options:0];
649 size_t length = [prefix length];
651 NSRange lrange = NSMakeRange(length, [self length] - length);
652 NSRange rrange = NSMakeRange(length, [other length] - length);
654 lrange = [self rangeOfString:@"/" options:0 range:lrange];
655 rrange = [other rangeOfString:@"/" options:0 range:rrange];
657 NSComparisonResult value;
659 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
660 value = NSOrderedSame;
661 else if (lrange.location == NSNotFound)
662 value = NSOrderedAscending;
663 else if (rrange.location == NSNotFound)
664 value = NSOrderedDescending;
666 value = NSOrderedSame;
668 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
669 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
670 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
671 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
673 NSComparisonResult result = [lpath compare:rpath];
674 return result == NSOrderedSame ? value : result;
677 - (NSString *) stringByCachingURLWithCurrentCDN {
679 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
680 withString:@"://cache.cydia.saurik.com/"
684 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
685 return [(id)CFURLCreateStringByAddingPercentEscapes(
690 kCFStringEncodingUTF8
697 /* C++ NSString Wrapper Cache {{{ */
698 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
699 return size == 0 ? NULL :
700 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
701 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
704 static _finline CFStringRef CYStringCreate(const char *data) {
705 return CYStringCreate(data, strlen(data));
714 _finline void clear_() {
715 if (cache_ != NULL) {
722 _finline bool empty() const {
726 _finline size_t size() const {
730 _finline char *data() const {
734 _finline void clear() {
739 _finline CYString() :
746 _finline ~CYString() {
750 void operator =(const CYString &rhs) {
754 if (rhs.cache_ == nil)
757 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
760 void set(apr_pool_t *pool, const char *data, size_t size) {
766 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
767 memcpy(temp, data, size);
774 _finline void set(apr_pool_t *pool, const char *data) {
775 set(pool, data, data == NULL ? 0 : strlen(data));
778 _finline void set(apr_pool_t *pool, const std::string &rhs) {
779 set(pool, rhs.data(), rhs.size());
782 bool operator ==(const CYString &rhs) const {
783 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
786 _finline operator CFStringRef() {
788 cache_ = CYStringCreate(data_, size_);
792 _finline operator id() {
793 return (NSString *) static_cast<CFStringRef>(*this);
797 /* C++ NSString Algorithm Adapters {{{ */
799 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
802 struct NSStringMapHash :
803 std::unary_function<NSString *, size_t>
805 _finline size_t operator ()(NSString *value) const {
806 return CFStringHashNSString((CFStringRef) value);
810 struct NSStringMapLess :
811 std::binary_function<NSString *, NSString *, bool>
813 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
814 return [lhs compare:rhs] == NSOrderedAscending;
818 struct NSStringMapEqual :
819 std::binary_function<NSString *, NSString *, bool>
821 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
822 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
823 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
824 //[lhs isEqualToString:rhs];
829 /* Perl-Compatible RegEx {{{ */
839 Pcre(const char *regex) :
844 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
847 lprintf("%d:%s\n", offset, error);
851 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
852 matches_ = new int[(capture_ + 1) * 3];
860 NSString *operator [](size_t match) {
861 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
864 bool operator ()(NSString *data) {
865 // XXX: length is for characters, not for bytes
866 return operator ()([data UTF8String], [data length]);
869 bool operator ()(const char *data, size_t size) {
871 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
875 /* Mime Addresses {{{ */
876 @interface Address : NSObject {
882 - (NSString *) address;
884 - (void) setAddress:(NSString *)address;
886 + (Address *) addressWithString:(NSString *)string;
887 - (Address *) initWithString:(NSString *)string;
890 @implementation Address
899 - (NSString *) name {
903 - (NSString *) address {
907 - (void) setAddress:(NSString *)address {
909 [address_ autorelease];
913 address_ = [address retain];
916 + (Address *) addressWithString:(NSString *)string {
917 return [[[Address alloc] initWithString:string] autorelease];
920 + (NSArray *) _attributeKeys {
921 return [NSArray arrayWithObjects:@"address", @"name", nil];
924 - (NSArray *) attributeKeys {
925 return [[self class] _attributeKeys];
928 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
929 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
932 - (Address *) initWithString:(NSString *)string {
933 if ((self = [super init]) != nil) {
934 const char *data = [string UTF8String];
935 size_t size = [string length];
937 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
939 if (address_r(data, size)) {
940 name_ = [address_r[1] retain];
941 address_ = [address_r[2] retain];
943 name_ = [string retain];
951 /* CoreGraphics Primitives {{{ */
962 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
965 Set(space, red, green, blue, alpha);
970 CGColorRelease(color_);
977 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
979 float color[] = {red, green, blue, alpha};
980 color_ = CGColorCreate(space, (CGFloat *) color);
983 operator CGColorRef() {
989 /* Random Global Variables {{{ */
990 static const int PulseInterval_ = 50000;
991 static const int ButtonBarWidth_ = 60;
992 static const int ButtonBarHeight_ = 48;
993 static const float KeyboardTime_ = 0.3f;
996 static NSArray *Finishes_;
998 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
999 #define NotifyConfig_ "/etc/notify.conf"
1001 static bool Queuing_;
1003 static CYColor Blue_;
1004 static CYColor Blueish_;
1005 static CYColor Black_;
1006 static CYColor Off_;
1007 static CYColor White_;
1008 static CYColor Gray_;
1009 static CYColor Green_;
1010 static CYColor Purple_;
1011 static CYColor Purplish_;
1013 static UIColor *InstallingColor_;
1014 static UIColor *RemovingColor_;
1016 static NSString *App_;
1017 static NSString *Home_;
1019 static BOOL Advanced_;
1020 static BOOL Ignored_;
1022 static UIFont *Font12_;
1023 static UIFont *Font12Bold_;
1024 static UIFont *Font14_;
1025 static UIFont *Font18Bold_;
1026 static UIFont *Font22Bold_;
1028 static const char *Machine_ = NULL;
1029 static NSString *System_ = nil;
1030 static NSString *SerialNumber_ = nil;
1031 static NSString *ChipID_ = nil;
1032 static NSString *Token_ = nil;
1033 static NSString *UniqueID_ = nil;
1034 static NSString *PLMN_ = nil;
1035 static NSString *Build_ = nil;
1036 static NSString *Product_ = nil;
1037 static NSString *Safari_ = nil;
1039 static CFLocaleRef Locale_;
1040 static NSArray *Languages_;
1041 static CGColorSpaceRef space_;
1043 static NSDictionary *SectionMap_;
1044 static NSMutableDictionary *Metadata_;
1045 static _transient NSMutableDictionary *Settings_;
1046 static _transient NSString *Role_;
1047 static _transient NSMutableDictionary *Packages_;
1048 static _transient NSMutableDictionary *Sections_;
1049 static _transient NSMutableDictionary *Sources_;
1050 static bool Changed_;
1051 static NSDate *now_;
1053 static bool IsWildcat_;
1056 /* Display Helpers {{{ */
1057 inline float Interpolate(float begin, float end, float fraction) {
1058 return (end - begin) * fraction + begin;
1061 /* XXX: localize this! */
1062 NSString *SizeString(double size) {
1063 bool negative = size < 0;
1068 while (size > 1024) {
1073 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1075 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1078 const char *StripVersion_(const char *version) {
1079 const char *colon(strchr(version, ':'));
1081 version = colon + 1;
1085 CFStringRef StripVersion(const char *version) {
1086 const char *colon(strchr(version, ':'));
1088 version = colon + 1;
1089 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1091 return CYStringCreate(version);
1094 NSString *LocalizeSection(NSString *section) {
1095 static Pcre title_r("^(.*?) \\((.*)\\)$");
1096 if (title_r(section)) {
1097 NSString *parent(title_r[1]);
1098 NSString *child(title_r[2]);
1100 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1101 LocalizeSection(parent),
1102 LocalizeSection(child)
1106 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1109 NSString *Simplify(NSString *title) {
1110 const char *data = [title UTF8String];
1111 size_t size = [title length];
1113 static Pcre square_r("^\\[(.*)\\]$");
1114 if (square_r(data, size))
1115 return Simplify(square_r[1]);
1117 static Pcre paren_r("^\\((.*)\\)$");
1118 if (paren_r(data, size))
1119 return Simplify(paren_r[1]);
1121 static Pcre title_r("^(.*?) \\((.*)\\)$");
1122 if (title_r(data, size))
1123 return Simplify(title_r[1]);
1129 NSString *GetLastUpdate() {
1130 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1133 return UCLocalize("NEVER_OR_UNKNOWN");
1135 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1136 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1138 CFRelease(formatter);
1140 return [(NSString *) formatted autorelease];
1143 bool isSectionVisible(NSString *section) {
1144 NSDictionary *metadata([Sections_ objectForKey:section]);
1145 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1146 return hidden == nil || ![hidden boolValue];
1151 /* Delegate Prototypes {{{ */
1155 @interface NSObject (ProgressDelegate)
1158 @protocol ProgressDelegate
1159 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1160 - (void) setProgressTitle:(NSString *)title;
1161 - (void) setProgressPercent:(float)percent;
1162 - (void) startProgress;
1163 - (void) addProgressOutput:(NSString *)output;
1164 - (bool) isCancelling:(size_t)received;
1167 @protocol ConfigurationDelegate
1168 - (void) repairWithSelector:(SEL)selector;
1169 - (void) setConfigurationData:(NSString *)data;
1172 @class PackageController;
1174 @protocol CydiaDelegate
1175 - (void) setPackageController:(PackageController *)view;
1176 - (void) clearPackage:(Package *)package;
1177 - (void) installPackage:(Package *)package;
1178 - (void) installPackages:(NSArray *)packages;
1179 - (void) removePackage:(Package *)package;
1180 - (void) beginUpdate;
1182 - (void) distUpgrade;
1184 - (void) updateData;
1186 - (void) showSettings;
1187 - (UIProgressHUD *) addProgressHUD;
1188 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1189 - (CYViewController *) pageForPackage:(NSString *)name;
1190 - (PackageController *) packageController;
1191 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1195 /* Status Delegation {{{ */
1197 public pkgAcquireStatus
1200 _transient NSObject<ProgressDelegate> *delegate_;
1208 void setDelegate(id delegate) {
1209 delegate_ = delegate;
1212 NSObject<ProgressDelegate> *getDelegate() const {
1216 virtual bool MediaChange(std::string media, std::string drive) {
1220 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1223 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1224 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1225 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1228 virtual void Done(pkgAcquire::ItemDesc &item) {
1231 virtual void Fail(pkgAcquire::ItemDesc &item) {
1233 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1234 item.Owner->Status == pkgAcquire::Item::StatDone
1238 std::string &error(item.Owner->ErrorText);
1242 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1243 NSArray *fields([description componentsSeparatedByString:@" "]);
1244 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1246 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1247 withObject:[NSArray arrayWithObjects:
1248 [NSString stringWithUTF8String:error.c_str()],
1255 virtual bool Pulse(pkgAcquire *Owner) {
1256 bool value = pkgAcquireStatus::Pulse(Owner);
1259 double(CurrentBytes + CurrentItems) /
1260 double(TotalBytes + TotalItems)
1263 [delegate_ setProgressPercent:percent];
1264 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1267 virtual void Start() {
1268 [delegate_ startProgress];
1271 virtual void Stop() {
1275 /* Progress Delegation {{{ */
1280 _transient id<ProgressDelegate> delegate_;
1284 virtual void Update() {
1285 /*if (abs(Percent - percent_) > 2)
1286 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1290 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1291 [delegate_ setProgressPercent:(Percent / 100)];*/
1301 void setDelegate(id delegate) {
1302 delegate_ = delegate;
1305 id getDelegate() const {
1309 virtual void Done() {
1311 //[delegate_ setProgressPercent:1];
1316 /* Database Interface {{{ */
1317 typedef std::map< unsigned long, _H<Source> > SourceMap;
1319 @interface Database : NSObject {
1325 pkgCacheFile cache_;
1326 pkgDepCache::Policy *policy_;
1327 pkgRecords *records_;
1328 pkgProblemResolver *resolver_;
1329 pkgAcquire *fetcher_;
1331 SPtr<pkgPackageManager> manager_;
1332 pkgSourceList *list_;
1335 CFMutableArrayRef packages_;
1337 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1346 + (Database *) sharedInstance;
1349 - (void) _readCydia:(NSNumber *)fd;
1350 - (void) _readStatus:(NSNumber *)fd;
1351 - (void) _readOutput:(NSNumber *)fd;
1355 - (Package *) packageWithName:(NSString *)name;
1357 - (pkgCacheFile &) cache;
1358 - (pkgDepCache::Policy *) policy;
1359 - (pkgRecords *) records;
1360 - (pkgProblemResolver *) resolver;
1361 - (pkgAcquire &) fetcher;
1362 - (pkgSourceList &) list;
1363 - (NSArray *) packages;
1364 - (NSArray *) sources;
1365 - (void) reloadData;
1373 - (void) setVisible;
1375 - (void) updateWithStatus:(Status &)status;
1377 - (void) setDelegate:(id)delegate;
1378 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1381 /* Delegate Helpers {{{ */
1382 @implementation NSObject (ProgressDelegate)
1384 - (void) _setProgressErrorPackage:(NSArray *)args {
1385 [self performSelector:@selector(setProgressError:forPackage:)
1386 withObject:[args objectAtIndex:0]
1387 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1391 - (void) _setProgressErrorTitle:(NSArray *)args {
1392 [self performSelector:@selector(setProgressError:withTitle:)
1393 withObject:[args objectAtIndex:0]
1394 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1398 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1399 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1400 withObject:[NSArray arrayWithObjects:error, title, nil]
1405 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1406 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1408 [self performSelector:@selector(setProgressError:withTitle:)
1410 withObject:(package == nil ? id : [package name])
1417 /* Source Class {{{ */
1418 @interface Source : NSObject {
1419 CYString depiction_;
1420 CYString description_;
1426 CYString distribution_;
1431 NSString *authority_;
1433 CYString defaultIcon_;
1435 NSDictionary *record_;
1439 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1441 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1443 - (NSString *) depictionForPackage:(NSString *)package;
1444 - (NSString *) supportForPackage:(NSString *)package;
1446 - (NSDictionary *) record;
1450 - (NSString *) distribution;
1451 - (NSString *) type;
1453 - (NSString *) host;
1455 - (NSString *) name;
1456 - (NSString *) description;
1457 - (NSString *) label;
1458 - (NSString *) origin;
1459 - (NSString *) version;
1461 - (NSString *) defaultIcon;
1465 @implementation Source
1469 distribution_.clear();
1472 description_.clear();
1478 defaultIcon_.clear();
1480 if (record_ != nil) {
1490 if (authority_ != nil) {
1491 [authority_ release];
1501 + (NSArray *) _attributeKeys {
1502 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1505 - (NSArray *) attributeKeys {
1506 return [[self class] _attributeKeys];
1509 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1510 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1513 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1516 trusted_ = index->IsTrusted();
1518 uri_.set(pool, index->GetURI());
1519 distribution_.set(pool, index->GetDist());
1520 type_.set(pool, index->GetType());
1522 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1523 if (dindex != NULL) {
1525 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1528 pkgTagFile tags(&fd);
1530 pkgTagSection section;
1537 {"default-icon", &defaultIcon_},
1538 {"depiction", &depiction_},
1539 {"description", &description_},
1541 {"origin", &origin_},
1542 {"support", &support_},
1543 {"version", &version_},
1546 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1547 const char *start, *end;
1549 if (section.Find(names[i].name_, start, end)) {
1550 CYString &value(*names[i].value_);
1551 value.set(pool, start, end - start);
1557 record_ = [Sources_ objectForKey:[self key]];
1559 record_ = [record_ retain];
1561 NSURL *url([NSURL URLWithString:uri_]);
1565 host_ = [[host_ lowercaseString] retain];
1570 authority_ = [url path];
1572 if (authority_ != nil)
1573 authority_ = [authority_ retain];
1576 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1577 if ((self = [super init]) != nil) {
1578 [self setMetaIndex:index inPool:pool];
1582 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1583 NSDictionary *lhr = [self record];
1584 NSDictionary *rhr = [source record];
1587 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1589 NSString *lhs = [self name];
1590 NSString *rhs = [source name];
1592 if ([lhs length] != 0 && [rhs length] != 0) {
1593 unichar lhc = [lhs characterAtIndex:0];
1594 unichar rhc = [rhs characterAtIndex:0];
1596 if (isalpha(lhc) && !isalpha(rhc))
1597 return NSOrderedAscending;
1598 else if (!isalpha(lhc) && isalpha(rhc))
1599 return NSOrderedDescending;
1602 return [lhs compare:rhs options:LaxCompareOptions_];
1605 - (NSString *) depictionForPackage:(NSString *)package {
1606 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1609 - (NSString *) supportForPackage:(NSString *)package {
1610 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1613 - (NSDictionary *) record {
1621 - (NSString *) uri {
1625 - (NSString *) distribution {
1626 return distribution_;
1629 - (NSString *) type {
1633 - (NSString *) key {
1634 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1637 - (NSString *) host {
1641 - (NSString *) name {
1642 return origin_.empty() ? authority_ : origin_;
1645 - (NSString *) description {
1646 return description_;
1649 - (NSString *) label {
1650 return label_.empty() ? authority_ : label_;
1653 - (NSString *) origin {
1657 - (NSString *) version {
1661 - (NSString *) defaultIcon {
1662 return defaultIcon_;
1667 /* Relationship Class {{{ */
1668 @interface Relationship : NSObject {
1673 - (NSString *) type;
1675 - (NSString *) name;
1679 @implementation Relationship
1687 - (NSString *) type {
1695 - (NSString *) name {
1702 /* Package Class {{{ */
1703 @interface Package : NSObject {
1707 pkgCache::VerIterator version_;
1708 pkgCache::PkgIterator iterator_;
1709 _transient Database *database_;
1710 pkgCache::VerFileIterator file_;
1717 NSString *section$_;
1724 CYString installed_;
1730 CYString depiction_;
1741 NSMutableArray *tags_;
1744 NSArray *relationships_;
1746 NSMutableDictionary *metadata_;
1747 _transient NSDate *firstSeen_;
1748 _transient NSDate *lastSeen_;
1752 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1753 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1755 - (pkgCache::PkgIterator) iterator;
1758 - (NSString *) section;
1759 - (NSString *) simpleSection;
1761 - (NSString *) longSection;
1762 - (NSString *) shortSection;
1766 - (Address *) maintainer;
1768 - (NSString *) longDescription;
1769 - (NSString *) shortDescription;
1772 - (NSMutableDictionary *) metadata;
1774 - (BOOL) subscribed;
1777 - (NSString *) latest;
1778 - (NSString *) installed;
1779 - (BOOL) uninstalled;
1782 - (BOOL) upgradableAndEssential:(BOOL)essential;
1785 - (BOOL) unfiltered;
1789 - (BOOL) halfConfigured;
1790 - (BOOL) halfInstalled;
1792 - (NSString *) mode;
1794 - (void) setVisible;
1797 - (NSString *) name;
1799 - (NSString *) homepage;
1800 - (NSString *) depiction;
1801 - (Address *) author;
1803 - (NSString *) support;
1805 - (NSArray *) files;
1806 - (NSArray *) relationships;
1807 - (NSArray *) warnings;
1808 - (NSArray *) applications;
1810 - (Source *) source;
1811 - (NSString *) role;
1813 - (BOOL) matches:(NSString *)text;
1815 - (bool) hasSupportingRole;
1816 - (BOOL) hasTag:(NSString *)tag;
1817 - (NSString *) primaryPurpose;
1818 - (NSArray *) purposes;
1819 - (bool) isCommercial;
1821 - (CYString &) cyname;
1823 - (uint32_t) compareBySection:(NSArray *)sections;
1825 - (uint32_t) compareForChanges;
1830 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1831 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1832 - (bool) isInstalledAndVisible:(NSNumber *)number;
1833 - (bool) isVisibleInSection:(NSString *)section;
1834 - (bool) isVisibleInSource:(Source *)source;
1838 uint32_t PackageChangesRadix(Package *self, void *) {
1843 uint32_t timestamp : 30;
1844 uint32_t ignored : 1;
1845 uint32_t upgradable : 1;
1849 bool upgradable([self upgradableAndEssential:YES]);
1850 value.bits.upgradable = upgradable ? 1 : 0;
1853 value.bits.timestamp = 0;
1854 value.bits.ignored = [self ignored] ? 0 : 1;
1855 value.bits.upgradable = 1;
1857 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1858 value.bits.ignored = 0;
1859 value.bits.upgradable = 0;
1862 return _not(uint32_t) - value.key;
1865 _finline static void Stifle(uint8_t &value) {
1868 uint32_t PackagePrefixRadix(Package *self, void *context) {
1869 size_t offset(reinterpret_cast<size_t>(context));
1870 CYString &name([self cyname]);
1872 size_t size(name.size());
1875 char *text(name.data());
1878 if (!isdigit(text[0]))
1882 while (size != digits && isdigit(text[digits]))
1892 if (offset == 0 && zeros != 0) {
1893 memset(data, '0', zeros);
1894 memcpy(data + zeros, text, 4 - zeros);
1896 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1897 if (size <= offset - zeros)
1900 text += offset - zeros;
1901 size -= offset - zeros;
1904 memcpy(data, text, 4);
1906 memcpy(data, text, size);
1907 memset(data + size, 0, 4 - size);
1910 for (size_t i(0); i != 4; ++i)
1911 if (isalpha(data[i]))
1919 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1921 /* XXX: ntohl may be more honest */
1922 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1925 CYString &(*PackageName)(Package *self, SEL sel);
1927 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1928 _profile(PackageNameCompare)
1929 CYString &lhi(PackageName(lhs, @selector(cyname)));
1930 CYString &rhi(PackageName(rhs, @selector(cyname)));
1931 CFStringRef lhn(lhi), rhn(rhi);
1934 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1935 else if (rhn == NULL)
1936 return NSOrderedDescending;
1938 _profile(PackageNameCompare$NumbersLast)
1939 if (!lhi.empty() && !rhi.empty()) {
1940 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1941 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1942 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1943 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1944 return lha ? NSOrderedAscending : NSOrderedDescending;
1948 CFIndex length = CFStringGetLength(lhn);
1950 _profile(PackageNameCompare$Compare)
1951 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1956 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1957 return PackageNameCompare(*lhs, *rhs, context);
1960 struct PackageNameOrdering :
1961 std::binary_function<Package *, Package *, bool>
1963 _finline bool operator ()(Package *lhs, Package *rhs) const {
1964 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1968 @implementation Package
1970 - (NSString *) description {
1971 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1977 if (section$_ != nil)
1978 [section$_ release];
1983 if (sponsor$_ != nil)
1984 [sponsor$_ release];
1985 if (author$_ != nil)
1992 if (relationships_ != nil)
1993 [relationships_ release];
1994 if (metadata_ != nil)
1995 [metadata_ release];
2000 + (NSString *) webScriptNameForSelector:(SEL)selector {
2001 if (selector == @selector(hasTag:))
2007 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2008 return [self webScriptNameForSelector:selector] == nil;
2011 + (NSArray *) _attributeKeys {
2012 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];
2015 - (NSArray *) attributeKeys {
2016 return [[self class] _attributeKeys];
2019 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2020 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2030 _profile(Package$parse)
2031 pkgRecords::Parser *parser;
2033 _profile(Package$parse$Lookup)
2034 parser = &[database_ records]->Lookup(file_);
2039 _profile(Package$parse$Find)
2045 {"depiction", &depiction_},
2046 {"homepage", &homepage_},
2047 {"website", &website},
2049 {"support", &support_},
2050 {"sponsor", &sponsor_},
2051 {"author", &author_},
2054 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2055 const char *start, *end;
2057 if (parser->Find(names[i].name_, start, end)) {
2058 CYString &value(*names[i].value_);
2059 _profile(Package$parse$Value)
2060 value.set(pool_, start, end - start);
2066 _profile(Package$parse$Tagline)
2067 const char *start, *end;
2068 if (parser->ShortDesc(start, end)) {
2069 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2072 while (stop != start && stop[-1] == '\r')
2074 tagline_.set(pool_, start, stop - start);
2078 _profile(Package$parse$Retain)
2079 if (homepage_.empty())
2080 homepage_ = website;
2081 if (homepage_ == depiction_)
2087 - (void) setVisible {
2088 visible_ = required_ && [self unfiltered];
2091 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2092 if ((self = [super init]) != nil) {
2093 _profile(Package$initWithVersion)
2094 era_ = [database era];
2098 iterator_ = version.ParentPkg();
2099 database_ = database;
2101 _profile(Package$initWithVersion$Latest)
2102 latest_ = (NSString *) StripVersion(version_.VerStr());
2105 pkgCache::VerIterator current;
2106 _profile(Package$initWithVersion$Versions)
2107 current = iterator_.CurrentVer();
2109 installed_.set(pool_, StripVersion_(current.VerStr()));
2111 if (!version_.end())
2112 file_ = version_.FileList();
2114 pkgCache &cache([database_ cache]);
2115 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2119 _profile(Package$initWithVersion$Name)
2120 id_.set(pool_, iterator_.Name());
2121 name_.set(pool, iterator_.Display());
2124 _profile(Package$lowercaseString)
2125 char *data(id_.data());
2126 for (size_t i(0), e(id_.size()); i != e; ++i)
2127 // XXX: do not use tolower() as this is not locale-specific? :(
2132 _profile(Package$initWithVersion$Source)
2133 source_ = [database_ getSource:file_.File()];
2142 _profile(Package$initWithVersion$Tags)
2143 pkgCache::TagIterator tag(iterator_.TagList());
2145 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2147 const char *name(tag.Name());
2148 [tags_ addObject:(NSString *)CYStringCreate(name)];
2149 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2150 role_ = (NSString *) CYStringCreate(name + 6);
2151 if (required_ && strncmp(name, "require::", 9) == 0 && (
2156 } while (!tag.end());
2160 bool changed(false);
2162 _profile(Package$initWithVersion$Metadata)
2163 metadata_ = [Packages_ objectForKey:id_];
2165 if (metadata_ == nil) {
2168 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2169 firstSeen_, @"FirstSeen",
2170 latest_, @"LastVersion",
2175 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2176 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2178 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2179 subscribed_ = [subscribed boolValue];
2181 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2183 if (firstSeen_ == nil) {
2184 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2185 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2189 if (version == nil) {
2190 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2192 } else if (![version isEqualToString:latest_]) {
2193 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2195 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2200 metadata_ = [metadata_ retain];
2203 [Packages_ setObject:metadata_ forKey:id_];
2208 _profile(Package$initWithVersion$Section)
2209 section_.set(pool_, iterator_.Section());
2212 obsolete_ = [self hasTag:@"cydia::obsolete"];
2213 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2218 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2219 pkgCache::VerIterator version;
2221 _profile(Package$packageWithIterator$GetCandidateVer)
2222 version = [database policy]->GetCandidateVer(iterator);
2228 return [[[Package alloc]
2229 initWithVersion:version
2236 - (pkgCache::PkgIterator) iterator {
2240 - (NSString *) section {
2241 if (section$_ == nil) {
2242 if (section_.empty())
2245 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2246 NSString *name(section_);
2249 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2250 if (NSString *rename = [value objectForKey:@"Rename"]) {
2255 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2259 - (NSString *) simpleSection {
2260 if (NSString *section = [self section])
2261 return Simplify(section);
2266 - (NSString *) longSection {
2267 return LocalizeSection([self section]);
2270 - (NSString *) shortSection {
2271 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2274 - (NSString *) uri {
2277 pkgIndexFile *index;
2278 pkgCache::PkgFileIterator file(file_.File());
2279 if (![database_ list].FindIndex(file, index))
2281 return [NSString stringWithUTF8String:iterator_->Path];
2282 //return [NSString stringWithUTF8String:file.Site()];
2283 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2287 - (Address *) maintainer {
2290 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2291 const std::string &maintainer(parser->Maintainer());
2292 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2296 return version_.end() ? 0 : version_->InstalledSize;
2299 - (NSString *) longDescription {
2300 @synchronized (database_) {
2301 if ([database_ era] != era_ || file_.end())
2304 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2305 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2307 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2308 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2309 if ([lines count] < 2)
2312 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2313 for (size_t i(1), e([lines count]); i != e; ++i) {
2314 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2315 [trimmed addObject:trim];
2318 return [trimmed componentsJoinedByString:@"\n"];
2321 - (NSString *) shortDescription {
2326 _profile(Package$index)
2327 CFStringRef name((CFStringRef) [self name]);
2328 if (CFStringGetLength(name) == 0)
2330 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2331 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2333 return toupper(character);
2337 - (NSMutableDictionary *) metadata {
2342 if (subscribed_ && lastSeen_ != nil)
2347 - (BOOL) subscribed {
2352 NSDictionary *metadata([self metadata]);
2353 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2354 return [ignored boolValue];
2359 - (NSString *) latest {
2363 - (NSString *) installed {
2367 - (BOOL) uninstalled {
2368 return installed_.empty();
2372 return !version_.end();
2375 - (BOOL) upgradableAndEssential:(BOOL)essential {
2376 _profile(Package$upgradableAndEssential)
2377 pkgCache::VerIterator current(iterator_.CurrentVer());
2379 return essential && essential_ && visible_;
2381 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2385 - (BOOL) essential {
2390 return [database_ cache][iterator_].InstBroken();
2393 - (BOOL) unfiltered {
2394 NSString *section([self section]);
2395 return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
2403 unsigned char current(iterator_->CurrentState);
2404 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2407 - (BOOL) halfConfigured {
2408 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2411 - (BOOL) halfInstalled {
2412 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2416 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2417 return state.Mode != pkgDepCache::ModeKeep;
2420 - (NSString *) mode {
2421 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2423 switch (state.Mode) {
2424 case pkgDepCache::ModeDelete:
2425 if ((state.iFlags & pkgDepCache::Purge) != 0)
2429 case pkgDepCache::ModeKeep:
2430 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2431 return @"REINSTALL";
2432 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2436 case pkgDepCache::ModeInstall:
2437 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2438 return @"REINSTALL";
2439 else*/ switch (state.Status) {
2441 return @"DOWNGRADE";
2447 return @"NEW_INSTALL";
2458 - (NSString *) name {
2459 return name_.empty() ? id_ : name_;
2462 - (UIImage *) icon {
2463 NSString *section = [self simpleSection];
2467 if ([static_cast<id>(icon_) hasPrefix:@"file:///"])
2468 // XXX: correct escaping
2469 icon = [UIImage imageAtPath:[static_cast<id>(icon_) substringFromIndex:7]];
2470 if (icon == nil) if (section != nil)
2471 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2472 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2473 if ([dicon hasPrefix:@"file:///"])
2474 // XXX: correct escaping
2475 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2477 icon = [UIImage applicationImageNamed:@"unknown.png"];
2481 - (NSString *) homepage {
2485 - (NSString *) depiction {
2486 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2489 - (Address *) sponsor {
2490 if (sponsor$_ == nil) {
2491 if (sponsor_.empty())
2493 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2497 - (Address *) author {
2498 if (author$_ == nil) {
2499 if (author_.empty())
2501 author$_ = [[Address addressWithString:author_] retain];
2505 - (NSString *) support {
2506 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2509 - (NSArray *) files {
2510 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2511 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2514 fin.open([path UTF8String]);
2519 while (std::getline(fin, line))
2520 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2525 - (NSArray *) relationships {
2526 return relationships_;
2529 - (NSArray *) warnings {
2530 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2531 const char *name(iterator_.Name());
2533 size_t length(strlen(name));
2534 if (length < 2) invalid:
2535 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2536 else for (size_t i(0); i != length; ++i)
2538 /* XXX: technically this is not allowed */
2539 (name[i] < 'A' || name[i] > 'Z') &&
2540 (name[i] < 'a' || name[i] > 'z') &&
2541 (name[i] < '0' || name[i] > '9') &&
2542 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2545 if (strcmp(name, "cydia") != 0) {
2548 bool _private = false;
2551 bool repository = [[self section] isEqualToString:@"Repositories"];
2553 if (NSArray *files = [self files])
2554 for (NSString *file in files)
2555 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2557 else if (!user && [file isEqualToString:@"/User"])
2559 else if (!_private && [file isEqualToString:@"/private"])
2561 else if (!stash && [file isEqualToString:@"/var/stash"])
2564 /* XXX: this is not sensitive enough. only some folders are valid. */
2565 if (cydia && !repository)
2566 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2568 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2570 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2572 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2575 return [warnings count] == 0 ? nil : warnings;
2578 - (NSArray *) applications {
2579 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2581 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2583 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2584 if (NSArray *files = [self files])
2585 for (NSString *file in files)
2586 if (application_r(file)) {
2587 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2588 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2589 if ([id isEqualToString:me])
2592 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2594 display = application_r[1];
2596 NSString *bundle([file stringByDeletingLastPathComponent]);
2597 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2598 if (icon == nil || [icon length] == 0)
2600 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2602 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2603 [applications addObject:application];
2605 [application addObject:id];
2606 [application addObject:display];
2607 [application addObject:url];
2610 return [applications count] == 0 ? nil : applications;
2613 - (Source *) source {
2615 @synchronized (database_) {
2616 if ([database_ era] != era_ || file_.end())
2619 source_ = [database_ getSource:file_.File()];
2631 - (NSString *) role {
2635 - (BOOL) matches:(NSString *)text {
2641 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2642 if (range.location != NSNotFound)
2645 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2646 if (range.location != NSNotFound)
2649 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2650 if (range.location != NSNotFound)
2656 - (bool) hasSupportingRole {
2659 if ([role_ isEqualToString:@"enduser"])
2661 if ([Role_ isEqualToString:@"User"])
2663 if ([role_ isEqualToString:@"hacker"])
2665 if ([Role_ isEqualToString:@"Hacker"])
2667 if ([role_ isEqualToString:@"developer"])
2669 if ([Role_ isEqualToString:@"Developer"])
2674 - (BOOL) hasTag:(NSString *)tag {
2675 return tags_ == nil ? NO : [tags_ containsObject:tag];
2678 - (NSString *) primaryPurpose {
2679 for (NSString *tag in tags_)
2680 if ([tag hasPrefix:@"purpose::"])
2681 return [tag substringFromIndex:9];
2685 - (NSArray *) purposes {
2686 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2687 for (NSString *tag in tags_)
2688 if ([tag hasPrefix:@"purpose::"])
2689 [purposes addObject:[tag substringFromIndex:9]];
2690 return [purposes count] == 0 ? nil : purposes;
2693 - (bool) isCommercial {
2694 return [self hasTag:@"cydia::commercial"];
2697 - (CYString &) cyname {
2698 return name_.empty() ? id_ : name_;
2701 - (uint32_t) compareBySection:(NSArray *)sections {
2702 NSString *section([self section]);
2703 for (size_t i(0), e([sections count]); i != e; ++i) {
2704 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2708 return _not(uint32_t);
2711 - (uint32_t) compareForChanges {
2716 uint32_t timestamp : 30;
2717 uint32_t ignored : 1;
2718 uint32_t upgradable : 1;
2722 bool upgradable([self upgradableAndEssential:YES]);
2723 value.bits.upgradable = upgradable ? 1 : 0;
2726 value.bits.timestamp = 0;
2727 value.bits.ignored = [self ignored] ? 0 : 1;
2728 value.bits.upgradable = 1;
2730 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2731 value.bits.ignored = 0;
2732 value.bits.upgradable = 0;
2735 return _not(uint32_t) - value.key;
2739 pkgProblemResolver *resolver = [database_ resolver];
2740 resolver->Clear(iterator_);
2741 resolver->Protect(iterator_);
2745 pkgProblemResolver *resolver = [database_ resolver];
2746 resolver->Clear(iterator_);
2747 resolver->Protect(iterator_);
2748 pkgCacheFile &cache([database_ cache]);
2749 cache->MarkInstall(iterator_, false);
2750 pkgDepCache::StateCache &state((*cache)[iterator_]);
2751 if (!state.Install())
2752 cache->SetReInstall(iterator_, true);
2756 pkgProblemResolver *resolver = [database_ resolver];
2757 resolver->Clear(iterator_);
2758 resolver->Protect(iterator_);
2759 resolver->Remove(iterator_);
2760 [database_ cache]->MarkDelete(iterator_, true);
2763 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2764 _profile(Package$isUnfilteredAndSearchedForBy)
2767 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2768 value &= [self unfiltered];
2771 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2772 value &= [self matches:search];
2779 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2780 if ([search length] == 0)
2783 _profile(Package$isUnfilteredAndSelectedForBy)
2786 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2787 value &= [self unfiltered];
2790 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2791 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2798 - (bool) isInstalledAndVisible:(NSNumber *)number {
2799 return (![number boolValue] || [self visible]) && ![self uninstalled];
2802 - (bool) isVisibleInSection:(NSString *)name {
2803 NSString *section = [self section];
2808 section == nil && [name length] == 0 ||
2809 [name isEqualToString:section]
2813 - (bool) isVisibleInSource:(Source *)source {
2814 return [self source] == source && [self visible];
2819 /* Section Class {{{ */
2820 @interface Section : NSObject {
2825 NSString *localized_;
2828 - (NSComparisonResult) compareByLocalized:(Section *)section;
2829 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2830 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2831 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2832 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2833 - (NSString *) name;
2840 - (void) addToCount;
2842 - (void) setCount:(size_t)count;
2843 - (NSString *) localized;
2847 @implementation Section
2851 if (localized_ != nil)
2852 [localized_ release];
2856 - (NSComparisonResult) compareByLocalized:(Section *)section {
2857 NSString *lhs(localized_);
2858 NSString *rhs([section localized]);
2860 /*if ([lhs length] != 0 && [rhs length] != 0) {
2861 unichar lhc = [lhs characterAtIndex:0];
2862 unichar rhc = [rhs characterAtIndex:0];
2864 if (isalpha(lhc) && !isalpha(rhc))
2865 return NSOrderedAscending;
2866 else if (!isalpha(lhc) && isalpha(rhc))
2867 return NSOrderedDescending;
2870 return [lhs compare:rhs options:LaxCompareOptions_];
2873 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2874 if ((self = [self initWithName:name localize:NO]) != nil) {
2875 if (localized != nil)
2876 localized_ = [localized retain];
2880 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2881 return [self initWithName:name row:0 localize:localize];
2884 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2885 if ((self = [super init]) != nil) {
2886 name_ = [name retain];
2890 localized_ = [LocalizeSection(name_) retain];
2894 /* XXX: localize the index thingees */
2895 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2896 if ((self = [super init]) != nil) {
2897 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2903 - (NSString *) name {
2923 - (void) addToCount {
2927 - (void) setCount:(size_t)count {
2931 - (NSString *) localized {
2938 static NSString *Colon_;
2939 static NSString *Error_;
2940 static NSString *Warning_;
2942 /* Database Implementation {{{ */
2943 @implementation Database
2945 + (Database *) sharedInstance {
2946 static Database *instance;
2947 if (instance == nil)
2948 instance = [[Database alloc] init];
2958 NSRecycleZone(zone_);
2959 // XXX: malloc_destroy_zone(zone_);
2960 apr_pool_destroy(pool_);
2964 - (void) _readCydia:(NSNumber *)fd { _pooled
2965 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2966 std::istream is(&ib);
2969 static Pcre finish_r("^finish:([^:]*)$");
2971 while (std::getline(is, line)) {
2972 const char *data(line.c_str());
2973 size_t size = line.size();
2974 lprintf("C:%s\n", data);
2976 if (finish_r(data, size)) {
2977 NSString *finish = finish_r[1];
2978 int index = [Finishes_ indexOfObject:finish];
2979 if (index != INT_MAX && index > Finish_)
2987 - (void) _readStatus:(NSNumber *)fd { _pooled
2988 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2989 std::istream is(&ib);
2992 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2993 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2995 while (std::getline(is, line)) {
2996 const char *data(line.c_str());
2997 size_t size(line.size());
2998 lprintf("S:%s\n", data);
3000 if (conffile_r(data, size)) {
3001 [delegate_ setConfigurationData:conffile_r[1]];
3002 } else if (strncmp(data, "status: ", 8) == 0) {
3003 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3004 [delegate_ setProgressTitle:string];
3005 } else if (pmstatus_r(data, size)) {
3006 std::string type([pmstatus_r[1] UTF8String]);
3007 NSString *id = pmstatus_r[2];
3009 float percent([pmstatus_r[3] floatValue]);
3010 [delegate_ setProgressPercent:(percent / 100)];
3012 NSString *string = pmstatus_r[4];
3014 if (type == "pmerror")
3015 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3016 withObject:[NSArray arrayWithObjects:string, id, nil]
3019 else if (type == "pmstatus") {
3020 [delegate_ setProgressTitle:string];
3021 } else if (type == "pmconffile")
3022 [delegate_ setConfigurationData:string];
3024 lprintf("E:unknown pmstatus\n");
3026 lprintf("E:unknown status\n");
3032 - (void) _readOutput:(NSNumber *)fd { _pooled
3033 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3034 std::istream is(&ib);
3037 while (std::getline(is, line)) {
3038 lprintf("O:%s\n", line.c_str());
3039 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3049 - (Package *) packageWithName:(NSString *)name {
3050 @synchronized (self) {
3051 if (static_cast<pkgDepCache *>(cache_) == NULL)
3053 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3054 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3058 if ((self = [super init]) != nil) {
3065 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3066 apr_pool_create(&pool_, NULL);
3068 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
3072 _assert(pipe(fds) != -1);
3075 _config->Set("APT::Keep-Fds::", cydiafd_);
3076 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3079 detachNewThreadSelector:@selector(_readCydia:)
3081 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3084 _assert(pipe(fds) != -1);
3088 detachNewThreadSelector:@selector(_readStatus:)
3090 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3093 _assert(pipe(fds) != -1);
3094 _assert(dup2(fds[0], 0) != -1);
3095 _assert(close(fds[0]) != -1);
3097 input_ = fdopen(fds[1], "a");
3099 _assert(pipe(fds) != -1);
3100 _assert(dup2(fds[1], 1) != -1);
3101 _assert(close(fds[1]) != -1);
3104 detachNewThreadSelector:@selector(_readOutput:)
3106 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3111 - (pkgCacheFile &) cache {
3115 - (pkgDepCache::Policy *) policy {
3119 - (pkgRecords *) records {
3123 - (pkgProblemResolver *) resolver {
3127 - (pkgAcquire &) fetcher {
3131 - (pkgSourceList &) list {
3135 - (NSArray *) packages {
3136 return (NSArray *) packages_;
3139 - (NSArray *) sources {
3140 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3141 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3142 [sources addObject:i->second];
3146 - (NSArray *) issues {
3147 if (cache_->BrokenCount() == 0)
3150 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3152 for (Package *package in [self packages]) {
3153 if (![package broken])
3155 pkgCache::PkgIterator pkg([package iterator]);
3157 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3158 [entry addObject:[package name]];
3159 [issues addObject:entry];
3161 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3165 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3166 pkgCache::DepIterator start;
3167 pkgCache::DepIterator end;
3168 dep.GlobOr(start, end); // ++dep
3170 if (!cache_->IsImportantDep(end))
3172 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3175 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3176 [entry addObject:failure];
3177 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3179 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3180 if (Package *package = [self packageWithName:name])
3181 name = [package name];
3182 [failure addObject:name];
3184 pkgCache::PkgIterator target(start.TargetPkg());
3185 if (target->ProvidesList != 0)
3186 [failure addObject:@"?"];
3188 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3190 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3191 else if (!cache_[target].CandidateVerIter(cache_).end())
3192 [failure addObject:@"-"];
3193 else if (target->ProvidesList == 0)
3194 [failure addObject:@"!"];
3196 [failure addObject:@"%"];
3200 if (start.TargetVer() != 0)
3201 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3212 - (bool) popErrorWithTitle:(NSString *)title {
3214 std::string message;
3216 while (!_error->empty()) {
3218 bool warning(!_error->PopMessage(error));
3222 size_t size(error.size());
3223 if (size == 0 || error[size - 1] != '\n')
3225 error.resize(size - 1);
3227 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3229 if (!message.empty())
3234 if (fatal && !message.empty())
3235 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3240 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3241 return [self popErrorWithTitle:title] || !success;
3244 - (void) reloadData { CYPoolStart() {
3245 @synchronized (self) {
3248 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3249 CFArrayRemoveAllValues(packages_);
3276 apr_pool_clear(pool_);
3277 NSRecycleZone(zone_);
3279 int chk(creat("/tmp/cydia.chk", 0644));
3283 NSString *title(UCLocalize("DATABASE"));
3286 if (!cache_.Open(progress_, true)) { pop:
3288 bool warning(!_error->PopMessage(error));
3289 lprintf("cache_.Open():[%s]\n", error.c_str());
3291 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3292 [delegate_ repairWithSelector:@selector(configure)];
3293 else if (error == "The package lists or status file could not be parsed or opened.")
3294 [delegate_ repairWithSelector:@selector(update)];
3295 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3296 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3297 // else if (error == "The list of sources could not be read.")
3299 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3308 unlink("/tmp/cydia.chk");
3310 now_ = [[NSDate date] retain];
3312 policy_ = new pkgDepCache::Policy();
3313 records_ = new pkgRecords(cache_);
3314 resolver_ = new pkgProblemResolver(cache_);
3315 fetcher_ = new pkgAcquire(&status_);
3318 list_ = new pkgSourceList();
3319 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3322 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3323 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3327 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3330 if (cache_->BrokenCount() != 0) {
3331 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3334 if (cache_->BrokenCount() != 0) {
3335 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3339 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3343 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3344 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3345 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3346 // XXX: this could be more intelligent
3347 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3348 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3350 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3355 /*std::vector<Package *> packages;
3356 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3357 [packages_ release];
3362 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3363 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3364 //packages.push_back(package);
3365 CFArrayAppendValue(packages_, [package retain]);
3369 /*if (packages.empty())
3370 packages_ = [[NSArray alloc] init];
3372 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3375 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3376 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3377 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3385 /*if (!packages.empty())
3386 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3387 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3389 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3391 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3393 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3397 } } CYPoolEnd() _trace(); }
3399 - (void) configure {
3400 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3401 system([dpkg UTF8String]);
3405 // XXX: I don't remember this condition
3410 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3412 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3414 if ([self popErrorWithTitle:title])
3418 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3421 public pkgArchiveCleaner
3424 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3429 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3436 fetcher_->Shutdown();
3438 pkgRecords records(cache_);
3440 lock_ = new FileFd();
3441 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3443 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3445 if ([self popErrorWithTitle:title])
3449 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3452 manager_ = (_system->CreatePM(cache_));
3453 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3460 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3462 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3464 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3466 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3467 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3470 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3475 bool failed = false;
3476 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3477 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3479 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3482 std::string uri = (*item)->DescURI();
3483 std::string error = (*item)->ErrorText;
3485 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3488 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3489 withObject:[NSArray arrayWithObjects:
3490 [NSString stringWithUTF8String:error.c_str()],
3502 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3504 if (_error->PendingError()) {
3509 if (result == pkgPackageManager::Failed) {
3514 if (result != pkgPackageManager::Completed) {
3519 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3521 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3523 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3524 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3527 if (![before isEqualToArray:after])
3532 NSString *title(UCLocalize("UPGRADE"));
3533 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3539 [self updateWithStatus:status_];
3542 - (void) setVisible {
3543 for (Package *package in [self packages])
3544 [package setVisible];
3547 - (void) updateWithStatus:(Status &)status {
3548 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3549 NSString *title(UCLocalize("REFRESHING_DATA"));
3552 if (!list.ReadMainList())
3553 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3556 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3557 if ([self popErrorWithTitle:title])
3560 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3561 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3562 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3564 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3568 - (void) setDelegate:(id)delegate {
3569 delegate_ = delegate;
3570 status_.setDelegate(delegate);
3571 progress_.setDelegate(delegate);
3574 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3575 SourceMap::const_iterator i(sources_.find(file->ID));
3576 return i == sources_.end() ? nil : i->second;
3582 /* Confirmation Controller {{{ */
3583 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3584 if (!iterator.end())
3585 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3586 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3588 pkgCache::PkgIterator package(dep.TargetPkg());
3591 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3599 /* Web Scripting {{{ */
3600 @interface CydiaObject : NSObject {
3605 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3608 @implementation CydiaObject
3611 [indirect_ release];
3615 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3616 if ((self = [super init]) != nil) {
3617 indirect_ = [indirect retain];
3621 - (void) setDelegate:(id)delegate {
3622 delegate_ = delegate;
3625 + (NSArray *) _attributeKeys {
3626 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3629 - (NSArray *) attributeKeys {
3630 return [[self class] _attributeKeys];
3633 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3634 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3637 - (NSString *) device {
3638 return [[UIDevice currentDevice] uniqueIdentifier];
3641 #if 0 // XXX: implement!
3642 - (NSString *) mac {
3643 if (![indirect_ promptForSensitive:@"Mac Address"])
3647 - (NSString *) serial {
3648 if (![indirect_ promptForSensitive:@"Serial #"])
3652 - (NSString *) firewire {
3653 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3657 - (NSString *) imei {
3658 if (![indirect_ promptForSensitive:@"IMEI"])
3663 + (NSString *) webScriptNameForSelector:(SEL)selector {
3664 if (selector == @selector(close))
3666 else if (selector == @selector(getInstalledPackages))
3667 return @"getInstalledPackages";
3668 else if (selector == @selector(getPackageById:))
3669 return @"getPackageById";
3670 else if (selector == @selector(installPackages:))
3671 return @"installPackages";
3672 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3673 return @"setButtonImage";
3674 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3675 return @"setButtonTitle";
3676 else if (selector == @selector(setPopupHook:))
3677 return @"setPopupHook";
3678 else if (selector == @selector(setSpecial:))
3679 return @"setSpecial";
3680 else if (selector == @selector(setToken:))
3682 else if (selector == @selector(setViewportWidth:))
3683 return @"setViewportWidth";
3684 else if (selector == @selector(supports:))
3686 else if (selector == @selector(stringWithFormat:arguments:))
3688 else if (selector == @selector(localizedStringForKey:value:table:))
3690 else if (selector == @selector(du:))
3692 else if (selector == @selector(statfs:))
3698 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3699 return [self webScriptNameForSelector:selector] == nil;
3702 - (BOOL) supports:(NSString *)feature {
3703 return [feature isEqualToString:@"window.open"];
3706 - (NSArray *) getInstalledPackages {
3707 NSArray *packages([[Database sharedInstance] packages]);
3708 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3709 for (Package *package in packages)
3710 if ([package installed] != nil)
3711 [installed addObject:package];
3715 - (Package *) getPackageById:(NSString *)id {
3716 Package *package([[Database sharedInstance] packageWithName:id]);
3721 - (NSArray *) statfs:(NSString *)path {
3724 if (path == nil || statfs([path UTF8String], &stat) == -1)
3727 return [NSArray arrayWithObjects:
3728 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3729 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3730 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3734 - (NSNumber *) du:(NSString *)path {
3735 NSNumber *value(nil);
3738 _assert(pipe(fds) != -1);
3740 pid_t pid(ExecFork());
3742 _assert(dup2(fds[1], 1) != -1);
3743 _assert(close(fds[0]) != -1);
3744 _assert(close(fds[1]) != -1);
3745 /* XXX: this should probably not use du */
3746 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3751 _assert(close(fds[1]) != -1);
3753 if (FILE *du = fdopen(fds[0], "r")) {
3755 while (fgets(line, sizeof(line), du) != NULL) {
3756 size_t length(strlen(line));
3757 while (length != 0 && line[length - 1] == '\n')
3758 line[--length] = '\0';
3759 if (char *tab = strchr(line, '\t')) {
3761 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3766 } else _assert(close(fds[0]));
3770 if (waitpid(pid, &status, 0) == -1)
3773 else _assert(false);
3782 - (void) installPackages:(NSArray *)packages {
3783 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3786 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3787 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3790 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3791 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3794 - (void) setSpecial:(id)function {
3795 [indirect_ setSpecial:function];
3798 - (void) setToken:(NSString *)token {
3801 Token_ = [token retain];
3803 [Metadata_ setObject:Token_ forKey:@"Token"];
3807 - (void) setPopupHook:(id)function {
3808 [indirect_ setPopupHook:function];
3811 - (void) setViewportWidth:(float)width {
3812 [indirect_ setViewportWidth:width];
3815 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3816 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3817 unsigned count([arguments count]);
3819 for (unsigned i(0); i != count; ++i)
3820 values[i] = [arguments objectAtIndex:i];
3821 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3824 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3825 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3827 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3829 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3835 /* Cydia Browser Controller {{{ */
3836 @interface CYBrowserController : BrowserController {
3837 CydiaObject *cydia_;
3842 @implementation CYBrowserController
3849 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3852 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3853 [super webView:view didClearWindowObject:window forFrame:frame];
3855 WebDataSource *source([frame dataSource]);
3856 NSURLResponse *response([source response]);
3857 NSURL *url([response URL]);
3858 NSString *scheme([url scheme]);
3860 NSHTTPURLResponse *http;
3861 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3862 http = (NSHTTPURLResponse *) response;
3866 NSDictionary *headers([http allHeaderFields]);
3867 NSString *host([url host]);
3868 [self setHeaders:headers forHost:host];
3871 [host isEqualToString:@"cydia.saurik.com"] ||
3872 [host hasSuffix:@".cydia.saurik.com"] ||
3873 [scheme isEqualToString:@"file"]
3875 [window setValue:cydia_ forKey:@"cydia"];
3878 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3879 if (System_ != NULL)
3880 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3881 if (Machine_ != NULL)
3882 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3884 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3886 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3889 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3890 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3891 [self _setMoreHeaders:copy];
3895 - (void) setDelegate:(id)delegate {
3896 [super setDelegate:delegate];
3897 [cydia_ setDelegate:delegate];
3901 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3902 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3904 WebView *webview([[webview_ _documentView] webView]);
3906 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3908 NSString *application = package == nil ? @"Cydia" : [NSString
3909 stringWithFormat:@"Cydia/%@",
3914 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3916 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3917 if (Product_ != nil)
3918 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3920 [webview setApplicationNameForUserAgent:application];
3927 /* Confirmation {{{ */
3928 @protocol ConfirmationControllerDelegate
3929 - (void) cancelAndClear:(bool)clear;
3930 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3934 @interface ConfirmationController : CYBrowserController {
3935 _transient Database *database_;
3936 UIAlertView *essential_;
3943 - (id) initWithDatabase:(Database *)database;
3947 @implementation ConfirmationController
3954 if (essential_ != nil)
3955 [essential_ release];
3959 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3960 NSString *context([alert context]);
3962 if ([context isEqualToString:@"remove"]) {
3963 if (button == [alert cancelButtonIndex]) {
3964 [self dismissModalViewControllerAnimated:YES];
3965 } else if (button == [alert firstOtherButtonIndex]) {
3968 [delegate_ confirmWithNavigationController:[self navigationController]];
3971 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3972 } else if ([context isEqualToString:@"unable"]) {
3973 [self dismissModalViewControllerAnimated:YES];
3974 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3976 [super alertView:alert clickedButtonAtIndex:button];
3980 - (void) _doContinue {
3981 [self dismissModalViewControllerAnimated:YES];
3982 [delegate_ cancelAndClear:NO];
3985 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
3986 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
3990 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3991 [super webView:view didClearWindowObject:window forFrame:frame];
3992 [window setValue:changes_ forKey:@"changes"];
3993 [window setValue:issues_ forKey:@"issues"];
3994 [window setValue:sizes_ forKey:@"sizes"];
3995 [window setValue:self forKey:@"queue"];
3998 - (id) initWithDatabase:(Database *)database {
3999 if ((self = [super init]) != nil) {
4000 database_ = database;
4002 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4004 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4005 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4006 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4007 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4008 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4012 pkgDepCache::Policy *policy([database_ policy]);
4014 pkgCacheFile &cache([database_ cache]);
4015 NSArray *packages = [database_ packages];
4016 for (Package *package in packages) {
4017 pkgCache::PkgIterator iterator = [package iterator];
4018 pkgDepCache::StateCache &state(cache[iterator]);
4020 NSString *name([package name]);
4022 if (state.NewInstall())
4023 [installing addObject:name];
4024 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4025 [reinstalling addObject:name];
4026 else if (state.Upgrade())
4027 [upgrading addObject:name];
4028 else if (state.Downgrade())
4029 [downgrading addObject:name];
4030 else if (state.Delete()) {
4031 if ([package essential])
4033 [removing addObject:name];
4036 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4037 substrate_ |= DepSubstrate(iterator.CurrentVer());
4042 else if (Advanced_) {
4043 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4045 essential_ = [[UIAlertView alloc]
4046 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4047 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4049 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4050 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4053 [essential_ setContext:@"remove"];
4055 essential_ = [[UIAlertView alloc]
4056 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4057 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4059 cancelButtonTitle:UCLocalize("OKAY")
4060 otherButtonTitles:nil
4063 [essential_ setContext:@"unable"];
4066 changes_ = [[NSArray alloc] initWithObjects:
4074 issues_ = [database_ issues];
4076 issues_ = [issues_ retain];
4078 sizes_ = [[NSArray alloc] initWithObjects:
4079 SizeString([database_ fetcher].FetchNeeded()),
4080 SizeString([database_ fetcher].PartialPresent()),
4083 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4085 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
4086 initWithTitle:UCLocalize("CANCEL")
4087 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4088 style:UIBarButtonItemStylePlain
4090 action:@selector(cancelButtonClicked)
4092 [[self navigationItem] setLeftBarButtonItem:leftItem];
4097 - (void) applyRightButton {
4098 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
4099 initWithTitle:UCLocalize("CONFIRM")
4100 style:UIBarButtonItemStylePlain
4102 action:@selector(confirmButtonClicked)
4104 #if !AlwaysReload && !IgnoreInstall
4105 if (issues_ == nil && ![self isLoading]) [[self navigationItem] setRightBarButtonItem:rightItem];
4106 else [super applyRightButton];
4108 [[self navigationItem] setRightBarButtonItem:nil];
4110 [rightItem release];
4113 - (void) cancelButtonClicked {
4114 [self dismissModalViewControllerAnimated:YES];
4115 [delegate_ cancelAndClear:YES];
4119 - (void) confirmButtonClicked {
4123 if (essential_ != nil)
4128 [delegate_ confirmWithNavigationController:[self navigationController]];
4136 /* Progress Data {{{ */
4137 @interface ProgressData : NSObject {
4143 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4150 @implementation ProgressData
4152 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4153 if ((self = [super init]) != nil) {
4154 selector_ = selector;
4174 /* Progress Controller {{{ */
4175 @interface ProgressController : CYViewController <
4176 ConfigurationDelegate,
4179 _transient Database *database_;
4180 UIProgressBar *progress_;
4181 UITextView *output_;
4182 UITextLabel *status_;
4183 UIPushButton *close_;
4185 SHA1SumValue springlist_;
4186 SHA1SumValue notifyconf_;
4190 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4192 - (void) _retachThread;
4193 - (void) _detachNewThreadData:(ProgressData *)data;
4194 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4200 @protocol ProgressControllerDelegate
4201 - (void) progressControllerIsComplete:(ProgressController *)sender;
4204 @implementation ProgressController
4207 [database_ setDelegate:nil];
4208 [progress_ release];
4217 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4218 if ((self = [super init]) != nil) {
4219 database_ = database;
4220 [database_ setDelegate:self];
4221 delegate_ = delegate;
4223 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4225 progress_ = [[UIProgressBar alloc] init];
4226 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4227 [progress_ setStyle:0];
4229 status_ = [[UITextLabel alloc] init];
4230 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4231 [status_ setColor:[UIColor whiteColor]];
4232 [status_ setBackgroundColor:[UIColor clearColor]];
4233 [status_ setCentersHorizontally:YES];
4234 //[status_ setFont:font];
4236 output_ = [[UITextView alloc] init];
4238 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4239 //[output_ setTextFont:@"Courier New"];
4240 [output_ setFont:[[output_ font] fontWithSize:12]];
4241 [output_ setTextColor:[UIColor whiteColor]];
4242 [output_ setBackgroundColor:[UIColor clearColor]];
4243 [output_ setMarginTop:0];
4244 [output_ setAllowsRubberBanding:YES];
4245 [output_ setEditable:NO];
4246 [[self view] addSubview:output_];
4248 close_ = [[UIPushButton alloc] init];
4249 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4250 [close_ setAutosizesToFit:NO];
4251 [close_ setDrawsShadow:YES];
4252 [close_ setStretchBackground:YES];
4253 [close_ setEnabled:YES];
4254 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4255 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4256 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4257 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4261 - (void) positionViews {
4262 CGRect bounds = [[self view] bounds];
4263 CGSize prgsize = [UIProgressBar defaultSize];
4266 (bounds.size.width - prgsize.width) / 2,
4267 bounds.size.height - prgsize.height - 20
4270 float closewidth = bounds.size.width - 20;
4271 if (closewidth > 300) closewidth = 300;
4273 [progress_ setFrame:prgrect];
4274 [status_ setFrame:CGRectMake(
4276 bounds.size.height - prgsize.height - 50,
4277 bounds.size.width - 20,
4280 [output_ setFrame:CGRectMake(
4283 bounds.size.width - 20,
4284 bounds.size.height - 62
4286 [close_ setFrame:CGRectMake(
4287 (bounds.size.width - closewidth) / 2,
4288 bounds.size.height - prgsize.height - 50,
4294 - (void) viewWillAppear:(BOOL)animated {
4295 [super viewDidAppear:animated];
4296 [[self navigationItem] setHidesBackButton:YES];
4297 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4299 [self positionViews];
4302 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4303 [self positionViews];
4306 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4307 NSString *context([alert context]);
4309 if ([context isEqualToString:@"conffile"]) {
4310 FILE *input = [database_ input];
4311 if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
4312 else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
4317 - (void) closeButtonPushed {
4320 UpdateExternalStatus(0);
4324 [self dismissModalViewControllerAnimated:YES];
4328 [delegate_ terminateWithSuccess];
4329 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4330 [delegate_ suspendWithAnimation:YES];
4332 [delegate_ suspend];*/
4336 system("launchctl stop com.apple.SpringBoard");
4340 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4349 - (void) _retachThread {
4350 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4352 [[self view] addSubview:close_];
4353 [progress_ removeFromSuperview];
4354 [status_ removeFromSuperview];
4356 [database_ popErrorWithTitle:title_];
4357 [delegate_ progressControllerIsComplete:self];
4361 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4364 MMap mmap(file, MMap::ReadOnly);
4366 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4367 if (!(notifyconf_ == sha1.Result()))
4374 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4377 MMap mmap(file, MMap::ReadOnly);
4379 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4380 if (!(springlist_ == sha1.Result()))
4386 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4387 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4388 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4389 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4390 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4393 system("su -c /usr/bin/uicache mobile");
4395 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4397 [delegate_ setStatusBarShowsProgress:NO];
4400 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4401 [[data target] performSelector:[data selector] withObject:[data object]];
4404 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4407 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4408 UpdateExternalStatus(1);
4415 title_ = [title retain];
4417 [[self navigationItem] setTitle:title_];
4419 [status_ setText:nil];
4420 [output_ setText:@""];
4421 [progress_ setProgress:0];
4423 [close_ removeFromSuperview];
4424 [[self view] addSubview:progress_];
4425 [[self view] addSubview:status_];
4427 [delegate_ setStatusBarShowsProgress:YES];
4432 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4435 MMap mmap(file, MMap::ReadOnly);
4437 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4438 notifyconf_ = sha1.Result();
4444 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4447 MMap mmap(file, MMap::ReadOnly);
4449 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4450 springlist_ = sha1.Result();
4455 detachNewThreadSelector:@selector(_detachNewThreadData:)
4457 withObject:[[ProgressData alloc]
4458 initWithSelector:selector
4465 - (void) repairWithSelector:(SEL)selector {
4467 detachNewThreadSelector:selector
4470 title:UCLocalize("REPAIRING")
4474 - (void) setConfigurationData:(NSString *)data {
4476 performSelectorOnMainThread:@selector(_setConfigurationData:)
4482 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4483 CYActionSheet *sheet([[[CYActionSheet alloc]
4485 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4486 defaultButtonIndex:0
4489 [sheet setMessage:error];
4490 [sheet yieldToPopupAlertAnimated:YES];
4494 - (void) setProgressTitle:(NSString *)title {
4496 performSelectorOnMainThread:@selector(_setProgressTitle:)
4502 - (void) setProgressPercent:(float)percent {
4504 performSelectorOnMainThread:@selector(_setProgressPercent:)
4505 withObject:[NSNumber numberWithFloat:percent]
4510 - (void) startProgress {
4513 - (void) addProgressOutput:(NSString *)output {
4515 performSelectorOnMainThread:@selector(_addProgressOutput:)
4521 - (bool) isCancelling:(size_t)received {
4525 - (void) _setConfigurationData:(NSString *)data {
4526 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4528 if (!conffile_r(data)) {
4529 lprintf("E:invalid conffile\n");
4533 NSString *ofile = conffile_r[1];
4534 //NSString *nfile = conffile_r[2];
4536 UIAlertView *alert = [[[UIAlertView alloc]
4537 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4538 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4540 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4541 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4542 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4546 [alert setContext:@"conffile"];
4550 - (void) _setProgressTitle:(NSString *)title {
4551 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4552 for (size_t i(0), e([words count]); i != e; ++i) {
4553 NSString *word([words objectAtIndex:i]);
4554 if (Package *package = [database_ packageWithName:word])
4555 [words replaceObjectAtIndex:i withObject:[package name]];
4558 [status_ setText:[words componentsJoinedByString:@" "]];
4561 - (void) _setProgressPercent:(NSNumber *)percent {
4562 [progress_ setProgress:[percent floatValue]];
4565 - (void) _addProgressOutput:(NSString *)output {
4566 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4567 CGSize size = [output_ contentSize];
4568 CGRect rect = {{0, size.height}, {size.width, 0}};
4569 [output_ scrollRectToVisible:rect animated:YES];
4572 - (BOOL) isRunning {
4579 /* Cell Content View {{{ */
4580 @protocol ContentDelegate
4581 - (void) drawContentRect:(CGRect)rect;
4584 @interface ContentView : UIView {
4585 _transient id<ContentDelegate> delegate_;
4590 @implementation ContentView
4591 - (id) initWithFrame:(CGRect)frame {
4592 if ((self = [super initWithFrame:frame]) != nil) {
4593 /* Fix landscape stretching. */
4594 [self setNeedsDisplayOnBoundsChange:YES];
4598 - (void) setDelegate:(id<ContentDelegate>)delegate {
4599 delegate_ = delegate;
4602 - (void) drawRect:(CGRect)rect {
4603 [super drawRect:rect];
4604 [delegate_ drawContentRect:rect];
4608 /* Package Cell {{{ */
4609 @interface PackageCell : UITableViewCell <
4614 NSString *description_;
4620 ContentView *content_;
4626 - (PackageCell *) init;
4627 - (void) setPackage:(Package *)package;
4629 + (int) heightForPackage:(Package *)package;
4630 - (void) drawContentRect:(CGRect)rect;
4634 @implementation PackageCell
4636 - (void) clearPackage {
4647 if (description_ != nil) {
4648 [description_ release];
4652 if (source_ != nil) {
4657 if (badge_ != nil) {
4662 if (placard_ != nil) {
4672 [self clearPackage];
4679 return faded_ ? [self selectionPercent] : fade_;
4682 - (PackageCell *) init {
4683 CGRect frame(CGRectMake(0, 0, 320, 74));
4684 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4685 UIView *content([self contentView]);
4686 CGRect bounds([content bounds]);
4688 content_ = [[ContentView alloc] initWithFrame:bounds];
4689 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4690 [content addSubview:content_];
4692 [content_ setDelegate:self];
4693 [content_ setOpaque:YES];
4694 if ([self respondsToSelector:@selector(selectionPercent)])
4699 - (void) _setBackgroundColor {
4701 if (NSString *mode = [package_ mode]) {
4702 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4703 color = remove ? RemovingColor_ : InstallingColor_;
4705 color = [UIColor whiteColor];
4707 [content_ setBackgroundColor:color];
4708 [self setNeedsDisplay];
4711 - (void) setPackage:(Package *)package {
4712 [self clearPackage];
4715 Source *source = [package source];
4717 icon_ = [[package icon] retain];
4718 name_ = [[package name] retain];
4721 description_ = [package longDescription];
4722 if (description_ == nil)
4723 description_ = [package shortDescription];
4724 if (description_ != nil)
4725 description_ = [description_ retain];
4727 commercial_ = [package isCommercial];
4729 package_ = [package retain];
4731 NSString *label = nil;
4732 bool trusted = false;
4734 if (source != nil) {
4735 label = [source label];
4736 trusted = [source trusted];
4737 } else if ([[package id] isEqualToString:@"firmware"])
4738 label = UCLocalize("APPLE");
4740 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4742 NSString *from(label);
4744 NSString *section = [package simpleSection];
4745 if (section != nil && ![section isEqualToString:label]) {
4746 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4747 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4750 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4751 source_ = [from retain];
4753 if (NSString *purpose = [package primaryPurpose])
4754 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4755 badge_ = [badge_ retain];
4757 if ([package installed] != nil)
4758 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4759 placard_ = [placard_ retain];
4761 [self _setBackgroundColor];
4762 [content_ setNeedsDisplay];
4765 - (void) drawContentRect:(CGRect)rect {
4766 bool selected([self isSelected]);
4767 float width([self bounds].size.width);
4770 CGContextRef context(UIGraphicsGetCurrentContext());
4771 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4772 CGContextFillRect(context, rect);
4777 rect.size = [icon_ size];
4779 rect.size.width /= 2;
4780 rect.size.height /= 2;
4782 rect.origin.x = 25 - rect.size.width / 2;
4783 rect.origin.y = 25 - rect.size.height / 2;
4785 [icon_ drawInRect:rect];
4788 if (badge_ != nil) {
4789 CGSize size = [badge_ size];
4791 [badge_ drawAtPoint:CGPointMake(
4792 36 - size.width / 2,
4793 36 - size.height / 2
4801 UISetColor(commercial_ ? Purple_ : Black_);
4802 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4803 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4806 UISetColor(commercial_ ? Purplish_ : Gray_);
4807 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4809 if (placard_ != nil)
4810 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4813 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4814 //[self _setBackgroundColor];
4815 [super setSelected:selected animated:fade];
4816 [content_ setNeedsDisplay];
4819 + (int) heightForPackage:(Package *)package {
4825 /* Section Cell {{{ */
4826 @interface SectionCell : UITableViewCell <
4834 ContentView *content_;
4839 - (void) setSection:(Section *)section editing:(BOOL)editing;
4843 @implementation SectionCell
4845 - (void) clearSection {
4846 if (basic_ != nil) {
4851 if (section_ != nil) {
4861 if (count_ != nil) {
4868 [self clearSection];
4876 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4877 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4878 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4879 switch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4880 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4882 UIView *content([self contentView]);
4883 CGRect bounds([content bounds]);
4885 content_ = [[ContentView alloc] initWithFrame:bounds];
4886 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4887 [content addSubview:content_];
4888 [content_ setBackgroundColor:[UIColor whiteColor]];
4890 [content_ setDelegate:self];
4894 - (void) onSwitch:(id)sender {
4895 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4896 if (metadata == nil) {
4897 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4898 [Sections_ setObject:metadata forKey:basic_];
4902 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4905 - (void) setSection:(Section *)section editing:(BOOL)editing {
4906 if (editing != editing_) {
4908 [switch_ removeFromSuperview];
4910 [self addSubview:switch_];
4914 [self clearSection];
4916 if (section == nil) {
4917 name_ = [UCLocalize("ALL_PACKAGES") retain];
4920 basic_ = [section name];
4922 basic_ = [basic_ retain];
4924 section_ = [section localized];
4925 if (section_ != nil)
4926 section_ = [section_ retain];
4928 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4929 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4932 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4935 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4936 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
4938 [content_ setNeedsDisplay];
4941 - (void) setFrame:(CGRect)frame {
4942 [super setFrame:frame];
4944 CGRect rect([switch_ frame]);
4945 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4948 - (void) drawContentRect:(CGRect)rect {
4949 BOOL selected = [self isSelected];
4951 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4959 float width(rect.size.width);
4963 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4965 CGSize size = [count_ sizeWithFont:Font14_];
4969 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4975 /* File Table {{{ */
4976 @interface FileTable : CYViewController <
4977 UITableViewDataSource,
4980 _transient Database *database_;
4983 NSMutableArray *files_;
4987 - (id) initWithDatabase:(Database *)database;
4988 - (void) setPackage:(Package *)package;
4992 @implementation FileTable
4995 if (package_ != nil)
5004 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5005 return files_ == nil ? 0 : [files_ count];
5008 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5012 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5013 static NSString *reuseIdentifier = @"Cell";
5015 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5017 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5018 [cell setFont:[UIFont systemFontOfSize:16]];
5020 [cell setText:[files_ objectAtIndex:indexPath.row]];
5021 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5026 - (id) initWithDatabase:(Database *)database {
5027 if ((self = [super init]) != nil) {
5028 database_ = database;
5030 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5032 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5034 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5035 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5036 [list_ setRowHeight:24.0f];
5037 [[self view] addSubview:list_];
5039 [list_ setDataSource:self];
5040 [list_ setDelegate:self];
5044 - (void) setPackage:(Package *)package {
5045 if (package_ != nil) {
5046 [package_ autorelease];
5055 [files_ removeAllObjects];
5057 if (package != nil) {
5058 package_ = [package retain];
5059 name_ = [[package id] retain];
5061 if (NSArray *files = [package files])
5062 [files_ addObjectsFromArray:files];
5064 if ([files_ count] != 0) {
5065 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5066 [files_ removeObjectAtIndex:0];
5067 [files_ sortUsingSelector:@selector(compareByPath:)];
5069 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5070 [stack addObject:@"/"];
5072 for (int i(0), e([files_ count]); i != e; ++i) {
5073 NSString *file = [files_ objectAtIndex:i];
5074 while (![file hasPrefix:[stack lastObject]])
5075 [stack removeLastObject];
5076 NSString *directory = [stack lastObject];
5077 [stack addObject:[file stringByAppendingString:@"/"]];
5078 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5079 ([stack count] - 2) * 3, "",
5080 [file substringFromIndex:[directory length]]
5089 - (void) reloadData {
5090 [self setPackage:[database_ packageWithName:name_]];
5095 /* Package Controller {{{ */
5096 @interface PackageController : CYBrowserController <
5097 UIActionSheetDelegate
5099 _transient Database *database_;
5103 NSMutableArray *buttons_;
5104 UIBarButtonItem *button_;
5107 - (id) initWithDatabase:(Database *)database;
5108 - (void) setPackage:(Package *)package;
5112 @implementation PackageController
5115 if (package_ != nil)
5129 if ([self retainCount] == 1)
5130 [delegate_ setPackageController:self];
5134 /* XXX: this is not safe at all... localization of /fail/ */
5135 - (void) _clickButtonWithName:(NSString *)name {
5136 if ([name isEqualToString:UCLocalize("CLEAR")])
5137 [delegate_ clearPackage:package_];
5138 else if ([name isEqualToString:UCLocalize("INSTALL")])
5139 [delegate_ installPackage:package_];
5140 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5141 [delegate_ installPackage:package_];
5142 else if ([name isEqualToString:UCLocalize("REMOVE")])
5143 [delegate_ removePackage:package_];
5144 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5145 [delegate_ installPackage:package_];
5146 else _assert(false);
5149 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5150 NSString *context([sheet context]);
5152 if ([context isEqualToString:@"modify"]) {
5153 if (button != [sheet cancelButtonIndex]) {
5154 NSString *buttonName = [buttons_ objectAtIndex:button];
5155 [self _clickButtonWithName:buttonName];
5158 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5162 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5163 [super webView:view didClearWindowObject:window forFrame:frame];
5164 [window setValue:package_ forKey:@"package"];
5167 - (bool) _allowJavaScriptPanel {
5172 - (void) _customButtonClicked {
5173 int count([buttons_ count]);
5178 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5180 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5181 [buttons addObjectsFromArray:buttons_];
5183 UIActionSheet *sheet = [[[UIActionSheet alloc]
5186 cancelButtonTitle:nil
5187 destructiveButtonTitle:nil
5188 otherButtonTitles:nil
5191 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5193 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5194 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5196 [sheet setContext:@"modify"];
5198 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5202 // We don't want to allow non-commercial packages to do custom things to the install button,
5203 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5204 - (void) customButtonClicked {
5206 [super customButtonClicked];
5208 [self _customButtonClicked];
5211 - (void) reloadButtonClicked {
5212 // Don't reload a package view by clicking the button.
5215 - (void) applyLoadingTitle {
5216 // Don't show "Loading" as the title. Ever.
5219 - (UIBarButtonItem *) rightButton {
5224 - (id) initWithDatabase:(Database *)database {
5225 if ((self = [super init]) != nil) {
5226 database_ = database;
5227 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5228 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5232 - (void) setPackage:(Package *)package {
5233 if (package_ != nil) {
5234 [package_ autorelease];
5243 [buttons_ removeAllObjects];
5245 if (package != nil) {
5248 package_ = [package retain];
5249 name_ = [[package id] retain];
5250 commercial_ = [package isCommercial];
5252 if ([package_ mode] != nil)
5253 [buttons_ addObject:UCLocalize("CLEAR")];
5254 if ([package_ source] == nil);
5255 else if ([package_ upgradableAndEssential:NO])
5256 [buttons_ addObject:UCLocalize("UPGRADE")];
5257 else if ([package_ uninstalled])
5258 [buttons_ addObject:UCLocalize("INSTALL")];
5260 [buttons_ addObject:UCLocalize("REINSTALL")];
5261 if (![package_ uninstalled])
5262 [buttons_ addObject:UCLocalize("REMOVE")];
5269 switch ([buttons_ count]) {
5270 case 0: title = nil; break;
5271 case 1: title = [buttons_ objectAtIndex:0]; break;
5272 default: title = UCLocalize("MODIFY"); break;
5275 button_ = [[UIBarButtonItem alloc]
5277 style:UIBarButtonItemStylePlain
5279 action:@selector(customButtonClicked)
5283 - (bool) isLoading {
5284 return commercial_ ? [super isLoading] : false;
5287 - (void) reloadData {
5288 [self setPackage:[database_ packageWithName:name_]];
5293 /* Package Table {{{ */
5294 @interface PackageTable : UIView <
5295 UITableViewDataSource,
5298 _transient Database *database_;
5299 NSMutableArray *packages_;
5300 NSMutableArray *sections_;
5302 NSMutableArray *index_;
5303 NSMutableDictionary *indices_;
5309 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5311 - (void) setDelegate:(id)delegate;
5313 - (void) reloadData;
5314 - (void) resetCursor;
5316 - (UITableView *) list;
5318 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5320 - (void) deselectWithAnimation:(BOOL)animated;
5324 @implementation PackageTable
5327 [packages_ release];
5328 [sections_ release];
5336 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5337 NSInteger count([sections_ count]);
5338 return count == 0 ? 1 : count;
5341 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5342 if ([sections_ count] == 0)
5344 return [[sections_ objectAtIndex:section] name];
5347 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5348 if ([sections_ count] == 0)
5350 return [[sections_ objectAtIndex:section] count];
5353 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5354 Section *section([sections_ objectAtIndex:[path section]]);
5355 NSInteger row([path row]);
5356 Package *package([packages_ objectAtIndex:([section row] + row)]);
5360 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5361 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5363 cell = [[[PackageCell alloc] init] autorelease];
5364 [cell setPackage:[self packageAtIndexPath:path]];
5368 - (void) deselectWithAnimation:(BOOL)animated {
5369 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5372 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5373 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5376 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5377 Package *package([self packageAtIndexPath:path]);
5378 package = [database_ packageWithName:[package id]];
5379 [target_ performSelector:action_ withObject:package];
5383 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5384 return [packages_ count] > 20 ? index_ : nil;
5387 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5391 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5392 if ((self = [super initWithFrame:frame]) != nil) {
5393 database_ = database;
5398 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5399 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5401 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5402 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5404 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5405 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5406 [list_ setRowHeight:73.0f];
5407 [self addSubview:list_];
5409 [list_ setDataSource:self];
5410 [list_ setDelegate:self];
5414 - (void) setDelegate:(id)delegate {
5415 delegate_ = delegate;
5418 - (bool) hasPackage:(Package *)package {
5422 - (void) reloadData {
5423 NSArray *packages = [database_ packages];
5425 [packages_ removeAllObjects];
5426 [sections_ removeAllObjects];
5428 _profile(PackageTable$reloadData$Filter)
5429 for (Package *package in packages)
5430 if ([self hasPackage:package])
5431 [packages_ addObject:package];
5434 [index_ removeAllObjects];
5435 [indices_ removeAllObjects];
5437 Section *section = nil;
5439 _profile(PackageTable$reloadData$Section)
5440 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5444 _profile(PackageTable$reloadData$Section$Package)
5445 package = [packages_ objectAtIndex:offset];
5446 index = [package index];
5449 if (section == nil || [section index] != index) {
5450 _profile(PackageTable$reloadData$Section$Allocate)
5451 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5454 [index_ addObject:[section name]];
5455 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5457 _profile(PackageTable$reloadData$Section$Add)
5458 [sections_ addObject:section];
5462 [section addToCount];
5466 _profile(PackageTable$reloadData$List)
5471 - (void) resetCursor {
5472 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5475 - (UITableView *) list {
5479 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5480 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5485 /* Filtered Package Table {{{ */
5486 @interface FilteredPackageTable : PackageTable {
5492 - (void) setObject:(id)object;
5493 - (void) setObject:(id)object forFilter:(SEL)filter;
5495 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5499 @implementation FilteredPackageTable
5507 - (void) setFilter:(SEL)filter {
5510 /* XXX: this is an unsafe optimization of doomy hell */
5511 Method method(class_getInstanceMethod([Package class], filter));
5512 _assert(method != NULL);
5513 imp_ = method_getImplementation(method);
5514 _assert(imp_ != NULL);
5517 - (void) setObject:(id)object {
5523 object_ = [object retain];
5526 - (void) setObject:(id)object forFilter:(SEL)filter {
5527 [self setFilter:filter];
5528 [self setObject:object];
5531 - (bool) hasPackage:(Package *)package {
5532 _profile(FilteredPackageTable$hasPackage)
5533 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5537 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5538 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5539 [self setFilter:filter];
5540 object_ = [object retain];
5548 /* Filtered Package Controller {{{ */
5549 @interface FilteredPackageController : CYViewController {
5550 _transient Database *database_;
5551 FilteredPackageTable *packages_;
5555 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5559 @implementation FilteredPackageController
5562 [packages_ release];
5568 - (void) viewDidAppear:(BOOL)animated {
5569 [super viewDidAppear:animated];
5570 [packages_ deselectWithAnimation:animated];
5573 - (void) didSelectPackage:(Package *)package {
5574 PackageController *view([delegate_ packageController]);
5575 [view setPackage:package];
5576 [view setDelegate:delegate_];
5577 [[self navigationController] pushViewController:view animated:YES];
5580 - (NSString *) title { return title_; }
5582 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5583 if ((self = [super init]) != nil) {
5584 database_ = database;
5585 title_ = [title copy];
5586 [[self navigationItem] setTitle:title_];
5588 packages_ = [[FilteredPackageTable alloc]
5589 initWithFrame:[[self view] bounds]
5592 action:@selector(didSelectPackage:)
5597 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5598 [[self view] addSubview:packages_];
5602 - (void) reloadData {
5603 [packages_ reloadData];
5606 - (void) setDelegate:(id)delegate {
5607 [super setDelegate:delegate];
5608 [packages_ setDelegate:delegate];
5615 /* Add Source Controller {{{ */
5616 @interface AddSourceController : CYViewController {
5617 _transient Database *database_;
5620 - (id) initWithDatabase:(Database *)database;
5624 @implementation AddSourceController
5626 - (id) initWithDatabase:(Database *)database {
5627 if ((self = [super init]) != nil) {
5628 database_ = database;
5634 /* Source Cell {{{ */
5635 @interface SourceCell : UITableViewCell <
5640 NSString *description_;
5642 ContentView *content_;
5645 - (void) setSource:(Source *)source;
5649 @implementation SourceCell
5651 - (void) clearSource {
5654 [description_ release];
5663 - (void) setSource:(Source *)source {
5667 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5669 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5670 icon_ = [icon_ retain];
5672 origin_ = [[source name] retain];
5673 label_ = [[source uri] retain];
5674 description_ = [[source description] retain];
5676 [content_ setNeedsDisplay];
5685 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5686 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5687 UIView *content([self contentView]);
5688 CGRect bounds([content bounds]);
5690 content_ = [[ContentView alloc] initWithFrame:bounds];
5691 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5692 [content_ setBackgroundColor:[UIColor whiteColor]];
5693 [content addSubview:content_];
5695 [content_ setDelegate:self];
5696 [content_ setOpaque:YES];
5700 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5701 [super setSelected:selected animated:animated];
5702 [content_ setNeedsDisplay];
5705 - (void) drawContentRect:(CGRect)rect {
5706 bool selected([self isSelected]);
5707 float width(rect.size.width);
5710 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5717 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5721 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5725 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5730 /* Source Table {{{ */
5731 @interface SourceTable : CYViewController <
5732 UITableViewDataSource,
5735 _transient Database *database_;
5737 NSMutableArray *sources_;
5741 UIProgressHUD *hud_;
5744 //NSURLConnection *installer_;
5745 NSURLConnection *trivial_;
5746 NSURLConnection *trivial_bz2_;
5747 NSURLConnection *trivial_gz_;
5748 //NSURLConnection *automatic_;
5753 - (id) initWithDatabase:(Database *)database;
5755 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5759 @implementation SourceTable
5761 - (void) _deallocConnection:(NSURLConnection *)connection {
5762 if (connection != nil) {
5763 [connection cancel];
5764 //[connection setDelegate:nil];
5765 [connection release];
5777 //[self _deallocConnection:installer_];
5778 [self _deallocConnection:trivial_];
5779 [self _deallocConnection:trivial_gz_];
5780 [self _deallocConnection:trivial_bz2_];
5781 //[self _deallocConnection:automatic_];
5788 - (void) viewDidAppear:(BOOL)animated {
5789 [super viewDidAppear:animated];
5790 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5793 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5794 return offset_ == 0 ? 1 : 2;
5797 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5798 switch (section + (offset_ == 0 ? 1 : 0)) {
5799 case 0: return UCLocalize("ENTERED_BY_USER");
5800 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5806 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5807 int count = [sources_ count];
5809 case 0: return (offset_ == 0 ? count : offset_);
5810 case 1: return count - offset_;
5816 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5818 switch (indexPath.section) {
5819 case 0: idx = indexPath.row; break;
5820 case 1: idx = indexPath.row + offset_; break;
5824 return [sources_ objectAtIndex:idx];
5827 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5828 Source *source = [self sourceAtIndexPath:indexPath];
5829 return [source description] == nil ? 56 : 73;
5832 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5833 static NSString *cellIdentifier = @"SourceCell";
5835 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5836 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5837 [cell setSource:[self sourceAtIndexPath:indexPath]];
5842 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5843 return UITableViewCellAccessoryDisclosureIndicator;
5846 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5847 Source *source = [self sourceAtIndexPath:indexPath];
5849 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5850 initWithDatabase:database_
5851 title:[source label]
5852 filter:@selector(isVisibleInSource:)
5856 [packages setDelegate:delegate_];
5858 [[self navigationController] pushViewController:packages animated:YES];
5861 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5862 Source *source = [self sourceAtIndexPath:indexPath];
5863 return [source record] != nil;
5866 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5867 Source *source = [self sourceAtIndexPath:indexPath];
5868 [Sources_ removeObjectForKey:[source key]];
5869 [delegate_ syncData];
5873 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5876 @"./", @"Distribution",
5877 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5879 [delegate_ syncData];
5882 - (NSString *) getWarning {
5883 NSString *href(href_);
5884 NSRange colon([href rangeOfString:@"://"]);
5885 if (colon.location != NSNotFound)
5886 href = [href substringFromIndex:(colon.location + 3)];
5887 href = [href stringByAddingPercentEscapes];
5888 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5889 href = [href stringByCachingURLWithCurrentCDN];
5891 NSURL *url([NSURL URLWithString:href]);
5893 NSStringEncoding encoding;
5894 NSError *error(nil);
5896 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5897 return [warning length] == 0 ? nil : warning;
5901 - (void) _endConnection:(NSURLConnection *)connection {
5902 NSURLConnection **field = NULL;
5903 if (connection == trivial_)
5905 else if (connection == trivial_bz2_)
5906 field = &trivial_bz2_;
5907 else if (connection == trivial_gz_)
5908 field = &trivial_gz_;
5909 _assert(field != NULL);
5910 [connection release];
5915 trivial_bz2_ == nil &&
5921 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5924 UIAlertView *alert = [[[UIAlertView alloc]
5925 initWithTitle:UCLocalize("SOURCE_WARNING")
5928 cancelButtonTitle:UCLocalize("CANCEL")
5929 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5932 [alert setContext:@"warning"];
5933 [alert setNumberOfRows:1];
5937 } else if (error_ != nil) {
5938 UIAlertView *alert = [[[UIAlertView alloc]
5939 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5940 message:[error_ localizedDescription]
5942 cancelButtonTitle:UCLocalize("OK")
5943 otherButtonTitles:nil
5946 [alert setContext:@"urlerror"];
5949 UIAlertView *alert = [[[UIAlertView alloc]
5950 initWithTitle:UCLocalize("NOT_REPOSITORY")
5951 message:UCLocalize("NOT_REPOSITORY_EX")
5953 cancelButtonTitle:UCLocalize("OK")
5954 otherButtonTitles:nil
5957 [alert setContext:@"trivial"];
5961 [delegate_ setStatusBarShowsProgress:NO];
5962 [delegate_ removeProgressHUD:hud_];
5972 if (error_ != nil) {
5979 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5980 switch ([response statusCode]) {
5986 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5987 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5989 error_ = [error retain];
5990 [self _endConnection:connection];
5993 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5994 [self _endConnection:connection];
5997 - (NSString *) title { return UCLocalize("SOURCES"); }
5999 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6000 NSMutableURLRequest *request = [NSMutableURLRequest
6001 requestWithURL:[NSURL URLWithString:href]
6002 cachePolicy:NSURLRequestUseProtocolCachePolicy
6003 timeoutInterval:120.0
6006 [request setHTTPMethod:method];
6008 if (Machine_ != NULL)
6009 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6010 if (UniqueID_ != nil)
6011 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6013 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6015 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6018 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6019 NSString *context([alert context]);
6021 if ([context isEqualToString:@"source"]) {
6024 NSString *href = [[alert textField] text];
6026 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6028 if (![href hasSuffix:@"/"])
6029 href_ = [href stringByAppendingString:@"/"];
6032 href_ = [href_ retain];
6034 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6035 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6036 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6037 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6041 hud_ = [[delegate_ addProgressHUD] retain];
6042 [hud_ setText:UCLocalize("VERIFYING_URL")];
6051 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6052 } else if ([context isEqualToString:@"trivial"])
6053 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6054 else if ([context isEqualToString:@"urlerror"])
6055 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6056 else if ([context isEqualToString:@"warning"]) {
6071 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6075 - (id) initWithDatabase:(Database *)database {
6076 if ((self = [super init]) != nil) {
6077 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6078 [self updateButtonsForEditingStatus:NO animated:NO];
6080 database_ = database;
6081 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6083 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6084 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6085 [[self view] addSubview:list_];
6087 [list_ setDataSource:self];
6088 [list_ setDelegate:self];
6094 - (void) reloadData {
6096 if (!list.ReadMainList())
6099 [sources_ removeAllObjects];
6100 [sources_ addObjectsFromArray:[database_ sources]];
6102 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6105 int count([sources_ count]);
6107 for (int i = 0; i != count; i++) {
6108 if ([[sources_ objectAtIndex:i] record] == nil) break;
6112 [list_ setEditing:NO];
6113 [self updateButtonsForEditingStatus:NO animated:NO];
6117 - (void) addButtonClicked {
6118 /*[book_ pushPage:[[[AddSourceController alloc]
6123 UIAlertView *alert = [[[UIAlertView alloc]
6124 initWithTitle:UCLocalize("ENTER_APT_URL")
6127 cancelButtonTitle:UCLocalize("CANCEL")
6128 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6131 [alert setContext:@"source"];
6132 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6134 [alert setNumberOfRows:1];
6135 [alert addTextFieldWithValue:@"http://" label:@""];
6137 UITextInputTraits *traits = [[alert textField] textInputTraits];
6138 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6139 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6140 [traits setKeyboardType:UIKeyboardTypeURL];
6141 // XXX: UIReturnKeyDone
6142 [traits setReturnKeyType:UIReturnKeyNext];
6147 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6148 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
6149 initWithTitle:UCLocalize("ADD")
6150 style:UIBarButtonItemStylePlain
6152 action:@selector(addButtonClicked)
6154 [[self navigationItem] setLeftBarButtonItem:editing ? leftItem : [[self navigationItem] backBarButtonItem] animated:animated];
6157 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6158 initWithTitle:editing ? UCLocalize("DONE") : UCLocalize("EDIT")
6159 style:editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6161 action:@selector(editButtonClicked)
6163 [[self navigationItem] setRightBarButtonItem:rightItem animated:animated];
6164 [rightItem release];
6166 if (IsWildcat_ && !editing) {
6167 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6168 initWithTitle:UCLocalize("SETTINGS")
6169 style:UIBarButtonItemStylePlain
6171 action:@selector(settingsButtonClicked)
6173 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6174 [settingsItem release];
6178 - (void) settingsButtonClicked {
6179 [delegate_ showSettings];
6182 - (void) editButtonClicked {
6183 [list_ setEditing:![list_ isEditing] animated:YES];
6185 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6191 /* Installed Controller {{{ */
6192 @interface InstalledController : FilteredPackageController {
6196 - (id) initWithDatabase:(Database *)database;
6198 - (void) updateRoleButton;
6199 - (void) queueStatusDidChange;
6203 @implementation InstalledController
6209 - (NSString *) title { return UCLocalize("INSTALLED"); }
6211 - (id) initWithDatabase:(Database *)database {
6212 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6213 [self updateRoleButton];
6214 [self queueStatusDidChange];
6219 - (void) queueButtonClicked {
6224 - (void) queueStatusDidChange {
6227 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6228 initWithTitle:UCLocalize("QUEUE")
6229 style:UIBarButtonItemStyleDone
6231 action:@selector(queueButtonClicked)
6233 if (Queuing_) [[self navigationItem] setLeftBarButtonItem:queueItem];
6234 else [[self navigationItem] setLeftBarButtonItem:nil];
6235 [queueItem release];
6240 - (void) reloadData {
6241 [packages_ reloadData];
6244 - (void) updateRoleButton {
6245 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6246 initWithTitle:expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")
6247 style:expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6249 action:@selector(roleButtonClicked)
6251 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) [[self navigationItem] setRightBarButtonItem:rightItem];
6252 [rightItem release];
6255 - (void) roleButtonClicked {
6256 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6257 [packages_ reloadData];
6260 [self updateRoleButton];
6263 - (void) setDelegate:(id)delegate {
6264 [super setDelegate:delegate];
6265 [packages_ setDelegate:delegate];
6271 /* Home Controller {{{ */
6272 @interface HomeController : CYBrowserController {
6277 @implementation HomeController
6279 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6280 [super _setMoreHeaders:request];
6283 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6284 if (UniqueID_ != nil)
6285 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6287 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6290 - (void) aboutButtonClicked {
6291 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6293 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6294 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6295 [alert setCancelButtonIndex:0];
6298 @"Copyright (C) 2008-2010\n"
6299 "Jay Freeman (saurik)\n"
6300 "saurik@saurik.com\n"
6301 "http://www.saurik.com/"
6307 - (void) viewWillAppear:(BOOL)animated {
6308 [super viewWillAppear:animated];
6309 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6312 - (void) viewWillDisappear:(BOOL)animated {
6313 [super viewWillDisappear:animated];
6314 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6318 if ((self = [super init]) != nil) {
6319 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6320 initWithTitle:UCLocalize("ABOUT")
6321 style:UIBarButtonItemStylePlain
6323 action:@selector(aboutButtonClicked)
6330 /* Manage Controller {{{ */
6331 @interface ManageController : CYBrowserController {
6334 - (void) queueStatusDidChange;
6337 @implementation ManageController
6340 if ((self = [super init]) != nil) {
6341 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6343 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6344 initWithTitle:UCLocalize("SETTINGS")
6345 style:UIBarButtonItemStylePlain
6347 action:@selector(settingsButtonClicked)
6349 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6350 [settingsItem release];
6352 [self queueStatusDidChange];
6356 - (void) settingsButtonClicked {
6357 [delegate_ showSettings];
6361 - (void) queueButtonClicked {
6365 - (void) applyLoadingTitle {
6366 // No "Loading" title.
6369 - (void) applyRightButton {
6374 - (void) queueStatusDidChange {
6376 if (!IsWildcat_ && Queuing_) {
6377 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6378 initWithTitle:UCLocalize("QUEUE")
6379 style:UIBarButtonItemStyleDone
6381 action:@selector(queueButtonClicked)
6383 [[self navigationItem] setRightBarButtonItem:queueItem];
6385 [queueItem release];
6387 [[self navigationItem] setRightBarButtonItem:nil];
6392 - (bool) isLoading {
6399 /* Refresh Bar {{{ */
6400 @interface RefreshBar : UINavigationBar {
6401 UIProgressIndicator *indicator_;
6402 UITextLabel *prompt_;
6403 UIProgressBar *progress_;
6404 UINavigationButton *cancel_;
6409 @implementation RefreshBar
6411 - (void) positionViews {
6412 CGRect frame = [cancel_ frame];
6413 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6414 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6415 [cancel_ setFrame:frame];
6417 CGSize prgsize = {75, 100};
6419 [self frame].size.width - prgsize.width - 10,
6420 ([self frame].size.height - prgsize.height) / 2
6422 [progress_ setFrame:prgrect];
6424 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6425 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6426 CGRect indrect = {{indoffset, indoffset}, indsize};
6427 [indicator_ setFrame:indrect];
6429 CGSize prmsize = {215, indsize.height + 4};
6431 indoffset * 2 + indsize.width,
6432 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6434 [prompt_ setFrame:prmrect];
6437 - (void)setFrame:(CGRect)frame {
6438 [super setFrame:frame];
6440 [self positionViews];
6443 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6444 if ((self = [super initWithFrame:frame])) {
6445 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6447 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6448 [self setBarStyle:UIBarStyleBlack];
6450 UIBarStyle barstyle([self _barStyle:NO]);
6451 bool ugly(barstyle == UIBarStyleDefault);
6453 UIProgressIndicatorStyle style = ugly ?
6454 UIProgressIndicatorStyleMediumBrown :
6455 UIProgressIndicatorStyleMediumWhite;
6457 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6458 [indicator_ setStyle:style];
6459 [indicator_ startAnimation];
6460 [self addSubview:indicator_];
6462 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6463 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6464 [prompt_ setBackgroundColor:[UIColor clearColor]];
6465 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6466 [self addSubview:prompt_];
6468 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6469 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6470 [progress_ setStyle:0];
6471 [self addSubview:progress_];
6473 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6474 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6475 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6476 [cancel_ setBarStyle:barstyle];
6478 [self positionViews];
6483 [cancel_ removeFromSuperview];
6487 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6488 [progress_ setProgress:0];
6489 [self addSubview:cancel_];
6493 [cancel_ removeFromSuperview];
6496 - (void) setPrompt:(NSString *)prompt {
6497 [prompt_ setText:prompt];
6500 - (void) setProgress:(float)progress {
6501 [progress_ setProgress:progress];
6507 @class CYNavigationController;
6509 /* Cydia Tab Bar Controller {{{ */
6510 @interface CYTabBarController : UITabBarController {
6511 Database *database_;
6516 @implementation CYTabBarController
6518 /* XXX: some logic should probably go here related to
6519 freeing the view controllers on tab change */
6521 - (void) reloadData {
6522 size_t count([[self viewControllers] count]);
6523 for (size_t i(0); i != count; ++i) {
6524 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6529 - (id) initWithDatabase:(Database *)database {
6530 if ((self = [super init]) != nil) {
6531 database_ = database;
6538 /* Cydia Navigation Controller {{{ */
6539 @interface CYNavigationController : UINavigationController {
6540 _transient Database *database_;
6541 id<UINavigationControllerDelegate> delegate_;
6544 - (id) initWithDatabase:(Database *)database;
6545 - (void) reloadData;
6550 @implementation CYNavigationController
6552 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6553 // Inherit autorotation settings for modal parents.
6554 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6555 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6557 return [super shouldAutorotateToInterfaceOrientation:orientation];
6565 - (void) reloadData {
6566 size_t count([[self viewControllers] count]);
6567 for (size_t i(0); i != count; ++i) {
6568 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6573 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6574 delegate_ = delegate;
6577 - (id) initWithDatabase:(Database *)database {
6578 if ((self = [super init]) != nil) {
6579 database_ = database;
6585 /* Cydia:// Protocol {{{ */
6586 @interface CydiaURLProtocol : NSURLProtocol {
6591 @implementation CydiaURLProtocol
6593 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6594 NSURL *url([request URL]);
6597 NSString *scheme([[url scheme] lowercaseString]);
6598 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6603 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6607 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6608 id<NSURLProtocolClient> client([self client]);
6610 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6612 NSData *data(UIImagePNGRepresentation(icon));
6614 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6615 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6616 [client URLProtocol:self didLoadData:data];
6617 [client URLProtocolDidFinishLoading:self];
6621 - (void) startLoading {
6622 id<NSURLProtocolClient> client([self client]);
6623 NSURLRequest *request([self request]);
6625 NSURL *url([request URL]);
6626 NSString *href([url absoluteString]);
6628 NSString *path([href substringFromIndex:8]);
6629 NSRange slash([path rangeOfString:@"/"]);
6632 if (slash.location == NSNotFound) {
6636 command = [path substringToIndex:slash.location];
6637 path = [path substringFromIndex:(slash.location + 1)];
6640 Database *database([Database sharedInstance]);
6642 if ([command isEqualToString:@"package-icon"]) {
6645 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6646 Package *package([database packageWithName:path]);
6649 UIImage *icon([package icon]);
6650 [self _returnPNGWithImage:icon forRequest:request];
6651 } else if ([command isEqualToString:@"source-icon"]) {
6654 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6655 NSString *source(Simplify(path));
6656 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6658 icon = [UIImage applicationImageNamed:@"unknown.png"];
6659 [self _returnPNGWithImage:icon forRequest:request];
6660 } else if ([command isEqualToString:@"uikit-image"]) {
6663 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6664 UIImage *icon(_UIImageWithName(path));
6665 [self _returnPNGWithImage:icon forRequest:request];
6666 } else if ([command isEqualToString:@"section-icon"]) {
6669 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6670 NSString *section(Simplify(path));
6671 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6673 icon = [UIImage applicationImageNamed:@"unknown.png"];
6674 [self _returnPNGWithImage:icon forRequest:request];
6676 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6680 - (void) stopLoading {
6686 /* Sections Controller {{{ */
6687 @interface SectionsController : CYViewController <
6688 UITableViewDataSource,
6691 _transient Database *database_;
6692 NSMutableArray *sections_;
6693 NSMutableArray *filtered_;
6699 - (id) initWithDatabase:(Database *)database;
6700 - (void) reloadData;
6703 - (void) editButtonClicked;
6707 @implementation SectionsController
6710 [list_ setDataSource:nil];
6711 [list_ setDelegate:nil];
6713 [sections_ release];
6714 [filtered_ release];
6716 [accessory_ release];
6720 - (void) viewDidAppear:(BOOL)animated {
6721 [super viewDidAppear:animated];
6722 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6725 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6726 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6730 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6731 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6734 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6738 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6739 static NSString *reuseIdentifier = @"SectionCell";
6741 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6742 if (cell == nil) cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6743 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6748 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6752 Section *section = [self sectionAtIndexPath:indexPath];
6753 NSString *name = [section name];
6756 if ([indexPath row] == 0) {
6759 title = UCLocalize("ALL_PACKAGES");
6762 name = [NSString stringWithString:name];
6763 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6766 title = UCLocalize("NO_SECTION");
6770 FilteredPackageController *table = [[[FilteredPackageController alloc]
6771 initWithDatabase:database_
6773 filter:@selector(isVisibleInSection:)
6777 [table setDelegate:delegate_];
6779 [[self navigationController] pushViewController:table animated:YES];
6782 - (NSString *) title { return UCLocalize("SECTIONS"); }
6784 - (id) initWithDatabase:(Database *)database {
6785 if ((self = [super init]) != nil) {
6786 database_ = database;
6788 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6790 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6791 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6793 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6794 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6795 [list_ setRowHeight:45.0f];
6796 [[self view] addSubview:list_];
6798 [list_ setDataSource:self];
6799 [list_ setDelegate:self];
6805 - (void) reloadData {
6806 NSArray *packages = [database_ packages];
6808 [sections_ removeAllObjects];
6809 [filtered_ removeAllObjects];
6812 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6813 SectionMap sections;
6814 sections.resize(64);
6816 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6820 for (Package *package in packages) {
6821 NSString *name([package section]);
6822 NSString *key(name == nil ? @"" : name);
6827 _profile(SectionsView$reloadData$Section)
6828 section = §ions[key];
6829 if (*section == nil) {
6830 _profile(SectionsView$reloadData$Section$Allocate)
6831 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6836 [*section addToCount];
6838 _profile(SectionsView$reloadData$Filter)
6839 if (![package valid] || ![package visible])
6843 [*section addToRow];
6847 _profile(SectionsView$reloadData$Section)
6848 section = [sections objectForKey:key];
6849 if (section == nil) {
6850 _profile(SectionsView$reloadData$Section$Allocate)
6851 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6852 [sections setObject:section forKey:key];
6857 [section addToCount];
6859 _profile(SectionsView$reloadData$Filter)
6860 if (![package valid] || ![package visible])
6870 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6871 [sections_ addObject:i->second];
6873 [sections_ addObjectsFromArray:[sections allValues]];
6876 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6878 for (Section *section in sections_) {
6879 size_t count([section row]);
6883 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6884 [section setCount:count];
6885 [filtered_ addObject:section];
6888 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6889 initWithTitle:[sections_ count] == 0 ? nil : UCLocalize("EDIT")
6890 style:UIBarButtonItemStylePlain
6892 action:@selector(editButtonClicked)
6894 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] != nil];
6895 [rightItem release];
6901 - (void) resetView {
6903 [self editButtonClicked];
6906 - (void) editButtonClicked {
6907 if ((editing_ = !editing_))
6910 [delegate_ updateData];
6912 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6913 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6914 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6917 - (UIView *) accessoryView {
6923 /* Changes Controller {{{ */
6924 @interface ChangesController : CYViewController <
6925 UITableViewDataSource,
6928 _transient Database *database_;
6929 CFMutableArrayRef packages_;
6930 NSMutableArray *sections_;
6933 BOOL hasSentFirstLoad_;
6936 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6937 - (void) reloadData;
6941 @implementation ChangesController
6944 [list_ setDelegate:nil];
6945 [list_ setDataSource:nil];
6947 CFRelease(packages_);
6949 [sections_ release];
6954 - (void) viewDidAppear:(BOOL)animated {
6955 [super viewDidAppear:animated];
6956 if (!hasSentFirstLoad_) {
6957 hasSentFirstLoad_ = YES;
6958 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6960 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6964 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6965 NSInteger count([sections_ count]);
6966 return count == 0 ? 1 : count;
6969 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6970 if ([sections_ count] == 0)
6972 return [[sections_ objectAtIndex:section] name];
6975 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6976 if ([sections_ count] == 0)
6978 return [[sections_ objectAtIndex:section] count];
6981 - (Package *) packageAtIndex:(NSUInteger)index {
6982 return (Package *) CFArrayGetValueAtIndex(packages_, index);
6985 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6986 Section *section([sections_ objectAtIndex:[path section]]);
6987 NSInteger row([path row]);
6988 return [self packageAtIndex:([section row] + row)];
6991 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6992 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6994 cell = [[[PackageCell alloc] init] autorelease];
6995 [cell setPackage:[self packageAtIndexPath:path]];
6999 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7000 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7003 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7004 Package *package([self packageAtIndexPath:path]);
7005 PackageController *view([delegate_ packageController]);
7006 [view setDelegate:delegate_];
7007 [view setPackage:package];
7008 [[self navigationController] pushViewController:view animated:YES];
7012 - (void) refreshButtonClicked {
7013 [delegate_ beginUpdate];
7014 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7017 - (void) upgradeButtonClicked {
7018 [delegate_ distUpgrade];
7021 - (NSString *) title { return UCLocalize("CHANGES"); }
7023 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7024 if ((self = [super init]) != nil) {
7025 database_ = database;
7026 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7028 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7030 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7032 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7033 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7034 [list_ setRowHeight:73.0f];
7035 [[self view] addSubview:list_];
7037 [list_ setDataSource:self];
7038 [list_ setDelegate:self];
7040 delegate_ = delegate;
7044 - (void) _reloadPackages:(NSArray *)packages {
7046 for (Package *package in packages)
7048 [package uninstalled] && [package valid] && [package visible] ||
7049 [package upgradableAndEssential:YES]
7051 CFArrayAppendValue(packages_, package);
7054 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7058 - (void) reloadData {
7059 NSArray *packages = [database_ packages];
7061 CFArrayRemoveAllValues(packages_);
7063 [sections_ removeAllObjects];
7066 UIProgressHUD *hud([delegate_ addProgressHUD]);
7068 [hud setText:@"Loading Changes"];
7069 //NSLog(@"HUD:%@::%@", delegate_, hud);
7070 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7071 [delegate_ removeProgressHUD:hud];
7073 [self _reloadPackages:packages];
7076 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7077 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7078 Section *section = nil;
7082 bool unseens = false;
7084 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7086 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7087 Package *package = [self packageAtIndex:offset];
7089 BOOL uae = [package upgradableAndEssential:YES];
7095 _profile(ChangesController$reloadData$Remember)
7096 seen = [package seen];
7099 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7104 name = UCLocalize("UNKNOWN");
7106 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7110 _profile(ChangesController$reloadData$Allocate)
7111 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7112 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7113 [sections_ addObject:section];
7117 [section addToCount];
7118 } else if ([package ignored])
7119 [ignored addToCount];
7122 [upgradable addToCount];
7127 CFRelease(formatter);
7130 Section *last = [sections_ lastObject];
7131 size_t count = [last count];
7132 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7133 [sections_ removeLastObject];
7136 if ([ignored count] != 0)
7137 [sections_ insertObject:ignored atIndex:0];
7139 [sections_ insertObject:upgradable atIndex:0];
7143 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7144 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7145 style:UIBarButtonItemStylePlain
7147 action:@selector(upgradeButtonClicked)
7149 if (upgrades_ > 0) [[self navigationItem] setRightBarButtonItem:rightItem];
7150 [rightItem release];
7152 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
7153 initWithTitle:UCLocalize("REFRESH")
7154 style:UIBarButtonItemStylePlain
7156 action:@selector(refreshButtonClicked)
7158 if (![delegate_ updating]) [[self navigationItem] setLeftBarButtonItem:leftItem];
7164 /* Search Controller {{{ */
7165 @interface SearchController : FilteredPackageController <
7168 UISearchBar *search_;
7171 - (id) initWithDatabase:(Database *)database;
7172 - (void) reloadData;
7176 @implementation SearchController
7183 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7184 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7185 [search_ resignFirstResponder];
7189 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7190 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7194 - (NSString *) title { return nil; }
7196 - (id) initWithDatabase:(Database *)database {
7197 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7200 - (void)viewDidAppear:(BOOL)animated {
7201 [super viewDidAppear:animated];
7203 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7204 [search_ layoutSubviews];
7205 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7206 UITextField *textField = [search_ searchField];
7207 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7208 [search_ setDelegate:self];
7209 [textField setEnablesReturnKeyAutomatically:NO];
7210 [[self navigationItem] setTitleView:textField];
7214 - (void) _reloadData {
7217 - (void) reloadData {
7218 _profile(SearchController$reloadData)
7219 [packages_ reloadData];
7222 [packages_ resetCursor];
7225 - (void) didSelectPackage:(Package *)package {
7226 [search_ resignFirstResponder];
7227 [super didSelectPackage:package];
7232 /* Settings Controller {{{ */
7233 @interface SettingsController : CYViewController <
7234 UITableViewDataSource,
7237 _transient Database *database_;
7240 UITableView *table_;
7241 id subscribedSwitch_;
7243 UITableViewCell *subscribedCell_;
7244 UITableViewCell *ignoredCell_;
7247 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7251 @implementation SettingsController
7255 if (package_ != nil)
7258 [subscribedSwitch_ release];
7259 [ignoredSwitch_ release];
7260 [subscribedCell_ release];
7261 [ignoredCell_ release];
7266 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7267 if (package_ == nil)
7273 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7274 if (package_ == nil)
7280 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7281 return UCLocalize("SHOW_ALL_CHANGES_EX");
7284 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7285 if (package_ == nil)
7288 NSMutableDictionary *metadata([package_ metadata]);
7291 if (NSNumber *number = [metadata objectForKey:key])
7292 before = [number boolValue];
7296 if (value != before) {
7297 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7299 [delegate_ updateData];
7303 - (void) onSubscribed:(id)control {
7304 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7307 - (void) onIgnored:(id)control {
7308 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
7311 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7312 if (package_ == nil)
7315 switch ([indexPath row]) {
7316 case 0: return subscribedCell_;
7317 case 1: return ignoredCell_;
7325 - (NSString *) title { return UCLocalize("SETTINGS"); }
7327 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7328 if ((self = [super init])) {
7329 database_ = database;
7330 name_ = [package retain];
7332 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7334 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7335 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7336 [[self view] addSubview:table_];
7338 subscribedSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7339 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7340 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7342 ignoredSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7343 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7344 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7346 subscribedCell_ = [[UITableViewCell alloc] init];
7347 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7348 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7349 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7351 ignoredCell_ = [[UITableViewCell alloc] init];
7352 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7353 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7354 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7356 [table_ setDataSource:self];
7357 [table_ setDelegate:self];
7362 - (void) reloadData {
7363 if (package_ != nil)
7364 [package_ autorelease];
7365 package_ = [database_ packageWithName:name_];
7366 if (package_ != nil) {
7368 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7369 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7372 [table_ reloadData];
7377 /* Signature Controller {{{ */
7378 @interface SignatureController : CYBrowserController {
7379 _transient Database *database_;
7383 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7387 @implementation SignatureController
7394 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7396 [super webView:view didClearWindowObject:window forFrame:frame];
7399 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7400 if ((self = [super init]) != nil) {
7401 database_ = database;
7402 package_ = [package retain];
7407 - (void) reloadData {
7408 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7414 /* Role Controller {{{ */
7415 @interface RoleController : CYViewController <
7416 UITableViewDataSource,
7419 _transient Database *database_;
7421 UITableView *table_;
7422 UISegmentedControl *segment_;
7426 - (void) showDoneButton;
7427 - (void) resizeSegmentedControl;
7431 @implementation RoleController
7435 [container_ release];
7440 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7441 if ((self = [super init])) {
7442 database_ = database;
7443 roledelegate_ = delegate;
7445 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7447 NSArray *items = [NSArray arrayWithObjects:
7449 UCLocalize("HACKER"),
7450 UCLocalize("DEVELOPER"),
7452 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7453 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7454 [container_ addSubview:segment_];
7457 if ([Role_ isEqualToString:@"User"]) index = 0;
7458 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7459 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7461 [segment_ setSelectedSegmentIndex:index];
7462 [self showDoneButton];
7465 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7466 [self resizeSegmentedControl];
7468 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7469 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7470 [table_ setDelegate:self];
7471 [table_ setDataSource:self];
7472 [[self view] addSubview:table_];
7473 [table_ reloadData];
7477 - (void) resizeSegmentedControl {
7478 CGFloat width = [[self view] frame].size.width;
7479 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7482 - (void) viewWillAppear:(BOOL)animated {
7483 [super viewWillAppear:animated];
7485 [self resizeSegmentedControl];
7488 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7489 [self resizeSegmentedControl];
7492 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7493 [self resizeSegmentedControl];
7497 NSString *role(nil);
7499 switch ([segment_ selectedSegmentIndex]) {
7500 case 0: role = @"User"; break;
7501 case 1: role = @"Hacker"; break;
7502 case 2: role = @"Developer"; break;
7507 if (![role isEqualToString:Role_]) {
7508 bool rolling(Role_ == nil);
7511 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7515 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7520 [roledelegate_ loadData];
7522 [roledelegate_ updateData];
7526 - (void) segmentChanged:(UISegmentedControl *)control {
7527 [self showDoneButton];
7530 - (void) doneButtonClicked {
7532 [[self navigationController] dismissModalViewControllerAnimated:YES];
7535 - (void) showDoneButton {
7536 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7537 initWithTitle:UCLocalize("DONE")
7538 style:UIBarButtonItemStyleDone
7540 action:@selector(doneButtonClicked)
7542 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] == nil];
7543 [rightItem release];
7546 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7547 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7551 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7555 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7556 return nil; // This method is required by the protocol.
7559 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7561 return UCLocalize("ROLE_EX");
7563 return [NSString stringWithFormat:
7564 @"%@: %@\n%@: %@\n%@: %@",
7565 UCLocalize("USER"), UCLocalize("USER_EX"),
7566 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7567 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7572 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7573 if (section == 3) return 44.0f;
7577 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7578 if (section == 3) return container_;
7584 /* Stash Controller {{{ */
7585 @interface CYStashController : CYViewController {
7586 UIActivityIndicatorView *spinner_;
7592 @implementation CYStashController
7594 if ((self = [super init])) {
7595 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7597 spinner_ = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
7598 CGRect spinrect = [spinner_ frame];
7599 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7600 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7601 [spinner_ setFrame:spinrect];
7602 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7603 [[self view] addSubview:spinner_];
7605 [spinner_ startAnimating];
7608 captrect.size.width = [[self view] frame].size.width;
7609 captrect.size.height = 40.0f;
7610 captrect.origin.x = 0;
7611 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7612 caption_ = [[UILabel alloc] initWithFrame:captrect];
7613 [caption_ setText:@"Initializing Filesystem"];
7614 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7615 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7616 [caption_ setTextColor:[UIColor whiteColor]];
7617 [caption_ setBackgroundColor:[UIColor clearColor]];
7618 [caption_ setShadowColor:[UIColor blackColor]];
7619 [caption_ setTextAlignment:UITextAlignmentCenter];
7620 [[self view] addSubview:caption_];
7624 statusrect.size.width = [[self view] frame].size.width;
7625 statusrect.size.height = 30.0f;
7626 statusrect.origin.x = 0;
7627 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7628 status_ = [[UILabel alloc] initWithFrame:statusrect];
7629 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7630 [status_ setText:@"(Cydia will exit when complete.)"];
7631 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7632 [status_ setTextColor:[UIColor whiteColor]];
7633 [status_ setBackgroundColor:[UIColor clearColor]];
7634 [status_ setShadowColor:[UIColor blackColor]];
7635 [status_ setTextAlignment:UITextAlignmentCenter];
7636 [[self view] addSubview:status_];
7641 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7642 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7647 /* Cydia Container {{{ */
7648 @interface CYContainer : UIViewController <ProgressDelegate> {
7649 _transient Database *database_;
7650 RefreshBar *refreshbar_;
7655 UITabBarController *root_;
7658 - (void) setTabBarController:(UITabBarController *)controller;
7660 - (void) dropBar:(BOOL)animated;
7661 - (void) beginUpdate;
7662 - (void) raiseBar:(BOOL)animated;
7667 @implementation CYContainer
7669 - (BOOL) _reallyWantsFullScreenLayout {
7673 // NOTE: UIWindow only sends the top controller these messages,
7674 // So we have to forward them on.
7676 - (void) viewDidAppear:(BOOL)animated {
7677 [super viewDidAppear:animated];
7678 [root_ viewDidAppear:animated];
7681 - (void) viewWillAppear:(BOOL)animated {
7682 [super viewWillAppear:animated];
7683 [root_ viewWillAppear:animated];
7686 - (void) viewDidDisappear:(BOOL)animated {
7687 [super viewDidDisappear:animated];
7688 [root_ viewDidDisappear:animated];
7691 - (void) viewWillDisappear:(BOOL)animated {
7692 [super viewWillDisappear:animated];
7693 [root_ viewWillDisappear:animated];
7696 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7697 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7700 - (void) setTabBarController:(UITabBarController *)controller {
7702 [[self view] addSubview:[root_ view]];
7705 - (void) setUpdate:(NSDate *)date {
7709 - (void) beginUpdate {
7711 [refreshbar_ start];
7716 detachNewThreadSelector:@selector(performUpdate)
7722 - (void) performUpdate { _pooled
7724 status.setDelegate(self);
7725 [database_ updateWithStatus:status];
7728 performSelectorOnMainThread:@selector(completeUpdate)
7734 - (void) completeUpdate {
7735 if (!updating_) return;
7738 [self raiseBar:YES];
7740 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7743 - (void) cancelUpdate {
7745 [self raiseBar:YES];
7747 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7750 - (void) cancelPressed {
7751 [self cancelUpdate];
7758 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7759 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7762 - (void) startProgress {
7765 - (void) setProgressTitle:(NSString *)title {
7767 performSelectorOnMainThread:@selector(_setProgressTitle:)
7773 - (bool) isCancelling:(size_t)received {
7777 - (void) setProgressPercent:(float)percent {
7779 performSelectorOnMainThread:@selector(_setProgressPercent:)
7780 withObject:[NSNumber numberWithFloat:percent]
7785 - (void) addProgressOutput:(NSString *)output {
7787 performSelectorOnMainThread:@selector(_addProgressOutput:)
7793 - (void) _setProgressTitle:(NSString *)title {
7794 [refreshbar_ setPrompt:title];
7797 - (void) _setProgressPercent:(NSNumber *)percent {
7798 [refreshbar_ setProgress:[percent floatValue]];
7801 - (void) _addProgressOutput:(NSString *)output {
7804 - (void) setUpdateDelegate:(id)delegate {
7805 updatedelegate_ = delegate;
7808 - (CGFloat) statusBarHeight {
7809 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7810 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7812 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7816 - (void) dropBar:(BOOL)animated {
7817 if (dropped_) return;
7820 [[self view] addSubview:refreshbar_];
7822 CGFloat sboffset = [self statusBarHeight];
7824 CGRect barframe = [refreshbar_ frame];
7825 barframe.origin.y = sboffset;
7826 [refreshbar_ setFrame:barframe];
7828 if (animated) [UIView beginAnimations:nil context:NULL];
7829 CGRect viewframe = [[root_ view] frame];
7830 viewframe.origin.y += barframe.size.height + sboffset;
7831 viewframe.size.height -= barframe.size.height + sboffset;
7832 [[root_ view] setFrame:viewframe];
7833 if (animated) [UIView commitAnimations];
7835 // Ensure bar has the proper width for our view, it might have changed
7836 barframe.size.width = viewframe.size.width;
7837 [refreshbar_ setFrame:barframe];
7839 // XXX: fix Apple's layout bug
7840 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7843 - (void) raiseBar:(BOOL)animated {
7844 if (!dropped_) return;
7847 [refreshbar_ removeFromSuperview];
7849 CGFloat sboffset = [self statusBarHeight];
7851 if (animated) [UIView beginAnimations:nil context:NULL];
7852 CGRect barframe = [refreshbar_ frame];
7853 CGRect viewframe = [[root_ view] frame];
7854 viewframe.origin.y -= barframe.size.height + sboffset;
7855 viewframe.size.height += barframe.size.height + sboffset;
7856 [[root_ view] setFrame:viewframe];
7857 if (animated) [UIView commitAnimations];
7859 // XXX: fix Apple's layout bug
7860 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7863 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7864 // XXX: fix Apple's layout bug
7865 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7868 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7874 // XXX: fix Apple's layout bug
7875 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7878 - (void) statusBarFrameChanged:(NSNotification *)notification {
7886 [refreshbar_ release];
7887 [[NSNotificationCenter defaultCenter] removeObserver:self];
7891 - (id) initWithDatabase:(Database *)database {
7892 if ((self = [super init]) != nil) {
7893 database_ = database;
7895 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7896 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7898 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7915 @interface Cydia : UIApplication <
7916 ConfirmationControllerDelegate,
7917 ProgressControllerDelegate,
7919 UINavigationControllerDelegate
7922 CYContainer *container_;
7925 NSMutableArray *essential_;
7926 NSMutableArray *broken_;
7928 Database *database_;
7932 UIKeyboard *keyboard_;
7933 UIProgressHUD *hud_;
7935 SectionsController *sections_;
7936 ChangesController *changes_;
7937 ManageController *manage_;
7938 SearchController *search_;
7939 SourceTable *sources_;
7940 InstalledController *installed_;
7943 CYStashController *stash_;
7948 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7949 - (void) setPage:(CYViewController *)page;
7954 static _finline void _setHomePage(Cydia *self) {
7955 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7958 @implementation Cydia
7960 - (void) beginUpdate {
7961 [container_ beginUpdate];
7965 return [container_ updating];
7968 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7973 if ([broken_ count] != 0) {
7974 int count = [broken_ count];
7976 UIAlertView *alert = [[[UIAlertView alloc]
7977 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7978 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7980 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7981 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
7984 [alert setContext:@"fixhalf"];
7986 } else if (!Ignored_ && [essential_ count] != 0) {
7987 int count = [essential_ count];
7989 UIAlertView *alert = [[[UIAlertView alloc]
7990 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7991 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
7993 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
7994 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
7997 [alert setContext:@"upgrade"];
8002 - (void) _saveConfig {
8005 NSString *error(nil);
8006 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8008 NSError *error(nil);
8009 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8010 NSLog(@"failure to save metadata data: %@", error);
8013 NSLog(@"failure to serialize metadata: %@", error);
8021 - (void) _updateData {
8024 /* XXX: this is just stupid */
8025 if (tag_ != 1 && sections_ != nil)
8026 [sections_ reloadData];
8027 if (tag_ != 2 && changes_ != nil)
8028 [changes_ reloadData];
8029 if (tag_ != 4 && search_ != nil)
8030 [search_ reloadData];
8032 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8035 - (int)indexOfTabWithTag:(int)tag {
8037 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8038 if ([[controller tabBarItem] tag] == tag) return i;
8045 - (void) _refreshIfPossible {
8046 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8048 bool recently = false;
8049 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8050 if (update != nil) {
8051 NSTimeInterval interval([update timeIntervalSinceNow]);
8052 if (interval <= 0 && interval > -(15*60))
8056 // Don't automatic refresh if:
8057 // - We already refreshed recently.
8058 // - We already auto-refreshed this launch.
8059 // - Auto-refresh is disabled.
8060 if (recently || loaded_ || ManualRefresh) {
8061 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8063 // If we are cancelling due to ManualRefresh or a recent refresh
8064 // we need to make sure it knows it's already loaded.
8068 // We are going to load, so remember that.
8072 SCNetworkReachabilityFlags flags; {
8073 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8074 SCNetworkReachabilityGetFlags(reachability, &flags);
8075 CFRelease(reachability);
8078 // XXX: this elaborate mess is what Apple is using to determine this? :(
8079 // XXX: do we care if the user has to intervene? maybe that's ok?
8081 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8082 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8083 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8084 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8085 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8086 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8090 // If we can reach the server, auto-refresh!
8092 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8097 - (void) refreshIfPossible {
8098 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8101 - (void) _reloadData {
8102 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8103 [hud setText:UCLocalize("RELOADING_DATA")];
8105 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8107 if (hud) [self removeProgressHUD:hud];
8111 [essential_ removeAllObjects];
8112 [broken_ removeAllObjects];
8114 NSArray *packages([database_ packages]);
8115 for (Package *package in packages) {
8117 [broken_ addObject:package];
8118 if ([package upgradableAndEssential:NO]) {
8119 if ([package essential])
8120 [essential_ addObject:package];
8125 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8127 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8128 [changesItem setBadgeValue:badge];
8129 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8131 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8132 [self setApplicationBadge:badge];
8134 [self setApplicationBadgeString:badge];
8136 [changesItem setBadgeValue:nil];
8137 [changesItem setAnimatedBadge:NO];
8139 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8140 [self removeApplicationBadge];
8141 else // XXX: maybe use setApplicationBadgeString also?
8142 [self setApplicationIconBadgeNumber:0];
8147 [self refreshIfPossible];
8150 - (void) updateData {
8151 [database_ setVisible];
8160 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8161 _assert(file != NULL);
8163 for (NSString *key in [Sources_ allKeys]) {
8164 NSDictionary *source([Sources_ objectForKey:key]);
8166 fprintf(file, "%s %s %s\n",
8167 [[source objectForKey:@"Type"] UTF8String],
8168 [[source objectForKey:@"URI"] UTF8String],
8169 [[source objectForKey:@"Distribution"] UTF8String]
8177 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8178 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8179 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8180 [container_ presentModalViewController:navigation animated:YES];
8183 detachNewThreadSelector:@selector(update_)
8186 title:UCLocalize("UPDATING_SOURCES")
8190 - (void) reloadData {
8191 @synchronized (self) {
8197 pkgProblemResolver *resolver = [database_ resolver];
8199 resolver->InstallProtect();
8200 if (!resolver->Resolve(true))
8204 - (CGRect) popUpBounds {
8205 return [[tabbar_ view] bounds];
8209 if (![database_ prepare])
8212 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8213 [page setDelegate:self];
8214 CYNavigationController *confirm_ = [[CYNavigationController alloc] initWithRootViewController:page];
8215 [confirm_ setDelegate:self];
8217 if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8218 [container_ presentModalViewController:confirm_ animated:YES];
8224 @synchronized (self) {
8229 - (void) clearPackage:(Package *)package {
8230 @synchronized (self) {
8237 - (void) installPackages:(NSArray *)packages {
8238 @synchronized (self) {
8239 for (Package *package in packages)
8246 - (void) installPackage:(Package *)package {
8247 @synchronized (self) {
8254 - (void) removePackage:(Package *)package {
8255 @synchronized (self) {
8262 - (void) distUpgrade {
8263 @synchronized (self) {
8264 if (![database_ upgrade])
8271 @synchronized (self) {
8276 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8277 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8279 if (navigation != nil) {
8280 [navigation pushViewController:progress animated:YES];
8282 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8283 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8284 [container_ presentModalViewController:navigation animated:YES];
8288 detachNewThreadSelector:@selector(perform)
8291 title:UCLocalize("RUNNING")
8295 - (void) progressControllerIsComplete:(ProgressController *)progress {
8299 - (void) setPage:(CYViewController *)page {
8300 [page setDelegate:self];
8302 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8303 [navController setViewControllers:[NSArray arrayWithObject:page]];
8304 for (CYNavigationController *page in [tabbar_ viewControllers]) {
8305 if (page != navController) [page setViewControllers:nil];
8309 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8310 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8311 [browser loadURL:url];
8315 - (SectionsController *) sectionsController {
8316 if (sections_ == nil)
8317 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8321 - (ChangesController *) changesController {
8322 if (changes_ == nil)
8323 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8327 - (ManageController *) manageController {
8328 if (manage_ == nil) {
8329 manage_ = (ManageController *) [[self
8330 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8331 withClass:[ManageController class]
8333 if (!IsWildcat_) queueDelegate_ = manage_;
8338 - (SearchController *) searchController {
8340 search_ = [[SearchController alloc] initWithDatabase:database_];
8344 - (SourceTable *) sourcesController {
8345 if (sources_ == nil)
8346 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8350 - (InstalledController *) installedController {
8351 if (installed_ == nil) {
8352 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8353 if (IsWildcat_) queueDelegate_ = installed_;
8358 - (void) tabBarController:(id)tabBarController didSelectViewController:(UIViewController *)viewController {
8359 int tag = [[viewController tabBarItem] tag];
8361 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8363 } else if (tag_ == 1) {
8364 [[self sectionsController] resetView];
8368 case kCydiaTag: _setHomePage(self); break;
8370 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8371 case kChangesTag: [self setPage:[self changesController]]; break;
8372 case kManageTag: [self setPage:[self manageController]]; break;
8373 case kInstalledTag: [self setPage:[self installedController]]; break;
8374 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8375 case kSearchTag: [self setPage:[self searchController]]; break;
8383 - (void) showSettings {
8384 RoleController *role = [[RoleController alloc] initWithDatabase:database_ delegate:self];
8385 CYNavigationController *nav = [[CYNavigationController alloc] initWithRootViewController:role];
8386 if (IsWildcat_) [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8387 [container_ presentModalViewController:nav animated:YES];
8390 - (void) setPackageController:(PackageController *)view {
8392 [view setPackage:nil];
8396 - (PackageController *) _packageController {
8397 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8400 - (PackageController *) packageController {
8401 return [self _packageController];
8404 // Returns the navigation controller for the queuing badge.
8405 - (id) queueBadgeController {
8406 int index = [self indexOfTabWithTag:kManageTag];
8407 if (index == -1) index = [self indexOfTabWithTag:kInstalledTag];
8409 return [[tabbar_ viewControllers] objectAtIndex:index];
8412 - (void) cancelAndClear:(bool)clear {
8413 @synchronized (self) {
8416 pkgCacheFile &cache([database_ cache]);
8417 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
8418 // Unmark method taken from Synaptic Package Manager.
8419 // Thanks for being sane, unlike Aptitude.
8420 if (!cache[iterator].Keep()) {
8421 cache->MarkKeep(iterator, false);
8422 cache->SetReInstall(iterator, false);
8428 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
8432 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8435 // Show the changes in the current view.
8436 [(CYNavigationController *) [tabbar_ selectedViewController] reloadData];
8437 [queueDelegate_ queueStatusDidChange];
8441 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8442 NSString *context([alert context]);
8444 if ([context isEqualToString:@"fixhalf"]) {
8445 if (button == [alert firstOtherButtonIndex]) {
8446 @synchronized (self) {
8447 for (Package *broken in broken_) {
8450 NSString *id = [broken id];
8451 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8452 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8453 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8454 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8460 } else if (button == [alert cancelButtonIndex]) {
8461 [broken_ removeAllObjects];
8465 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8466 } else if ([context isEqualToString:@"upgrade"]) {
8467 if (button == [alert firstOtherButtonIndex]) {
8468 @synchronized (self) {
8469 for (Package *essential in essential_)
8470 [essential install];
8475 } else if (button == [alert firstOtherButtonIndex] + 1) {
8477 } else if (button == [alert cancelButtonIndex]) {
8481 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8485 - (void) system:(NSString *)command { _pooled
8486 system([command UTF8String]);
8489 - (void) applicationWillSuspend {
8491 [super applicationWillSuspend];
8494 - (void) applicationSuspend:(__GSEvent *)event {
8495 // Use external process status API internally.
8496 // This is probably a really bad idea.
8497 uint64_t status = 0;
8499 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8500 notify_get_state(notify_token, &status);
8501 notify_cancel(notify_token);
8504 if (hud_ == nil && status == 0)
8505 [super applicationSuspend:event];
8508 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8510 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8513 - (void) _setSuspended:(BOOL)value {
8515 [super _setSuspended:value];
8518 - (UIProgressHUD *) addProgressHUD {
8519 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8520 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8522 [window_ setUserInteractionEnabled:NO];
8525 UIViewController *target = container_;
8526 while ([target modalViewController] != nil) target = [target modalViewController];
8527 [[target view] addSubview:hud];
8532 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8534 [hud removeFromSuperview];
8535 [window_ setUserInteractionEnabled:YES];
8538 - (CYViewController *) pageForPackage:(NSString *)name {
8539 if (Package *package = [database_ packageWithName:name]) {
8540 PackageController *view([self packageController]);
8541 [view setPackage:package];
8544 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8545 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8546 return [self _pageForURL:url withClass:[CYBrowserController class]];
8550 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8554 NSString *href([url absoluteString]);
8555 if ([href hasPrefix:@"apptapp://package/"])
8556 return [self pageForPackage:[href substringFromIndex:18]];
8558 NSString *scheme([[url scheme] lowercaseString]);
8559 if (![scheme isEqualToString:@"cydia"])
8561 NSString *path([url absoluteString]);
8562 if ([path length] < 8)
8564 path = [path substringFromIndex:8];
8565 if (![path hasPrefix:@"/"])
8566 path = [@"/" stringByAppendingString:path];
8568 if ([path isEqualToString:@"/add-source"])
8569 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8570 else if ([path isEqualToString:@"/storage"])
8571 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8572 else if ([path isEqualToString:@"/sources"])
8573 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8574 else if ([path isEqualToString:@"/packages"])
8575 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8576 else if ([path hasPrefix:@"/url/"])
8577 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8578 else if ([path hasPrefix:@"/launch/"])
8579 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8580 else if ([path hasPrefix:@"/package-settings/"])
8581 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8582 else if ([path hasPrefix:@"/package-signature/"])
8583 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8584 else if ([path hasPrefix:@"/package/"])
8585 return [self pageForPackage:[path substringFromIndex:9]];
8586 else if ([path hasPrefix:@"/files/"]) {
8587 NSString *name = [path substringFromIndex:7];
8589 if (Package *package = [database_ packageWithName:name]) {
8590 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8591 [files setPackage:package];
8599 - (void) applicationOpenURL:(NSURL *)url {
8600 [super applicationOpenURL:url];
8602 if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
8603 [self setPage:page];
8605 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8609 - (void) applicationWillResignActive:(UIApplication *)application {
8610 // Stop refreshing if you get a phone call or lock the device.
8611 if ([container_ updating]) [container_ cancelUpdate];
8613 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8614 [super applicationWillResignActive:application];
8617 - (void) addStashController {
8618 stash_ = [[CYStashController alloc] init];
8619 [window_ addSubview:[stash_ view]];
8622 - (void) removeStashController {
8623 [[stash_ view] removeFromSuperview];
8628 [self setIdleTimerDisabled:YES];
8630 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8631 [self setStatusBarShowsProgress:YES];
8632 UpdateExternalStatus(1);
8634 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8636 UpdateExternalStatus(0);
8637 [self setStatusBarShowsProgress:NO];
8639 [self removeStashController];
8641 if (ExecFork() == 0) {
8642 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8643 perror("launchctl stop");
8647 - (void) setupTabBarController {
8648 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8649 [tabbar_ setDelegate:self];
8651 NSMutableArray *items([NSMutableArray arrayWithObjects:
8652 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8653 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8654 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8655 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8659 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8660 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8662 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8665 NSMutableArray *controllers([NSMutableArray array]);
8667 for (UITabBarItem *item in items) {
8668 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8669 [controller setTabBarItem:item];
8670 [controllers addObject:controller];
8673 [tabbar_ setViewControllers:controllers];
8676 - (void) applicationDidFinishLaunching:(id)unused {
8677 [CYBrowserController _initialize];
8679 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8681 Font12_ = [[UIFont systemFontOfSize:12] retain];
8682 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8683 Font14_ = [[UIFont systemFontOfSize:14] retain];
8684 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8685 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8689 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8690 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8692 UIScreen *screen([UIScreen mainScreen]);
8694 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8695 [window_ orderFront:self];
8696 [window_ makeKey:self];
8697 [window_ setHidden:NO];
8700 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8701 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8702 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8703 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8704 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8705 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8706 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8707 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8708 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8711 [self addStashController];
8712 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8716 database_ = [Database sharedInstance];
8718 [self setupTabBarController];
8720 container_ = [[CYContainer alloc] initWithDatabase:database_];
8721 [container_ setUpdateDelegate:self];
8722 [container_ setTabBarController:tabbar_];
8723 [window_ addSubview:[container_ view]];
8725 // Show pinstripes while loading data.
8726 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8728 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8735 [self showSettings];
8739 [window_ setUserInteractionEnabled:NO];
8741 UIView *container = [[UIView alloc] init];
8742 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8744 UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
8745 [spinner startAnimating];
8746 [container addSubview:spinner];
8749 UILabel *label = [[UILabel alloc] init];
8750 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8751 [label setBackgroundColor:[UIColor clearColor]];
8752 [label setTextColor:[UIColor blackColor]];
8753 [label setShadowColor:[UIColor whiteColor]];
8754 [label setShadowOffset:CGSizeMake(0, 1)];
8755 [label setText:UCLocalize("LOADING_DATA")];
8756 [container addSubview:label];
8759 CGSize viewsize = [[tabbar_ view] frame].size;
8760 CGSize spinnersize = [spinner bounds].size;
8761 CGSize textsize = [[label text] sizeWithFont:[label font]];
8762 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8764 CGRect containrect = {
8765 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8766 CGSizeMake(bothwidth, spinnersize.height)
8769 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8777 [container setFrame:containrect];
8778 [spinner setFrame:spinrect];
8779 [label setFrame:textrect];
8780 [[container_ view] addSubview:container];
8781 [container release];
8786 // Show the home page
8787 [tabbar_ setSelectedIndex:0];
8789 [window_ setUserInteractionEnabled:YES];
8791 // XXX: does this actually slow anything down?
8792 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8793 [container removeFromSuperview];
8796 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8797 if (item != nil && IsWildcat_) {
8798 [sheet showFromBarButtonItem:item animated:YES];
8800 [sheet showInView:window_];
8807 id Alloc_(id self, SEL selector) {
8808 id object = alloc_(self, selector);
8809 lprintf("[%s]A-%p\n", self->isa->name, object);
8814 id Dealloc_(id self, SEL selector) {
8815 id object = dealloc_(self, selector);
8816 lprintf("[%s]D-%p\n", self->isa->name, object);
8820 Class $WebDefaultUIKitDelegate;
8822 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8823 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8824 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8825 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8828 static NSNumber *shouldPlayKeyboardSounds;
8832 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8834 case 1104: // Keyboard Button Clicked
8835 case 1105: // Keyboard Delete Repeated
8836 if (shouldPlayKeyboardSounds == nil) {
8837 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8838 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8841 if (![shouldPlayKeyboardSounds boolValue])
8845 _UIHardware$_playSystemSound$(self, _cmd, sound);
8849 int main(int argc, char *argv[]) { _pooled
8852 if (Class $UIDevice = objc_getClass("UIDevice")) {
8853 UIDevice *device([$UIDevice currentDevice]);
8854 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8858 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8860 /* Library Hacks {{{ */
8861 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8863 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8864 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8865 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8866 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8867 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8870 $UIHardware = objc_getClass("UIHardware");
8871 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8872 if (UIHardware$_playSystemSound$ != NULL) {
8873 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8874 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8877 /* Set Locale {{{ */
8878 Locale_ = CFLocaleCopyCurrent();
8879 Languages_ = [NSLocale preferredLanguages];
8880 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8881 //NSLog(@"%@", [Languages_ description]);
8884 if (Languages_ == nil || [Languages_ count] == 0)
8885 // XXX: consider just setting to C and then falling through?
8888 lang = [[Languages_ objectAtIndex:0] UTF8String];
8889 setenv("LANG", lang, true);
8892 //std::setlocale(LC_ALL, lang);
8893 NSLog(@"Setting Language: %s", lang);
8896 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8898 /* Parse Arguments {{{ */
8899 bool substrate(false);
8905 for (int argi(1); argi != argc; ++argi)
8906 if (strcmp(argv[argi], "--") == 0) {
8908 argv[argi] = argv[0];
8914 for (int argi(1); argi != arge; ++argi)
8915 if (strcmp(args[argi], "--substrate") == 0)
8918 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8922 App_ = [[NSBundle mainBundle] bundlePath];
8923 Home_ = NSHomeDirectory();
8929 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8930 alloc_ = alloc->method_imp;
8931 alloc->method_imp = (IMP) &Alloc_;*/
8933 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8934 dealloc_ = dealloc->method_imp;
8935 dealloc->method_imp = (IMP) &Dealloc_;*/
8937 /* System Information {{{ */
8941 size = sizeof(maxproc);
8942 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8943 perror("sysctlbyname(\"kern.maxproc\", ?)");
8944 else if (maxproc < 64) {
8946 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8947 perror("sysctlbyname(\"kern.maxproc\", #)");
8950 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8951 char *osversion = new char[size];
8952 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8953 perror("sysctlbyname(\"kern.osversion\", ?)");
8955 System_ = [NSString stringWithUTF8String:osversion];
8957 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8958 char *machine = new char[size];
8959 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8960 perror("sysctlbyname(\"hw.machine\", ?)");
8964 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8965 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8966 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8967 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8971 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8972 NSData *data((NSData *) ecid);
8973 size_t length([data length]);
8974 uint8_t bytes[length];
8975 [data getBytes:bytes];
8976 char string[length * 2 + 1];
8977 for (size_t i(0); i != length; ++i)
8978 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8979 ChipID_ = [NSString stringWithUTF8String:string];
8983 IOObjectRelease(service);
8987 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8989 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
8990 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
8991 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
8993 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
8994 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
8995 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
8997 if (mcc != NULL && mnc != NULL)
8998 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9005 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9006 Build_ = [system objectForKey:@"ProductBuildVersion"];
9007 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9008 Product_ = [info objectForKey:@"SafariProductVersion"];
9009 Safari_ = [info objectForKey:@"CFBundleVersion"];
9012 /* Load Database {{{ */
9014 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9016 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9018 if (Metadata_ == NULL)
9019 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9021 Settings_ = [Metadata_ objectForKey:@"Settings"];
9023 Packages_ = [Metadata_ objectForKey:@"Packages"];
9024 Sections_ = [Metadata_ objectForKey:@"Sections"];
9025 Sources_ = [Metadata_ objectForKey:@"Sources"];
9027 Token_ = [Metadata_ objectForKey:@"Token"];
9030 if (Settings_ != nil)
9031 Role_ = [Settings_ objectForKey:@"Role"];
9033 if (Packages_ == nil) {
9034 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
9035 [Metadata_ setObject:Packages_ forKey:@"Packages"];
9038 if (Sections_ == nil) {
9039 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9040 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9043 if (Sources_ == nil) {
9044 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9045 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9049 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9051 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9052 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9053 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9054 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9055 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9056 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9058 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9060 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9061 unlink("/tmp/.cydia.fw");
9063 } else if (access("/User", F_OK) != 0 || version < 2) {
9066 system("/usr/libexec/cydia/firmware.sh");
9070 _assert([[NSFileManager defaultManager]
9071 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9072 withIntermediateDirectories:YES
9077 if (access("/tmp/cydia.chk", F_OK) == 0) {
9078 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9079 _assert(errno == ENOENT);
9080 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9081 _assert(errno == ENOENT);
9084 /* APT Initialization {{{ */
9085 _assert(pkgInitConfig(*_config));
9086 _assert(pkgInitSystem(*_config, _system));
9089 _config->Set("APT::Acquire::Translation", lang);
9091 // XXX: this timeout might be important :(
9092 //_config->Set("Acquire::http::Timeout", 15);
9094 _config->Set("Acquire::http::MaxParallel", 3);
9096 /* Color Choices {{{ */
9097 space_ = CGColorSpaceCreateDeviceRGB();
9099 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9100 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9101 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9102 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9103 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9104 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9105 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9106 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9107 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9109 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9110 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9112 /* UIKit Configuration {{{ */
9113 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9114 if ($GSFontSetUseLegacyFontMetrics != NULL)
9115 $GSFontSetUseLegacyFontMetrics(YES);
9117 // XXX: I have a feeling this was important
9118 //UIKeyboardDisableAutomaticAppearance();
9121 Colon_ = UCLocalize("COLON_DELIMITED");
9122 Error_ = UCLocalize("ERROR");
9123 Warning_ = UCLocalize("WARNING");
9126 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9128 CGColorSpaceRelease(space_);