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 static _finline const char *StripVersion_(const char *version) {
1079 const char *colon(strchr(version, ':'));
1081 version = colon + 1;
1085 NSString *LocalizeSection(NSString *section) {
1086 static Pcre title_r("^(.*?) \\((.*)\\)$");
1087 if (title_r(section)) {
1088 NSString *parent(title_r[1]);
1089 NSString *child(title_r[2]);
1091 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1092 LocalizeSection(parent),
1093 LocalizeSection(child)
1097 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1100 NSString *Simplify(NSString *title) {
1101 const char *data = [title UTF8String];
1102 size_t size = [title length];
1104 static Pcre square_r("^\\[(.*)\\]$");
1105 if (square_r(data, size))
1106 return Simplify(square_r[1]);
1108 static Pcre paren_r("^\\((.*)\\)$");
1109 if (paren_r(data, size))
1110 return Simplify(paren_r[1]);
1112 static Pcre title_r("^(.*?) \\((.*)\\)$");
1113 if (title_r(data, size))
1114 return Simplify(title_r[1]);
1120 NSString *GetLastUpdate() {
1121 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1124 return UCLocalize("NEVER_OR_UNKNOWN");
1126 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1127 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1129 CFRelease(formatter);
1131 return [(NSString *) formatted autorelease];
1134 bool isSectionVisible(NSString *section) {
1135 NSDictionary *metadata([Sections_ objectForKey:section]);
1136 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1137 return hidden == nil || ![hidden boolValue];
1142 /* Delegate Prototypes {{{ */
1146 @interface NSObject (ProgressDelegate)
1149 @protocol ProgressDelegate
1150 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1151 - (void) setProgressTitle:(NSString *)title;
1152 - (void) setProgressPercent:(float)percent;
1153 - (void) startProgress;
1154 - (void) addProgressOutput:(NSString *)output;
1155 - (bool) isCancelling:(size_t)received;
1158 @protocol ConfigurationDelegate
1159 - (void) repairWithSelector:(SEL)selector;
1160 - (void) setConfigurationData:(NSString *)data;
1163 @class PackageController;
1165 @protocol CydiaDelegate
1166 - (void) setPackageController:(PackageController *)view;
1167 - (void) clearPackage:(Package *)package;
1168 - (void) installPackage:(Package *)package;
1169 - (void) installPackages:(NSArray *)packages;
1170 - (void) removePackage:(Package *)package;
1171 - (void) beginUpdate;
1173 - (void) distUpgrade;
1175 - (void) updateData;
1177 - (void) showSettings;
1178 - (UIProgressHUD *) addProgressHUD;
1179 - (BOOL) hudIsShowing;
1180 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1181 - (CYViewController *) pageForPackage:(NSString *)name;
1182 - (PackageController *) packageController;
1183 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1187 /* Status Delegation {{{ */
1189 public pkgAcquireStatus
1192 _transient NSObject<ProgressDelegate> *delegate_;
1200 void setDelegate(id delegate) {
1201 delegate_ = delegate;
1204 NSObject<ProgressDelegate> *getDelegate() const {
1208 virtual bool MediaChange(std::string media, std::string drive) {
1212 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1215 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1216 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1217 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1220 virtual void Done(pkgAcquire::ItemDesc &item) {
1223 virtual void Fail(pkgAcquire::ItemDesc &item) {
1225 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1226 item.Owner->Status == pkgAcquire::Item::StatDone
1230 std::string &error(item.Owner->ErrorText);
1234 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1235 NSArray *fields([description componentsSeparatedByString:@" "]);
1236 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1238 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1239 withObject:[NSArray arrayWithObjects:
1240 [NSString stringWithUTF8String:error.c_str()],
1247 virtual bool Pulse(pkgAcquire *Owner) {
1248 bool value = pkgAcquireStatus::Pulse(Owner);
1251 double(CurrentBytes + CurrentItems) /
1252 double(TotalBytes + TotalItems)
1255 [delegate_ setProgressPercent:percent];
1256 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1259 virtual void Start() {
1260 [delegate_ startProgress];
1263 virtual void Stop() {
1267 /* Progress Delegation {{{ */
1272 _transient id<ProgressDelegate> delegate_;
1276 virtual void Update() {
1277 /*if (abs(Percent - percent_) > 2)
1278 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1282 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1283 [delegate_ setProgressPercent:(Percent / 100)];*/
1293 void setDelegate(id delegate) {
1294 delegate_ = delegate;
1297 id getDelegate() const {
1301 virtual void Done() {
1303 //[delegate_ setProgressPercent:1];
1308 /* Database Interface {{{ */
1309 typedef std::map< unsigned long, _H<Source> > SourceMap;
1311 @interface Database : NSObject {
1317 pkgCacheFile cache_;
1318 pkgDepCache::Policy *policy_;
1319 pkgRecords *records_;
1320 pkgProblemResolver *resolver_;
1321 pkgAcquire *fetcher_;
1323 SPtr<pkgPackageManager> manager_;
1324 pkgSourceList *list_;
1327 CFMutableArrayRef packages_;
1329 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1338 + (Database *) sharedInstance;
1341 - (void) _readCydia:(NSNumber *)fd;
1342 - (void) _readStatus:(NSNumber *)fd;
1343 - (void) _readOutput:(NSNumber *)fd;
1347 - (Package *) packageWithName:(NSString *)name;
1349 - (pkgCacheFile &) cache;
1350 - (pkgDepCache::Policy *) policy;
1351 - (pkgRecords *) records;
1352 - (pkgProblemResolver *) resolver;
1353 - (pkgAcquire &) fetcher;
1354 - (pkgSourceList &) list;
1355 - (NSArray *) packages;
1356 - (NSArray *) sources;
1357 - (void) reloadData;
1365 - (void) setVisible;
1367 - (void) updateWithStatus:(Status &)status;
1369 - (void) setDelegate:(id)delegate;
1370 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1373 /* Delegate Helpers {{{ */
1374 @implementation NSObject (ProgressDelegate)
1376 - (void) _setProgressErrorPackage:(NSArray *)args {
1377 [self performSelector:@selector(setProgressError:forPackage:)
1378 withObject:[args objectAtIndex:0]
1379 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1383 - (void) _setProgressErrorTitle:(NSArray *)args {
1384 [self performSelector:@selector(setProgressError:withTitle:)
1385 withObject:[args objectAtIndex:0]
1386 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1390 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1391 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1392 withObject:[NSArray arrayWithObjects:error, title, nil]
1397 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1398 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1400 [self performSelector:@selector(setProgressError:withTitle:)
1402 withObject:(package == nil ? id : [package name])
1409 /* Source Class {{{ */
1410 @interface Source : NSObject {
1411 CYString depiction_;
1412 CYString description_;
1418 CYString distribution_;
1423 NSString *authority_;
1425 CYString defaultIcon_;
1427 NSDictionary *record_;
1431 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1433 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1435 - (NSString *) depictionForPackage:(NSString *)package;
1436 - (NSString *) supportForPackage:(NSString *)package;
1438 - (NSDictionary *) record;
1442 - (NSString *) distribution;
1443 - (NSString *) type;
1445 - (NSString *) host;
1447 - (NSString *) name;
1448 - (NSString *) description;
1449 - (NSString *) label;
1450 - (NSString *) origin;
1451 - (NSString *) version;
1453 - (NSString *) defaultIcon;
1457 @implementation Source
1461 distribution_.clear();
1464 description_.clear();
1470 defaultIcon_.clear();
1472 if (record_ != nil) {
1482 if (authority_ != nil) {
1483 [authority_ release];
1489 // XXX: this is a very inefficient way to call these deconstructors
1494 + (NSArray *) _attributeKeys {
1495 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1498 - (NSArray *) attributeKeys {
1499 return [[self class] _attributeKeys];
1502 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1503 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1506 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1509 trusted_ = index->IsTrusted();
1511 uri_.set(pool, index->GetURI());
1512 distribution_.set(pool, index->GetDist());
1513 type_.set(pool, index->GetType());
1515 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1516 if (dindex != NULL) {
1518 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1521 pkgTagFile tags(&fd);
1523 pkgTagSection section;
1530 {"default-icon", &defaultIcon_},
1531 {"depiction", &depiction_},
1532 {"description", &description_},
1534 {"origin", &origin_},
1535 {"support", &support_},
1536 {"version", &version_},
1539 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1540 const char *start, *end;
1542 if (section.Find(names[i].name_, start, end)) {
1543 CYString &value(*names[i].value_);
1544 value.set(pool, start, end - start);
1550 record_ = [Sources_ objectForKey:[self key]];
1552 record_ = [record_ retain];
1554 NSURL *url([NSURL URLWithString:uri_]);
1558 host_ = [[host_ lowercaseString] retain];
1563 authority_ = [url path];
1565 if (authority_ != nil)
1566 authority_ = [authority_ retain];
1569 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1570 if ((self = [super init]) != nil) {
1571 [self setMetaIndex:index inPool:pool];
1575 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1576 NSDictionary *lhr = [self record];
1577 NSDictionary *rhr = [source record];
1580 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1582 NSString *lhs = [self name];
1583 NSString *rhs = [source name];
1585 if ([lhs length] != 0 && [rhs length] != 0) {
1586 unichar lhc = [lhs characterAtIndex:0];
1587 unichar rhc = [rhs characterAtIndex:0];
1589 if (isalpha(lhc) && !isalpha(rhc))
1590 return NSOrderedAscending;
1591 else if (!isalpha(lhc) && isalpha(rhc))
1592 return NSOrderedDescending;
1595 return [lhs compare:rhs options:LaxCompareOptions_];
1598 - (NSString *) depictionForPackage:(NSString *)package {
1599 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1602 - (NSString *) supportForPackage:(NSString *)package {
1603 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1606 - (NSDictionary *) record {
1614 - (NSString *) uri {
1618 - (NSString *) distribution {
1619 return distribution_;
1622 - (NSString *) type {
1626 - (NSString *) key {
1627 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1630 - (NSString *) host {
1634 - (NSString *) name {
1635 return origin_.empty() ? authority_ : origin_;
1638 - (NSString *) description {
1639 return description_;
1642 - (NSString *) label {
1643 return label_.empty() ? authority_ : label_;
1646 - (NSString *) origin {
1650 - (NSString *) version {
1654 - (NSString *) defaultIcon {
1655 return defaultIcon_;
1660 /* Relationship Class {{{ */
1661 @interface Relationship : NSObject {
1666 - (NSString *) type;
1668 - (NSString *) name;
1672 @implementation Relationship
1680 - (NSString *) type {
1688 - (NSString *) name {
1695 /* Package Class {{{ */
1696 @interface Package : NSObject {
1700 pkgCache::VerIterator version_;
1701 pkgCache::PkgIterator iterator_;
1702 _transient Database *database_;
1703 pkgCache::VerFileIterator file_;
1709 _transient NSString *section$_;
1716 CYString installed_;
1722 CYString depiction_;
1733 NSMutableArray *tags_;
1736 NSMutableDictionary *metadata_;
1737 _transient NSDate *firstSeen_;
1738 _transient NSDate *lastSeen_;
1742 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1743 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1745 - (pkgCache::PkgIterator) iterator;
1748 - (NSString *) section;
1749 - (NSString *) simpleSection;
1751 - (NSString *) longSection;
1752 - (NSString *) shortSection;
1756 - (Address *) maintainer;
1758 - (NSString *) longDescription;
1759 - (NSString *) shortDescription;
1762 - (NSMutableDictionary *) metadata;
1764 - (BOOL) subscribed;
1767 - (NSString *) latest;
1768 - (NSString *) installed;
1769 - (BOOL) uninstalled;
1772 - (BOOL) upgradableAndEssential:(BOOL)essential;
1775 - (BOOL) unfiltered;
1779 - (BOOL) halfConfigured;
1780 - (BOOL) halfInstalled;
1782 - (NSString *) mode;
1784 - (void) setVisible;
1787 - (NSString *) name;
1789 - (NSString *) homepage;
1790 - (NSString *) depiction;
1791 - (Address *) author;
1793 - (NSString *) support;
1795 - (NSArray *) files;
1796 - (NSArray *) warnings;
1797 - (NSArray *) applications;
1799 - (Source *) source;
1800 - (NSString *) role;
1802 - (BOOL) matches:(NSString *)text;
1804 - (bool) hasSupportingRole;
1805 - (BOOL) hasTag:(NSString *)tag;
1806 - (NSString *) primaryPurpose;
1807 - (NSArray *) purposes;
1808 - (bool) isCommercial;
1810 - (CYString &) cyname;
1812 - (uint32_t) compareBySection:(NSArray *)sections;
1814 - (uint32_t) compareForChanges;
1819 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1820 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1821 - (bool) isInstalledAndVisible:(NSNumber *)number;
1822 - (bool) isVisibleInSection:(NSString *)section;
1823 - (bool) isVisibleInSource:(Source *)source;
1827 uint32_t PackageChangesRadix(Package *self, void *) {
1832 uint32_t timestamp : 30;
1833 uint32_t ignored : 1;
1834 uint32_t upgradable : 1;
1838 bool upgradable([self upgradableAndEssential:YES]);
1839 value.bits.upgradable = upgradable ? 1 : 0;
1842 value.bits.timestamp = 0;
1843 value.bits.ignored = [self ignored] ? 0 : 1;
1844 value.bits.upgradable = 1;
1846 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1847 value.bits.ignored = 0;
1848 value.bits.upgradable = 0;
1851 return _not(uint32_t) - value.key;
1854 _finline static void Stifle(uint8_t &value) {
1857 uint32_t PackagePrefixRadix(Package *self, void *context) {
1858 size_t offset(reinterpret_cast<size_t>(context));
1859 CYString &name([self cyname]);
1861 size_t size(name.size());
1864 char *text(name.data());
1867 if (!isdigit(text[0]))
1871 while (size != digits && isdigit(text[digits]))
1881 if (offset == 0 && zeros != 0) {
1882 memset(data, '0', zeros);
1883 memcpy(data + zeros, text, 4 - zeros);
1885 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1886 if (size <= offset - zeros)
1889 text += offset - zeros;
1890 size -= offset - zeros;
1893 memcpy(data, text, 4);
1895 memcpy(data, text, size);
1896 memset(data + size, 0, 4 - size);
1899 for (size_t i(0); i != 4; ++i)
1900 if (isalpha(data[i]))
1908 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1910 /* XXX: ntohl may be more honest */
1911 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1914 CYString &(*PackageName)(Package *self, SEL sel);
1916 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1917 _profile(PackageNameCompare)
1918 CYString &lhi(PackageName(lhs, @selector(cyname)));
1919 CYString &rhi(PackageName(rhs, @selector(cyname)));
1920 CFStringRef lhn(lhi), rhn(rhi);
1923 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1924 else if (rhn == NULL)
1925 return NSOrderedDescending;
1927 _profile(PackageNameCompare$NumbersLast)
1928 if (!lhi.empty() && !rhi.empty()) {
1929 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1930 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1931 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1932 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1933 return lha ? NSOrderedAscending : NSOrderedDescending;
1937 CFIndex length = CFStringGetLength(lhn);
1939 _profile(PackageNameCompare$Compare)
1940 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1945 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1946 return PackageNameCompare(*lhs, *rhs, context);
1949 struct PackageNameOrdering :
1950 std::binary_function<Package *, Package *, bool>
1952 _finline bool operator ()(Package *lhs, Package *rhs) const {
1953 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1957 @implementation Package
1959 - (NSString *) description {
1960 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1970 if (sponsor$_ != nil)
1971 [sponsor$_ release];
1972 if (author$_ != nil)
1979 if (metadata_ != nil)
1980 [metadata_ release];
1985 + (NSString *) webScriptNameForSelector:(SEL)selector {
1986 if (selector == @selector(hasTag:))
1992 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1993 return [self webScriptNameForSelector:selector] == nil;
1996 + (NSArray *) _attributeKeys {
1997 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];
2000 - (NSArray *) attributeKeys {
2001 return [[self class] _attributeKeys];
2004 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2005 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2015 _profile(Package$parse)
2016 pkgRecords::Parser *parser;
2018 _profile(Package$parse$Lookup)
2019 parser = &[database_ records]->Lookup(file_);
2024 _profile(Package$parse$Find)
2030 {"depiction", &depiction_},
2031 {"homepage", &homepage_},
2032 {"website", &website},
2034 {"support", &support_},
2035 {"sponsor", &sponsor_},
2036 {"author", &author_},
2039 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2040 const char *start, *end;
2042 if (parser->Find(names[i].name_, start, end)) {
2043 CYString &value(*names[i].value_);
2044 _profile(Package$parse$Value)
2045 value.set(pool_, start, end - start);
2051 _profile(Package$parse$Tagline)
2052 const char *start, *end;
2053 if (parser->ShortDesc(start, end)) {
2054 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2057 while (stop != start && stop[-1] == '\r')
2059 tagline_.set(pool_, start, stop - start);
2063 _profile(Package$parse$Retain)
2064 if (homepage_.empty())
2065 homepage_ = website;
2066 if (homepage_ == depiction_)
2072 - (void) setVisible {
2073 visible_ = required_ && [self unfiltered];
2076 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2077 if ((self = [super init]) != nil) {
2078 _profile(Package$initWithVersion)
2079 era_ = [database era];
2084 _profile(Package$initWithVersion$ParentPkg)
2085 iterator_ = version.ParentPkg();
2088 database_ = database;
2090 _profile(Package$initWithVersion$Latest)
2091 const char *latest(StripVersion_(version_.VerStr()));
2092 latest_ = (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(latest), strlen(latest), kCFStringEncodingASCII, NO);
2095 pkgCache::VerIterator current;
2096 _profile(Package$initWithVersion$Versions)
2097 current = iterator_.CurrentVer();
2099 installed_.set(pool_, StripVersion_(current.VerStr()));
2101 if (!version_.end())
2102 file_ = version_.FileList();
2104 pkgCache &cache([database_ cache]);
2105 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2109 _profile(Package$initWithVersion$Name)
2110 id_.set(pool_, iterator_.Name());
2111 name_.set(pool, iterator_.Display());
2114 _profile(Package$initWithVersion$lowercaseString)
2115 char *data(id_.data());
2116 for (size_t i(0), e(id_.size()); i != e; ++i)
2117 // XXX: do not use tolower() as this is not locale-specific? :(
2123 _profile(Package$initWithVersion$Tags)
2124 pkgCache::TagIterator tag(iterator_.TagList());
2126 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2128 const char *name(tag.Name());
2129 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2130 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2131 role_ = (NSString *) CYStringCreate(name + 6);
2132 if (required_ && strncmp(name, "require::", 9) == 0 && (
2137 } while (!tag.end());
2141 bool changed(false);
2143 _profile(Package$initWithVersion$Metadata)
2144 metadata_ = [Packages_ objectForKey:id_];
2146 if (metadata_ == nil) {
2149 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2150 firstSeen_, @"FirstSeen",
2151 latest_, @"LastVersion",
2156 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2157 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2159 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2160 subscribed_ = [subscribed boolValue];
2162 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2164 if (firstSeen_ == nil) {
2165 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2166 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2170 if (version == nil) {
2171 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2173 } else if (![version isEqualToString:latest_]) {
2174 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2176 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2181 metadata_ = [metadata_ retain];
2184 [Packages_ setObject:metadata_ forKey:id_];
2189 _profile(Package$initWithVersion$Section)
2190 section_.set(pool_, iterator_.Section());
2193 _profile(Package$initWithVersion$hasTag)
2194 obsolete_ = [self hasTag:@"cydia::obsolete"];
2195 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2198 _profile(Package$initWithVersion$setVisible)
2204 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2205 pkgCache::VerIterator version;
2207 _profile(Package$packageWithIterator$GetCandidateVer)
2208 version = [database policy]->GetCandidateVer(iterator);
2214 return [[[Package alloc]
2215 initWithVersion:version
2222 - (pkgCache::PkgIterator) iterator {
2226 - (NSString *) section {
2227 if (section$_ == nil) {
2228 if (section_.empty())
2231 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2232 NSString *name(section_);
2235 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2236 if (NSString *rename = [value objectForKey:@"Rename"]) {
2245 - (NSString *) simpleSection {
2246 if (NSString *section = [self section])
2247 return Simplify(section);
2252 - (NSString *) longSection {
2253 return LocalizeSection([self section]);
2256 - (NSString *) shortSection {
2257 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2260 - (NSString *) uri {
2263 pkgIndexFile *index;
2264 pkgCache::PkgFileIterator file(file_.File());
2265 if (![database_ list].FindIndex(file, index))
2267 return [NSString stringWithUTF8String:iterator_->Path];
2268 //return [NSString stringWithUTF8String:file.Site()];
2269 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2273 - (Address *) maintainer {
2276 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2277 const std::string &maintainer(parser->Maintainer());
2278 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2282 return version_.end() ? 0 : version_->InstalledSize;
2285 - (NSString *) longDescription {
2286 @synchronized (database_) {
2287 if ([database_ era] != era_ || file_.end())
2290 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2291 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2293 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2294 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2295 if ([lines count] < 2)
2298 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2299 for (size_t i(1), e([lines count]); i != e; ++i) {
2300 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2301 [trimmed addObject:trim];
2304 return [trimmed componentsJoinedByString:@"\n"];
2307 - (NSString *) shortDescription {
2312 _profile(Package$index)
2313 CFStringRef name((CFStringRef) [self name]);
2314 if (CFStringGetLength(name) == 0)
2316 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2317 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2319 return toupper(character);
2323 - (NSMutableDictionary *) metadata {
2328 if (subscribed_ && lastSeen_ != nil)
2333 - (BOOL) subscribed {
2338 NSDictionary *metadata([self metadata]);
2339 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2340 return [ignored boolValue];
2345 - (NSString *) latest {
2349 - (NSString *) installed {
2353 - (BOOL) uninstalled {
2354 return installed_.empty();
2358 return !version_.end();
2361 - (BOOL) upgradableAndEssential:(BOOL)essential {
2362 _profile(Package$upgradableAndEssential)
2363 pkgCache::VerIterator current(iterator_.CurrentVer());
2365 return essential && essential_ && visible_;
2367 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2371 - (BOOL) essential {
2376 return [database_ cache][iterator_].InstBroken();
2379 - (BOOL) unfiltered {
2380 _profile(Package$unfiltered$obsolete)
2385 _profile(Package$unfiltered$hasSupportingRole)
2386 if (![self hasSupportingRole])
2392 _profile(Package$unfiltered$section)
2393 section = [self section];
2396 _profile(Package$unfiltered$isSectionVisible)
2397 if (section != nil && !isSectionVisible(section))
2409 unsigned char current(iterator_->CurrentState);
2410 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2413 - (BOOL) halfConfigured {
2414 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2417 - (BOOL) halfInstalled {
2418 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2422 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2423 return state.Mode != pkgDepCache::ModeKeep;
2426 - (NSString *) mode {
2427 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2429 switch (state.Mode) {
2430 case pkgDepCache::ModeDelete:
2431 if ((state.iFlags & pkgDepCache::Purge) != 0)
2435 case pkgDepCache::ModeKeep:
2436 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2437 return @"REINSTALL";
2438 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2442 case pkgDepCache::ModeInstall:
2443 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2444 return @"REINSTALL";
2445 else*/ switch (state.Status) {
2447 return @"DOWNGRADE";
2453 return @"NEW_INSTALL";
2464 - (NSString *) name {
2465 return name_.empty() ? id_ : name_;
2468 - (UIImage *) icon {
2469 NSString *section = [self simpleSection];
2473 if ([static_cast<id>(icon_) hasPrefix:@"file:///"])
2474 // XXX: correct escaping
2475 icon = [UIImage imageAtPath:[static_cast<id>(icon_) substringFromIndex:7]];
2476 if (icon == nil) if (section != nil)
2477 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2478 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2479 if ([dicon hasPrefix:@"file:///"])
2480 // XXX: correct escaping
2481 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2483 icon = [UIImage applicationImageNamed:@"unknown.png"];
2487 - (NSString *) homepage {
2491 - (NSString *) depiction {
2492 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2495 - (Address *) sponsor {
2496 if (sponsor$_ == nil) {
2497 if (sponsor_.empty())
2499 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2503 - (Address *) author {
2504 if (author$_ == nil) {
2505 if (author_.empty())
2507 author$_ = [[Address addressWithString:author_] retain];
2511 - (NSString *) support {
2512 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2515 - (NSArray *) files {
2516 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2517 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2520 fin.open([path UTF8String]);
2525 while (std::getline(fin, line))
2526 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2531 - (NSArray *) warnings {
2532 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2533 const char *name(iterator_.Name());
2535 size_t length(strlen(name));
2536 if (length < 2) invalid:
2537 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2538 else for (size_t i(0); i != length; ++i)
2540 /* XXX: technically this is not allowed */
2541 (name[i] < 'A' || name[i] > 'Z') &&
2542 (name[i] < 'a' || name[i] > 'z') &&
2543 (name[i] < '0' || name[i] > '9') &&
2544 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2547 if (strcmp(name, "cydia") != 0) {
2550 bool _private = false;
2553 bool repository = [[self section] isEqualToString:@"Repositories"];
2555 if (NSArray *files = [self files])
2556 for (NSString *file in files)
2557 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2559 else if (!user && [file isEqualToString:@"/User"])
2561 else if (!_private && [file isEqualToString:@"/private"])
2563 else if (!stash && [file isEqualToString:@"/var/stash"])
2566 /* XXX: this is not sensitive enough. only some folders are valid. */
2567 if (cydia && !repository)
2568 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2570 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2572 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2574 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2577 return [warnings count] == 0 ? nil : warnings;
2580 - (NSArray *) applications {
2581 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2583 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2585 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2586 if (NSArray *files = [self files])
2587 for (NSString *file in files)
2588 if (application_r(file)) {
2589 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2590 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2591 if ([id isEqualToString:me])
2594 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2596 display = application_r[1];
2598 NSString *bundle([file stringByDeletingLastPathComponent]);
2599 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2600 if (icon == nil || [icon length] == 0)
2602 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2604 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2605 [applications addObject:application];
2607 [application addObject:id];
2608 [application addObject:display];
2609 [application addObject:url];
2612 return [applications count] == 0 ? nil : applications;
2615 - (Source *) source {
2616 if (source_ == nil) {
2617 @synchronized (database_) {
2618 if ([database_ era] != era_ || file_.end())
2619 source_ = (Source *) [NSNull null];
2621 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2625 return source_ == (Source *) [NSNull null] ? nil : source_;
2628 - (NSString *) role {
2632 - (BOOL) matches:(NSString *)text {
2638 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2639 if (range.location != NSNotFound)
2642 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2643 if (range.location != NSNotFound)
2646 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2647 if (range.location != NSNotFound)
2653 - (bool) hasSupportingRole {
2656 if ([role_ isEqualToString:@"enduser"])
2658 if ([Role_ isEqualToString:@"User"])
2660 if ([role_ isEqualToString:@"hacker"])
2662 if ([Role_ isEqualToString:@"Hacker"])
2664 if ([role_ isEqualToString:@"developer"])
2666 if ([Role_ isEqualToString:@"Developer"])
2671 - (BOOL) hasTag:(NSString *)tag {
2672 return tags_ == nil ? NO : [tags_ containsObject:tag];
2675 - (NSString *) primaryPurpose {
2676 for (NSString *tag in tags_)
2677 if ([tag hasPrefix:@"purpose::"])
2678 return [tag substringFromIndex:9];
2682 - (NSArray *) purposes {
2683 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2684 for (NSString *tag in tags_)
2685 if ([tag hasPrefix:@"purpose::"])
2686 [purposes addObject:[tag substringFromIndex:9]];
2687 return [purposes count] == 0 ? nil : purposes;
2690 - (bool) isCommercial {
2691 return [self hasTag:@"cydia::commercial"];
2694 - (CYString &) cyname {
2695 return name_.empty() ? id_ : name_;
2698 - (uint32_t) compareBySection:(NSArray *)sections {
2699 NSString *section([self section]);
2700 for (size_t i(0), e([sections count]); i != e; ++i) {
2701 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2705 return _not(uint32_t);
2708 - (uint32_t) compareForChanges {
2713 uint32_t timestamp : 30;
2714 uint32_t ignored : 1;
2715 uint32_t upgradable : 1;
2719 bool upgradable([self upgradableAndEssential:YES]);
2720 value.bits.upgradable = upgradable ? 1 : 0;
2723 value.bits.timestamp = 0;
2724 value.bits.ignored = [self ignored] ? 0 : 1;
2725 value.bits.upgradable = 1;
2727 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2728 value.bits.ignored = 0;
2729 value.bits.upgradable = 0;
2732 return _not(uint32_t) - value.key;
2736 @synchronized (database_) {
2737 pkgProblemResolver *resolver = [database_ resolver];
2738 resolver->Clear(iterator_);
2740 pkgCacheFile &cache([database_ cache]);
2741 cache->SetReInstall(iterator_, false);
2742 cache->MarkKeep(iterator_, false);
2746 @synchronized (database_) {
2747 pkgProblemResolver *resolver = [database_ resolver];
2748 resolver->Clear(iterator_);
2749 resolver->Protect(iterator_);
2751 pkgCacheFile &cache([database_ cache]);
2752 cache->SetReInstall(iterator_, false);
2753 cache->MarkInstall(iterator_, false);
2755 pkgDepCache::StateCache &state((*cache)[iterator_]);
2756 if (!state.Install())
2757 cache->SetReInstall(iterator_, true);
2761 @synchronized (database_) {
2762 pkgProblemResolver *resolver = [database_ resolver];
2763 resolver->Clear(iterator_);
2764 resolver->Remove(iterator_);
2765 resolver->Protect(iterator_);
2767 pkgCacheFile &cache([database_ cache]);
2768 cache->SetReInstall(iterator_, false);
2769 cache->MarkDelete(iterator_, true);
2772 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2773 _profile(Package$isUnfilteredAndSearchedForBy)
2776 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2777 value &= [self unfiltered];
2780 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2781 value &= [self matches:search];
2788 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2789 if ([search length] == 0)
2792 _profile(Package$isUnfilteredAndSelectedForBy)
2795 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2796 value &= [self unfiltered];
2799 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2800 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2807 - (bool) isInstalledAndVisible:(NSNumber *)number {
2808 return ((![number boolValue] && ![role_ isEqualToString:@"cydia"]) || [self visible]) && ![self uninstalled];
2811 - (bool) isVisibleInSection:(NSString *)name {
2812 NSString *section = [self section];
2817 section == nil && [name length] == 0 ||
2818 [name isEqualToString:section]
2822 - (bool) isVisibleInSource:(Source *)source {
2823 return [self source] == source && [self visible];
2828 /* Section Class {{{ */
2829 @interface Section : NSObject {
2834 NSString *localized_;
2837 - (NSComparisonResult) compareByLocalized:(Section *)section;
2838 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2839 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2840 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2841 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2842 - (NSString *) name;
2849 - (void) addToCount;
2851 - (void) setCount:(size_t)count;
2852 - (NSString *) localized;
2856 @implementation Section
2860 if (localized_ != nil)
2861 [localized_ release];
2865 - (NSComparisonResult) compareByLocalized:(Section *)section {
2866 NSString *lhs(localized_);
2867 NSString *rhs([section localized]);
2869 /*if ([lhs length] != 0 && [rhs length] != 0) {
2870 unichar lhc = [lhs characterAtIndex:0];
2871 unichar rhc = [rhs characterAtIndex:0];
2873 if (isalpha(lhc) && !isalpha(rhc))
2874 return NSOrderedAscending;
2875 else if (!isalpha(lhc) && isalpha(rhc))
2876 return NSOrderedDescending;
2879 return [lhs compare:rhs options:LaxCompareOptions_];
2882 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2883 if ((self = [self initWithName:name localize:NO]) != nil) {
2884 if (localized != nil)
2885 localized_ = [localized retain];
2889 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2890 return [self initWithName:name row:0 localize:localize];
2893 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2894 if ((self = [super init]) != nil) {
2895 name_ = [name retain];
2899 localized_ = [LocalizeSection(name_) retain];
2903 /* XXX: localize the index thingees */
2904 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2905 if ((self = [super init]) != nil) {
2906 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2912 - (NSString *) name {
2932 - (void) addToCount {
2936 - (void) setCount:(size_t)count {
2940 - (NSString *) localized {
2947 static NSString *Colon_;
2948 static NSString *Error_;
2949 static NSString *Warning_;
2951 /* Database Implementation {{{ */
2952 @implementation Database
2954 + (Database *) sharedInstance {
2955 static Database *instance;
2956 if (instance == nil)
2957 instance = [[Database alloc] init];
2966 // XXX: actually implement this thing
2968 NSRecycleZone(zone_);
2969 // XXX: malloc_destroy_zone(zone_);
2970 apr_pool_destroy(pool_);
2974 - (void) _readCydia:(NSNumber *)fd { _pooled
2975 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2976 std::istream is(&ib);
2979 static Pcre finish_r("^finish:([^:]*)$");
2981 while (std::getline(is, line)) {
2982 const char *data(line.c_str());
2983 size_t size = line.size();
2984 lprintf("C:%s\n", data);
2986 if (finish_r(data, size)) {
2987 NSString *finish = finish_r[1];
2988 int index = [Finishes_ indexOfObject:finish];
2989 if (index != INT_MAX && index > Finish_)
2997 - (void) _readStatus:(NSNumber *)fd { _pooled
2998 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2999 std::istream is(&ib);
3002 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3003 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3005 while (std::getline(is, line)) {
3006 const char *data(line.c_str());
3007 size_t size(line.size());
3008 lprintf("S:%s\n", data);
3010 if (conffile_r(data, size)) {
3011 [delegate_ setConfigurationData:conffile_r[1]];
3012 } else if (strncmp(data, "status: ", 8) == 0) {
3013 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3014 [delegate_ setProgressTitle:string];
3015 } else if (pmstatus_r(data, size)) {
3016 std::string type([pmstatus_r[1] UTF8String]);
3017 NSString *id = pmstatus_r[2];
3019 float percent([pmstatus_r[3] floatValue]);
3020 [delegate_ setProgressPercent:(percent / 100)];
3022 NSString *string = pmstatus_r[4];
3024 if (type == "pmerror")
3025 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3026 withObject:[NSArray arrayWithObjects:string, id, nil]
3029 else if (type == "pmstatus") {
3030 [delegate_ setProgressTitle:string];
3031 } else if (type == "pmconffile")
3032 [delegate_ setConfigurationData:string];
3034 lprintf("E:unknown pmstatus\n");
3036 lprintf("E:unknown status\n");
3042 - (void) _readOutput:(NSNumber *)fd { _pooled
3043 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3044 std::istream is(&ib);
3047 while (std::getline(is, line)) {
3048 lprintf("O:%s\n", line.c_str());
3049 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3059 - (Package *) packageWithName:(NSString *)name {
3060 @synchronized (self) {
3061 if (static_cast<pkgDepCache *>(cache_) == NULL)
3063 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3064 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3068 if ((self = [super init]) != nil) {
3075 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3076 apr_pool_create(&pool_, NULL);
3078 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
3082 _assert(pipe(fds) != -1);
3085 _config->Set("APT::Keep-Fds::", cydiafd_);
3086 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3089 detachNewThreadSelector:@selector(_readCydia:)
3091 withObject:[NSNumber numberWithInt:fds[0]]
3094 _assert(pipe(fds) != -1);
3098 detachNewThreadSelector:@selector(_readStatus:)
3100 withObject:[NSNumber numberWithInt:fds[0]]
3103 _assert(pipe(fds) != -1);
3104 _assert(dup2(fds[0], 0) != -1);
3105 _assert(close(fds[0]) != -1);
3107 input_ = fdopen(fds[1], "a");
3109 _assert(pipe(fds) != -1);
3110 _assert(dup2(fds[1], 1) != -1);
3111 _assert(close(fds[1]) != -1);
3114 detachNewThreadSelector:@selector(_readOutput:)
3116 withObject:[NSNumber numberWithInt:fds[0]]
3121 - (pkgCacheFile &) cache {
3125 - (pkgDepCache::Policy *) policy {
3129 - (pkgRecords *) records {
3133 - (pkgProblemResolver *) resolver {
3137 - (pkgAcquire &) fetcher {
3141 - (pkgSourceList &) list {
3145 - (NSArray *) packages {
3146 return (NSArray *) packages_;
3149 - (NSArray *) sources {
3150 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3151 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3152 [sources addObject:i->second];
3156 - (NSArray *) issues {
3157 if (cache_->BrokenCount() == 0)
3160 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3162 for (Package *package in [self packages]) {
3163 if (![package broken])
3165 pkgCache::PkgIterator pkg([package iterator]);
3167 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3168 [entry addObject:[package name]];
3169 [issues addObject:entry];
3171 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3175 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3176 pkgCache::DepIterator start;
3177 pkgCache::DepIterator end;
3178 dep.GlobOr(start, end); // ++dep
3180 if (!cache_->IsImportantDep(end))
3182 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3185 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3186 [entry addObject:failure];
3187 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3189 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3190 if (Package *package = [self packageWithName:name])
3191 name = [package name];
3192 [failure addObject:name];
3194 pkgCache::PkgIterator target(start.TargetPkg());
3195 if (target->ProvidesList != 0)
3196 [failure addObject:@"?"];
3198 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3200 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3201 else if (!cache_[target].CandidateVerIter(cache_).end())
3202 [failure addObject:@"-"];
3203 else if (target->ProvidesList == 0)
3204 [failure addObject:@"!"];
3206 [failure addObject:@"%"];
3210 if (start.TargetVer() != 0)
3211 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3222 - (bool) popErrorWithTitle:(NSString *)title {
3224 std::string message;
3226 while (!_error->empty()) {
3228 bool warning(!_error->PopMessage(error));
3232 size_t size(error.size());
3233 if (size == 0 || error[size - 1] != '\n')
3235 error.resize(size - 1);
3237 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3239 if (!message.empty())
3244 if (fatal && !message.empty())
3245 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3250 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3251 return [self popErrorWithTitle:title] || !success;
3254 - (void) reloadData { CYPoolStart() {
3255 @synchronized (self) {
3258 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3259 CFArrayRemoveAllValues(packages_);
3286 apr_pool_clear(pool_);
3287 NSRecycleZone(zone_);
3289 int chk(creat("/tmp/cydia.chk", 0644));
3293 NSString *title(UCLocalize("DATABASE"));
3296 if (!cache_.Open(progress_, true)) { pop:
3298 bool warning(!_error->PopMessage(error));
3299 lprintf("cache_.Open():[%s]\n", error.c_str());
3301 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3302 [delegate_ repairWithSelector:@selector(configure)];
3303 else if (error == "The package lists or status file could not be parsed or opened.")
3304 [delegate_ repairWithSelector:@selector(update)];
3305 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3306 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3307 // else if (error == "The list of sources could not be read.")
3309 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3318 unlink("/tmp/cydia.chk");
3320 now_ = [[NSDate date] retain];
3322 policy_ = new pkgDepCache::Policy();
3323 records_ = new pkgRecords(cache_);
3324 resolver_ = new pkgProblemResolver(cache_);
3325 fetcher_ = new pkgAcquire(&status_);
3328 list_ = new pkgSourceList();
3329 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3332 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3333 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3337 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3340 if (cache_->BrokenCount() != 0) {
3341 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3344 if (cache_->BrokenCount() != 0) {
3345 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3349 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3353 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3354 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3355 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3356 // XXX: this could be more intelligent
3357 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3358 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3360 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3365 /*std::vector<Package *> packages;
3366 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3367 [packages_ release];
3372 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3373 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3374 //packages.push_back(package);
3375 CFArrayAppendValue(packages_, [package retain]);
3379 /*if (packages.empty())
3380 packages_ = [[NSArray alloc] init];
3382 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3385 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3386 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3387 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3395 /*if (!packages.empty())
3396 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3397 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3399 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3401 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3403 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3407 } } CYPoolEnd() _trace(); }
3410 @synchronized (self) {
3412 resolver_ = new pkgProblemResolver(cache_);
3414 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3415 if (!cache_[iterator].Keep()) {
3416 cache_->MarkKeep(iterator, false);
3417 cache_->SetReInstall(iterator, false);
3422 - (void) configure {
3423 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3424 system([dpkg UTF8String]);
3428 // XXX: I don't remember this condition
3433 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3435 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3437 if ([self popErrorWithTitle:title])
3441 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3444 public pkgArchiveCleaner
3447 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3452 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3459 fetcher_->Shutdown();
3461 pkgRecords records(cache_);
3463 lock_ = new FileFd();
3464 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3466 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3468 if ([self popErrorWithTitle:title])
3472 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3475 manager_ = (_system->CreatePM(cache_));
3476 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3483 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3485 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3487 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3489 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3490 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3493 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3498 bool failed = false;
3499 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3500 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3502 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3505 std::string uri = (*item)->DescURI();
3506 std::string error = (*item)->ErrorText;
3508 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3511 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3512 withObject:[NSArray arrayWithObjects:
3513 [NSString stringWithUTF8String:error.c_str()],
3525 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3527 if (_error->PendingError()) {
3532 if (result == pkgPackageManager::Failed) {
3537 if (result != pkgPackageManager::Completed) {
3542 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3544 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3546 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3547 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3550 if (![before isEqualToArray:after])
3555 NSString *title(UCLocalize("UPGRADE"));
3556 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3562 [self updateWithStatus:status_];
3565 - (void) setVisible {
3566 for (Package *package in [self packages])
3567 [package setVisible];
3570 - (void) updateWithStatus:(Status &)status {
3571 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3572 NSString *title(UCLocalize("REFRESHING_DATA"));
3575 if (!list.ReadMainList())
3576 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3579 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3580 if ([self popErrorWithTitle:title])
3583 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3584 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3585 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3587 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3591 - (void) setDelegate:(id)delegate {
3592 delegate_ = delegate;
3593 status_.setDelegate(delegate);
3594 progress_.setDelegate(delegate);
3597 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3598 SourceMap::const_iterator i(sources_.find(file->ID));
3599 return i == sources_.end() ? nil : i->second;
3605 /* Confirmation Controller {{{ */
3606 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3607 if (!iterator.end())
3608 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3609 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3611 pkgCache::PkgIterator package(dep.TargetPkg());
3614 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3622 /* Web Scripting {{{ */
3623 @interface CydiaObject : NSObject {
3625 _transient id delegate_;
3628 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3631 @implementation CydiaObject
3634 [indirect_ release];
3638 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3639 if ((self = [super init]) != nil) {
3640 indirect_ = [indirect retain];
3644 - (void) setDelegate:(id)delegate {
3645 delegate_ = delegate;
3648 + (NSArray *) _attributeKeys {
3649 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3652 - (NSArray *) attributeKeys {
3653 return [[self class] _attributeKeys];
3656 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3657 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3660 - (NSString *) device {
3661 return [[UIDevice currentDevice] uniqueIdentifier];
3664 #if 0 // XXX: implement!
3665 - (NSString *) mac {
3666 if (![indirect_ promptForSensitive:@"Mac Address"])
3670 - (NSString *) serial {
3671 if (![indirect_ promptForSensitive:@"Serial #"])
3675 - (NSString *) firewire {
3676 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3680 - (NSString *) imei {
3681 if (![indirect_ promptForSensitive:@"IMEI"])
3686 + (NSString *) webScriptNameForSelector:(SEL)selector {
3687 if (selector == @selector(close))
3689 else if (selector == @selector(getInstalledPackages))
3690 return @"getInstalledPackages";
3691 else if (selector == @selector(getPackageById:))
3692 return @"getPackageById";
3693 else if (selector == @selector(installPackages:))
3694 return @"installPackages";
3695 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3696 return @"setButtonImage";
3697 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3698 return @"setButtonTitle";
3699 else if (selector == @selector(setPopupHook:))
3700 return @"setPopupHook";
3701 else if (selector == @selector(setSpecial:))
3702 return @"setSpecial";
3703 else if (selector == @selector(setToken:))
3705 else if (selector == @selector(setViewportWidth:))
3706 return @"setViewportWidth";
3707 else if (selector == @selector(supports:))
3709 else if (selector == @selector(stringWithFormat:arguments:))
3711 else if (selector == @selector(localizedStringForKey:value:table:))
3713 else if (selector == @selector(du:))
3715 else if (selector == @selector(statfs:))
3721 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3722 return [self webScriptNameForSelector:selector] == nil;
3725 - (BOOL) supports:(NSString *)feature {
3726 return [feature isEqualToString:@"window.open"];
3729 - (NSArray *) getInstalledPackages {
3730 NSArray *packages([[Database sharedInstance] packages]);
3731 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3732 for (Package *package in packages)
3733 if ([package installed] != nil)
3734 [installed addObject:package];
3738 - (Package *) getPackageById:(NSString *)id {
3739 Package *package([[Database sharedInstance] packageWithName:id]);
3744 - (NSArray *) statfs:(NSString *)path {
3747 if (path == nil || statfs([path UTF8String], &stat) == -1)
3750 return [NSArray arrayWithObjects:
3751 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3752 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3753 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3757 - (NSNumber *) du:(NSString *)path {
3758 NSNumber *value(nil);
3761 _assert(pipe(fds) != -1);
3763 pid_t pid(ExecFork());
3765 _assert(dup2(fds[1], 1) != -1);
3766 _assert(close(fds[0]) != -1);
3767 _assert(close(fds[1]) != -1);
3768 /* XXX: this should probably not use du */
3769 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3774 _assert(close(fds[1]) != -1);
3776 if (FILE *du = fdopen(fds[0], "r")) {
3778 while (fgets(line, sizeof(line), du) != NULL) {
3779 size_t length(strlen(line));
3780 while (length != 0 && line[length - 1] == '\n')
3781 line[--length] = '\0';
3782 if (char *tab = strchr(line, '\t')) {
3784 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3789 } else _assert(close(fds[0]));
3793 if (waitpid(pid, &status, 0) == -1)
3796 else _assert(false);
3805 - (void) installPackages:(NSArray *)packages {
3806 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3809 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3810 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3813 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3814 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3817 - (void) setSpecial:(id)function {
3818 [indirect_ setSpecial:function];
3821 - (void) setToken:(NSString *)token {
3824 Token_ = [token retain];
3826 [Metadata_ setObject:Token_ forKey:@"Token"];
3830 - (void) setPopupHook:(id)function {
3831 [indirect_ setPopupHook:function];
3834 - (void) setViewportWidth:(float)width {
3835 [indirect_ setViewportWidth:width];
3838 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3839 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3840 unsigned count([arguments count]);
3842 for (unsigned i(0); i != count; ++i)
3843 values[i] = [arguments objectAtIndex:i];
3844 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3847 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3848 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3850 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3852 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3858 /* Cydia Browser Controller {{{ */
3859 @interface CYBrowserController : BrowserController {
3860 CydiaObject *cydia_;
3865 @implementation CYBrowserController
3872 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3875 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3876 [super webView:view didClearWindowObject:window forFrame:frame];
3878 WebDataSource *source([frame dataSource]);
3879 NSURLResponse *response([source response]);
3880 NSURL *url([response URL]);
3881 NSString *scheme([url scheme]);
3883 NSHTTPURLResponse *http;
3884 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3885 http = (NSHTTPURLResponse *) response;
3889 NSDictionary *headers([http allHeaderFields]);
3890 NSString *host([url host]);
3891 [self setHeaders:headers forHost:host];
3894 [host isEqualToString:@"cydia.saurik.com"] ||
3895 [host hasSuffix:@".cydia.saurik.com"] ||
3896 [scheme isEqualToString:@"file"]
3898 [window setValue:cydia_ forKey:@"cydia"];
3901 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3902 if (System_ != NULL)
3903 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3904 if (Machine_ != NULL)
3905 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3907 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3909 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3912 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3913 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3914 [self _setMoreHeaders:copy];
3918 - (void) setDelegate:(id)delegate {
3919 [super setDelegate:delegate];
3920 [cydia_ setDelegate:delegate];
3924 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3925 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3927 WebView *webview([[webview_ _documentView] webView]);
3929 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3931 NSString *application = package == nil ? @"Cydia" : [NSString
3932 stringWithFormat:@"Cydia/%@",
3937 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3939 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3940 if (Product_ != nil)
3941 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3943 [webview setApplicationNameForUserAgent:application];
3950 /* Confirmation {{{ */
3951 @protocol ConfirmationControllerDelegate
3952 - (void) cancelAndClear:(bool)clear;
3953 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3957 @interface ConfirmationController : CYBrowserController {
3958 _transient Database *database_;
3959 UIAlertView *essential_;
3966 - (id) initWithDatabase:(Database *)database;
3970 @implementation ConfirmationController
3977 if (essential_ != nil)
3978 [essential_ release];
3982 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3983 NSString *context([alert context]);
3985 if ([context isEqualToString:@"remove"]) {
3986 if (button == [alert cancelButtonIndex]) {
3987 [self dismissModalViewControllerAnimated:YES];
3988 } else if (button == [alert firstOtherButtonIndex]) {
3991 [delegate_ confirmWithNavigationController:[self navigationController]];
3994 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3995 } else if ([context isEqualToString:@"unable"]) {
3996 [self dismissModalViewControllerAnimated:YES];
3997 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3999 [super alertView:alert clickedButtonAtIndex:button];
4003 - (void) _doContinue {
4004 [self dismissModalViewControllerAnimated:YES];
4005 [delegate_ cancelAndClear:NO];
4008 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4009 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4013 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4014 [super webView:view didClearWindowObject:window forFrame:frame];
4015 [window setValue:changes_ forKey:@"changes"];
4016 [window setValue:issues_ forKey:@"issues"];
4017 [window setValue:sizes_ forKey:@"sizes"];
4018 [window setValue:self forKey:@"queue"];
4021 - (id) initWithDatabase:(Database *)database {
4022 if ((self = [super init]) != nil) {
4023 database_ = database;
4025 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4027 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4028 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4029 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4030 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4031 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4035 pkgDepCache::Policy *policy([database_ policy]);
4037 pkgCacheFile &cache([database_ cache]);
4038 NSArray *packages = [database_ packages];
4039 for (Package *package in packages) {
4040 pkgCache::PkgIterator iterator = [package iterator];
4041 pkgDepCache::StateCache &state(cache[iterator]);
4043 NSString *name([package name]);
4045 if (state.NewInstall())
4046 [installing addObject:name];
4047 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4048 [reinstalling addObject:name];
4049 else if (state.Upgrade())
4050 [upgrading addObject:name];
4051 else if (state.Downgrade())
4052 [downgrading addObject:name];
4053 else if (state.Delete()) {
4054 if ([package essential])
4056 [removing addObject:name];
4059 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4060 substrate_ |= DepSubstrate(iterator.CurrentVer());
4065 else if (Advanced_) {
4066 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4068 essential_ = [[UIAlertView alloc]
4069 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4070 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4072 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4073 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4076 [essential_ setContext:@"remove"];
4078 essential_ = [[UIAlertView alloc]
4079 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4080 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4082 cancelButtonTitle:UCLocalize("OKAY")
4083 otherButtonTitles:nil
4086 [essential_ setContext:@"unable"];
4089 changes_ = [[NSArray alloc] initWithObjects:
4097 issues_ = [database_ issues];
4099 issues_ = [issues_ retain];
4101 sizes_ = [[NSArray alloc] initWithObjects:
4102 SizeString([database_ fetcher].FetchNeeded()),
4103 SizeString([database_ fetcher].PartialPresent()),
4106 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4108 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4109 initWithTitle:UCLocalize("CANCEL")
4110 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4111 style:UIBarButtonItemStylePlain
4113 action:@selector(cancelButtonClicked)
4118 - (void) applyRightButton {
4119 #if !AlwaysReload && !IgnoreInstall
4120 if (issues_ == nil && ![self isLoading])
4121 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4122 initWithTitle:UCLocalize("CONFIRM")
4123 style:UIBarButtonItemStylePlain
4125 action:@selector(confirmButtonClicked)
4128 [super applyRightButton];
4130 [[self navigationItem] setRightBarButtonItem:nil];
4134 - (void) cancelButtonClicked {
4135 [self dismissModalViewControllerAnimated:YES];
4136 [delegate_ cancelAndClear:YES];
4140 - (void) confirmButtonClicked {
4144 if (essential_ != nil)
4149 [delegate_ confirmWithNavigationController:[self navigationController]];
4157 /* Progress Data {{{ */
4158 @interface ProgressData : NSObject {
4160 // XXX: should these really both be _transient?
4161 _transient id target_;
4162 _transient id object_;
4165 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4172 @implementation ProgressData
4174 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4175 if ((self = [super init]) != nil) {
4176 selector_ = selector;
4196 /* Progress Controller {{{ */
4197 @interface ProgressController : CYViewController <
4198 ConfigurationDelegate,
4201 _transient Database *database_;
4202 UIProgressBar *progress_;
4203 UITextView *output_;
4204 UITextLabel *status_;
4205 UIPushButton *close_;
4207 SHA1SumValue springlist_;
4208 SHA1SumValue notifyconf_;
4212 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4214 - (void) _retachThread;
4215 - (void) _detachNewThreadData:(ProgressData *)data;
4216 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4222 @protocol ProgressControllerDelegate
4223 - (void) progressControllerIsComplete:(ProgressController *)sender;
4226 @implementation ProgressController
4229 [database_ setDelegate:nil];
4230 [progress_ release];
4239 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4240 if ((self = [super init]) != nil) {
4241 database_ = database;
4242 [database_ setDelegate:self];
4243 delegate_ = delegate;
4245 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4247 progress_ = [[UIProgressBar alloc] init];
4248 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4249 [progress_ setStyle:0];
4251 status_ = [[UITextLabel alloc] init];
4252 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4253 [status_ setColor:[UIColor whiteColor]];
4254 [status_ setBackgroundColor:[UIColor clearColor]];
4255 [status_ setCentersHorizontally:YES];
4256 //[status_ setFont:font];
4258 output_ = [[UITextView alloc] init];
4260 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4261 //[output_ setTextFont:@"Courier New"];
4262 [output_ setFont:[[output_ font] fontWithSize:12]];
4263 [output_ setTextColor:[UIColor whiteColor]];
4264 [output_ setBackgroundColor:[UIColor clearColor]];
4265 [output_ setMarginTop:0];
4266 [output_ setAllowsRubberBanding:YES];
4267 [output_ setEditable:NO];
4268 [[self view] addSubview:output_];
4270 close_ = [[UIPushButton alloc] init];
4271 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4272 [close_ setAutosizesToFit:NO];
4273 [close_ setDrawsShadow:YES];
4274 [close_ setStretchBackground:YES];
4275 [close_ setEnabled:YES];
4276 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4277 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4278 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4279 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4283 - (void) positionViews {
4284 CGRect bounds = [[self view] bounds];
4285 CGSize prgsize = [UIProgressBar defaultSize];
4288 (bounds.size.width - prgsize.width) / 2,
4289 bounds.size.height - prgsize.height - 20
4292 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4294 [progress_ setFrame:prgrect];
4295 [status_ setFrame:CGRectMake(
4297 bounds.size.height - prgsize.height - 50,
4298 bounds.size.width - 20,
4301 [output_ setFrame:CGRectMake(
4304 bounds.size.width - 20,
4305 bounds.size.height - 62
4307 [close_ setFrame:CGRectMake(
4308 (bounds.size.width - closewidth) / 2,
4309 bounds.size.height - prgsize.height - 50,
4315 - (void) viewWillAppear:(BOOL)animated {
4316 [super viewDidAppear:animated];
4317 [[self navigationItem] setHidesBackButton:YES];
4318 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4320 [self positionViews];
4323 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4324 [self positionViews];
4327 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4328 NSString *context([alert context]);
4330 if ([context isEqualToString:@"conffile"]) {
4331 FILE *input = [database_ input];
4332 if (button == [alert cancelButtonIndex])
4333 fprintf(input, "N\n");
4334 else if (button == [alert firstOtherButtonIndex])
4335 fprintf(input, "Y\n");
4340 - (void) closeButtonPushed {
4343 UpdateExternalStatus(0);
4347 [self dismissModalViewControllerAnimated:YES];
4351 [delegate_ terminateWithSuccess];
4352 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4353 [delegate_ suspendWithAnimation:YES];
4355 [delegate_ suspend];*/
4359 system("launchctl stop com.apple.SpringBoard");
4363 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4372 - (void) _retachThread {
4373 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4375 [[self view] addSubview:close_];
4376 [progress_ removeFromSuperview];
4377 [status_ removeFromSuperview];
4379 [database_ popErrorWithTitle:title_];
4380 [delegate_ progressControllerIsComplete:self];
4384 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4387 MMap mmap(file, MMap::ReadOnly);
4389 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4390 if (!(notifyconf_ == sha1.Result()))
4397 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4400 MMap mmap(file, MMap::ReadOnly);
4402 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4403 if (!(springlist_ == sha1.Result()))
4409 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4410 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4411 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4412 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4413 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4416 system("su -c /usr/bin/uicache mobile");
4418 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4420 [delegate_ setStatusBarShowsProgress:NO];
4423 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4424 [[data target] performSelector:[data selector] withObject:[data object]];
4425 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4428 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4429 UpdateExternalStatus(1);
4436 title_ = [title retain];
4438 [[self navigationItem] setTitle:title_];
4440 [status_ setText:nil];
4441 [output_ setText:@""];
4442 [progress_ setProgress:0];
4444 [close_ removeFromSuperview];
4445 [[self view] addSubview:progress_];
4446 [[self view] addSubview:status_];
4448 [delegate_ setStatusBarShowsProgress:YES];
4453 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4456 MMap mmap(file, MMap::ReadOnly);
4458 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4459 notifyconf_ = sha1.Result();
4465 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4468 MMap mmap(file, MMap::ReadOnly);
4470 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4471 springlist_ = sha1.Result();
4476 detachNewThreadSelector:@selector(_detachNewThreadData:)
4478 withObject:[[[ProgressData alloc]
4479 initWithSelector:selector
4486 - (void) repairWithSelector:(SEL)selector {
4488 detachNewThreadSelector:selector
4491 title:UCLocalize("REPAIRING")
4495 - (void) setConfigurationData:(NSString *)data {
4497 performSelectorOnMainThread:@selector(_setConfigurationData:)
4503 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4504 CYActionSheet *sheet([[[CYActionSheet alloc]
4506 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4507 defaultButtonIndex:0
4510 [sheet setMessage:error];
4511 [sheet yieldToPopupAlertAnimated:YES];
4515 - (void) setProgressTitle:(NSString *)title {
4517 performSelectorOnMainThread:@selector(_setProgressTitle:)
4523 - (void) setProgressPercent:(float)percent {
4525 performSelectorOnMainThread:@selector(_setProgressPercent:)
4526 withObject:[NSNumber numberWithFloat:percent]
4531 - (void) startProgress {
4534 - (void) addProgressOutput:(NSString *)output {
4536 performSelectorOnMainThread:@selector(_addProgressOutput:)
4542 - (bool) isCancelling:(size_t)received {
4546 - (void) _setConfigurationData:(NSString *)data {
4547 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4549 if (!conffile_r(data)) {
4550 lprintf("E:invalid conffile\n");
4554 NSString *ofile = conffile_r[1];
4555 //NSString *nfile = conffile_r[2];
4557 UIAlertView *alert = [[[UIAlertView alloc]
4558 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4559 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4561 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4562 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4563 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4567 [alert setContext:@"conffile"];
4571 - (void) _setProgressTitle:(NSString *)title {
4572 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4573 for (size_t i(0), e([words count]); i != e; ++i) {
4574 NSString *word([words objectAtIndex:i]);
4575 if (Package *package = [database_ packageWithName:word])
4576 [words replaceObjectAtIndex:i withObject:[package name]];
4579 [status_ setText:[words componentsJoinedByString:@" "]];
4582 - (void) _setProgressPercent:(NSNumber *)percent {
4583 [progress_ setProgress:[percent floatValue]];
4586 - (void) _addProgressOutput:(NSString *)output {
4587 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4588 CGSize size = [output_ contentSize];
4589 CGRect rect = {{0, size.height}, {size.width, 0}};
4590 [output_ scrollRectToVisible:rect animated:YES];
4593 - (BOOL) isRunning {
4600 /* Cell Content View {{{ */
4601 @protocol ContentDelegate
4602 - (void) drawContentRect:(CGRect)rect;
4605 @interface ContentView : UIView {
4606 _transient id<ContentDelegate> delegate_;
4611 @implementation ContentView
4612 - (id) initWithFrame:(CGRect)frame {
4613 if ((self = [super initWithFrame:frame]) != nil) {
4614 /* Fix landscape stretching. */
4615 [self setNeedsDisplayOnBoundsChange:YES];
4619 - (void) setDelegate:(id<ContentDelegate>)delegate {
4620 delegate_ = delegate;
4623 - (void) drawRect:(CGRect)rect {
4624 [super drawRect:rect];
4625 [delegate_ drawContentRect:rect];
4629 /* Package Cell {{{ */
4630 @interface PackageCell : UITableViewCell <
4635 NSString *description_;
4641 ContentView *content_;
4647 - (PackageCell *) init;
4648 - (void) setPackage:(Package *)package;
4650 + (int) heightForPackage:(Package *)package;
4651 - (void) drawContentRect:(CGRect)rect;
4655 @implementation PackageCell
4657 - (void) clearPackage {
4668 if (description_ != nil) {
4669 [description_ release];
4673 if (source_ != nil) {
4678 if (badge_ != nil) {
4683 if (placard_ != nil) {
4693 [self clearPackage];
4700 return faded_ ? [self selectionPercent] : fade_;
4703 - (PackageCell *) init {
4704 CGRect frame(CGRectMake(0, 0, 320, 74));
4705 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4706 UIView *content([self contentView]);
4707 CGRect bounds([content bounds]);
4709 content_ = [[ContentView alloc] initWithFrame:bounds];
4710 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4711 [content addSubview:content_];
4713 [content_ setDelegate:self];
4714 [content_ setOpaque:YES];
4715 if ([self respondsToSelector:@selector(selectionPercent)])
4720 - (void) _setBackgroundColor {
4722 if (NSString *mode = [package_ mode]) {
4723 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4724 color = remove ? RemovingColor_ : InstallingColor_;
4726 color = [UIColor whiteColor];
4728 [content_ setBackgroundColor:color];
4729 [self setNeedsDisplay];
4732 - (void) setPackage:(Package *)package {
4733 [self clearPackage];
4736 Source *source = [package source];
4738 icon_ = [[package icon] retain];
4739 name_ = [[package name] retain];
4742 description_ = [package longDescription];
4743 if (description_ == nil)
4744 description_ = [package shortDescription];
4745 if (description_ != nil)
4746 description_ = [description_ retain];
4748 commercial_ = [package isCommercial];
4750 package_ = [package retain];
4752 NSString *label = nil;
4753 bool trusted = false;
4755 if (source != nil) {
4756 label = [source label];
4757 trusted = [source trusted];
4758 } else if ([[package id] isEqualToString:@"firmware"])
4759 label = UCLocalize("APPLE");
4761 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4763 NSString *from(label);
4765 NSString *section = [package simpleSection];
4766 if (section != nil && ![section isEqualToString:label]) {
4767 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4768 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4771 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4772 source_ = [from retain];
4774 if (NSString *purpose = [package primaryPurpose])
4775 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4776 badge_ = [badge_ retain];
4778 if ([package installed] != nil)
4779 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4780 placard_ = [placard_ retain];
4782 [self _setBackgroundColor];
4783 [content_ setNeedsDisplay];
4786 - (void) drawContentRect:(CGRect)rect {
4787 bool selected([self isSelected]);
4788 float width([self bounds].size.width);
4791 CGContextRef context(UIGraphicsGetCurrentContext());
4792 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4793 CGContextFillRect(context, rect);
4798 rect.size = [icon_ size];
4800 rect.size.width /= 2;
4801 rect.size.height /= 2;
4803 rect.origin.x = 25 - rect.size.width / 2;
4804 rect.origin.y = 25 - rect.size.height / 2;
4806 [icon_ drawInRect:rect];
4809 if (badge_ != nil) {
4810 CGSize size = [badge_ size];
4812 [badge_ drawAtPoint:CGPointMake(
4813 36 - size.width / 2,
4814 36 - size.height / 2
4822 UISetColor(commercial_ ? Purple_ : Black_);
4823 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4824 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4827 UISetColor(commercial_ ? Purplish_ : Gray_);
4828 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4830 if (placard_ != nil)
4831 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4834 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4835 //[self _setBackgroundColor];
4836 [super setSelected:selected animated:fade];
4837 [content_ setNeedsDisplay];
4840 + (int) heightForPackage:(Package *)package {
4846 /* Section Cell {{{ */
4847 @interface SectionCell : UITableViewCell <
4855 ContentView *content_;
4860 - (void) setSection:(Section *)section editing:(BOOL)editing;
4864 @implementation SectionCell
4866 - (void) clearSection {
4867 if (basic_ != nil) {
4872 if (section_ != nil) {
4882 if (count_ != nil) {
4889 [self clearSection];
4897 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4898 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4899 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4900 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4901 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4903 UIView *content([self contentView]);
4904 CGRect bounds([content bounds]);
4906 content_ = [[ContentView alloc] initWithFrame:bounds];
4907 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4908 [content addSubview:content_];
4909 [content_ setBackgroundColor:[UIColor whiteColor]];
4911 [content_ setDelegate:self];
4915 - (void) onSwitch:(id)sender {
4916 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4917 if (metadata == nil) {
4918 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4919 [Sections_ setObject:metadata forKey:basic_];
4923 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4926 - (void) setSection:(Section *)section editing:(BOOL)editing {
4927 if (editing != editing_) {
4929 [switch_ removeFromSuperview];
4931 [self addSubview:switch_];
4935 [self clearSection];
4937 if (section == nil) {
4938 name_ = [UCLocalize("ALL_PACKAGES") retain];
4941 basic_ = [section name];
4943 basic_ = [basic_ retain];
4945 section_ = [section localized];
4946 if (section_ != nil)
4947 section_ = [section_ retain];
4949 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4950 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4953 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4956 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4957 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
4959 [content_ setNeedsDisplay];
4962 - (void) setFrame:(CGRect)frame {
4963 [super setFrame:frame];
4965 CGRect rect([switch_ frame]);
4966 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4969 - (void) drawContentRect:(CGRect)rect {
4970 BOOL selected = [self isSelected];
4972 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4980 float width(rect.size.width);
4984 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4986 CGSize size = [count_ sizeWithFont:Font14_];
4990 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4996 /* File Table {{{ */
4997 @interface FileTable : CYViewController <
4998 UITableViewDataSource,
5001 _transient Database *database_;
5004 NSMutableArray *files_;
5008 - (id) initWithDatabase:(Database *)database;
5009 - (void) setPackage:(Package *)package;
5013 @implementation FileTable
5016 if (package_ != nil)
5025 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5026 return files_ == nil ? 0 : [files_ count];
5029 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5033 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5034 static NSString *reuseIdentifier = @"Cell";
5036 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5038 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5039 [cell setFont:[UIFont systemFontOfSize:16]];
5041 [cell setText:[files_ objectAtIndex:indexPath.row]];
5042 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5047 - (id) initWithDatabase:(Database *)database {
5048 if ((self = [super init]) != nil) {
5049 database_ = database;
5051 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5053 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5055 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5056 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5057 [list_ setRowHeight:24.0f];
5058 [[self view] addSubview:list_];
5060 [list_ setDataSource:self];
5061 [list_ setDelegate:self];
5065 - (void) setPackage:(Package *)package {
5066 if (package_ != nil) {
5067 [package_ autorelease];
5076 [files_ removeAllObjects];
5078 if (package != nil) {
5079 package_ = [package retain];
5080 name_ = [[package id] retain];
5082 if (NSArray *files = [package files])
5083 [files_ addObjectsFromArray:files];
5085 if ([files_ count] != 0) {
5086 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5087 [files_ removeObjectAtIndex:0];
5088 [files_ sortUsingSelector:@selector(compareByPath:)];
5090 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5091 [stack addObject:@"/"];
5093 for (int i(0), e([files_ count]); i != e; ++i) {
5094 NSString *file = [files_ objectAtIndex:i];
5095 while (![file hasPrefix:[stack lastObject]])
5096 [stack removeLastObject];
5097 NSString *directory = [stack lastObject];
5098 [stack addObject:[file stringByAppendingString:@"/"]];
5099 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5100 ([stack count] - 2) * 3, "",
5101 [file substringFromIndex:[directory length]]
5110 - (void) reloadData {
5111 [self setPackage:[database_ packageWithName:name_]];
5116 /* Package Controller {{{ */
5117 @interface PackageController : CYBrowserController <
5118 UIActionSheetDelegate
5120 _transient Database *database_;
5124 NSMutableArray *buttons_;
5125 UIBarButtonItem *button_;
5128 - (id) initWithDatabase:(Database *)database;
5129 - (void) setPackage:(Package *)package;
5133 @implementation PackageController
5136 if (package_ != nil)
5150 if ([self retainCount] == 1)
5151 [delegate_ setPackageController:self];
5155 /* XXX: this is not safe at all... localization of /fail/ */
5156 - (void) _clickButtonWithName:(NSString *)name {
5157 if ([name isEqualToString:UCLocalize("CLEAR")])
5158 [delegate_ clearPackage:package_];
5159 else if ([name isEqualToString:UCLocalize("INSTALL")])
5160 [delegate_ installPackage:package_];
5161 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5162 [delegate_ installPackage:package_];
5163 else if ([name isEqualToString:UCLocalize("REMOVE")])
5164 [delegate_ removePackage:package_];
5165 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5166 [delegate_ installPackage:package_];
5167 else _assert(false);
5170 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5171 NSString *context([sheet context]);
5173 if ([context isEqualToString:@"modify"]) {
5174 if (button != [sheet cancelButtonIndex]) {
5175 NSString *buttonName = [buttons_ objectAtIndex:button];
5176 [self _clickButtonWithName:buttonName];
5179 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5183 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5184 [super webView:view didClearWindowObject:window forFrame:frame];
5185 [window setValue:package_ forKey:@"package"];
5188 - (bool) _allowJavaScriptPanel {
5193 - (void) _customButtonClicked {
5194 int count([buttons_ count]);
5199 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5201 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5202 [buttons addObjectsFromArray:buttons_];
5204 UIActionSheet *sheet = [[[UIActionSheet alloc]
5207 cancelButtonTitle:nil
5208 destructiveButtonTitle:nil
5209 otherButtonTitles:nil
5212 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5214 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5215 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5217 [sheet setContext:@"modify"];
5219 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5223 // We don't want to allow non-commercial packages to do custom things to the install button,
5224 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5225 - (void) customButtonClicked {
5227 [super customButtonClicked];
5229 [self _customButtonClicked];
5232 - (void) reloadButtonClicked {
5233 // Don't reload a package view by clicking the button.
5236 - (void) applyLoadingTitle {
5237 // Don't show "Loading" as the title. Ever.
5240 - (UIBarButtonItem *) rightButton {
5245 - (id) initWithDatabase:(Database *)database {
5246 if ((self = [super init]) != nil) {
5247 database_ = database;
5248 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5249 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5253 - (void) setPackage:(Package *)package {
5254 if (package_ != nil) {
5255 [package_ autorelease];
5264 [buttons_ removeAllObjects];
5266 if (package != nil) {
5269 package_ = [package retain];
5270 name_ = [[package id] retain];
5271 commercial_ = [package isCommercial];
5273 if ([package_ mode] != nil)
5274 [buttons_ addObject:UCLocalize("CLEAR")];
5275 if ([package_ source] == nil);
5276 else if ([package_ upgradableAndEssential:NO])
5277 [buttons_ addObject:UCLocalize("UPGRADE")];
5278 else if ([package_ uninstalled])
5279 [buttons_ addObject:UCLocalize("INSTALL")];
5281 [buttons_ addObject:UCLocalize("REINSTALL")];
5282 if (![package_ uninstalled])
5283 [buttons_ addObject:UCLocalize("REMOVE")];
5290 switch ([buttons_ count]) {
5291 case 0: title = nil; break;
5292 case 1: title = [buttons_ objectAtIndex:0]; break;
5293 default: title = UCLocalize("MODIFY"); break;
5296 button_ = [[UIBarButtonItem alloc]
5298 style:UIBarButtonItemStylePlain
5300 action:@selector(customButtonClicked)
5306 - (bool) isLoading {
5307 return commercial_ ? [super isLoading] : false;
5310 - (void) reloadData {
5311 [self setPackage:[database_ packageWithName:name_]];
5316 /* Package Table {{{ */
5317 @interface PackageTable : UIView <
5318 UITableViewDataSource,
5321 _transient Database *database_;
5322 NSMutableArray *packages_;
5323 NSMutableArray *sections_;
5325 NSMutableArray *index_;
5326 NSMutableDictionary *indices_;
5327 // XXX: this target_ seems to be delegate_. :(
5328 _transient id target_;
5330 // XXX: why do we even have this delegate_?
5331 _transient id delegate_;
5334 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5336 - (void) setDelegate:(id)delegate;
5338 - (void) reloadData;
5339 - (void) resetCursor;
5341 - (UITableView *) list;
5343 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5345 - (void) deselectWithAnimation:(BOOL)animated;
5349 @implementation PackageTable
5352 [packages_ release];
5353 [sections_ release];
5361 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5362 NSInteger count([sections_ count]);
5363 return count == 0 ? 1 : count;
5366 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5367 if ([sections_ count] == 0)
5369 return [[sections_ objectAtIndex:section] name];
5372 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5373 if ([sections_ count] == 0)
5375 return [[sections_ objectAtIndex:section] count];
5378 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5379 Section *section([sections_ objectAtIndex:[path section]]);
5380 NSInteger row([path row]);
5381 Package *package([packages_ objectAtIndex:([section row] + row)]);
5385 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5386 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5388 cell = [[[PackageCell alloc] init] autorelease];
5389 [cell setPackage:[self packageAtIndexPath:path]];
5393 - (void) deselectWithAnimation:(BOOL)animated {
5394 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5397 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5398 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5401 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5402 Package *package([self packageAtIndexPath:path]);
5403 package = [database_ packageWithName:[package id]];
5404 [target_ performSelector:action_ withObject:package];
5408 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5409 return [packages_ count] > 20 ? index_ : nil;
5412 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5416 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5417 if ((self = [super initWithFrame:frame]) != nil) {
5418 database_ = database;
5423 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5424 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5426 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5427 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5429 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5430 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5431 [list_ setRowHeight:73.0f];
5432 [self addSubview:list_];
5434 [list_ setDataSource:self];
5435 [list_ setDelegate:self];
5439 - (void) setDelegate:(id)delegate {
5440 delegate_ = delegate;
5443 - (bool) hasPackage:(Package *)package {
5447 - (void) reloadData {
5448 NSArray *packages = [database_ packages];
5450 [packages_ removeAllObjects];
5451 [sections_ removeAllObjects];
5453 _profile(PackageTable$reloadData$Filter)
5454 for (Package *package in packages)
5455 if ([self hasPackage:package])
5456 [packages_ addObject:package];
5459 [index_ removeAllObjects];
5460 [indices_ removeAllObjects];
5462 Section *section = nil;
5464 _profile(PackageTable$reloadData$Section)
5465 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5469 _profile(PackageTable$reloadData$Section$Package)
5470 package = [packages_ objectAtIndex:offset];
5471 index = [package index];
5474 if (section == nil || [section index] != index) {
5475 _profile(PackageTable$reloadData$Section$Allocate)
5476 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5479 [index_ addObject:[section name]];
5480 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5482 _profile(PackageTable$reloadData$Section$Add)
5483 [sections_ addObject:section];
5487 [section addToCount];
5491 _profile(PackageTable$reloadData$List)
5496 - (void) resetCursor {
5497 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5500 - (UITableView *) list {
5504 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5505 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5510 /* Filtered Package Table {{{ */
5511 @interface FilteredPackageTable : PackageTable {
5517 - (void) setObject:(id)object;
5518 - (void) setObject:(id)object forFilter:(SEL)filter;
5520 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5524 @implementation FilteredPackageTable
5532 - (void) setFilter:(SEL)filter {
5535 /* XXX: this is an unsafe optimization of doomy hell */
5536 Method method(class_getInstanceMethod([Package class], filter));
5537 _assert(method != NULL);
5538 imp_ = method_getImplementation(method);
5539 _assert(imp_ != NULL);
5542 - (void) setObject:(id)object {
5548 object_ = [object retain];
5551 - (void) setObject:(id)object forFilter:(SEL)filter {
5552 [self setFilter:filter];
5553 [self setObject:object];
5556 - (bool) hasPackage:(Package *)package {
5557 _profile(FilteredPackageTable$hasPackage)
5558 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5562 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5563 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5564 [self setFilter:filter];
5565 object_ = [object retain];
5573 /* Filtered Package Controller {{{ */
5574 @interface FilteredPackageController : CYViewController {
5575 _transient Database *database_;
5576 FilteredPackageTable *packages_;
5580 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5584 @implementation FilteredPackageController
5587 [packages_ release];
5593 - (void) viewDidAppear:(BOOL)animated {
5594 [super viewDidAppear:animated];
5595 [packages_ deselectWithAnimation:animated];
5598 - (void) didSelectPackage:(Package *)package {
5599 PackageController *view([delegate_ packageController]);
5600 [view setPackage:package];
5601 [view setDelegate:delegate_];
5602 [[self navigationController] pushViewController:view animated:YES];
5605 - (NSString *) title { return title_; }
5607 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5608 if ((self = [super init]) != nil) {
5609 database_ = database;
5610 title_ = [title copy];
5611 [[self navigationItem] setTitle:title_];
5613 packages_ = [[FilteredPackageTable alloc]
5614 initWithFrame:[[self view] bounds]
5617 action:@selector(didSelectPackage:)
5622 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5623 [[self view] addSubview:packages_];
5627 - (void) reloadData {
5628 [packages_ reloadData];
5631 - (void) setDelegate:(id)delegate {
5632 [super setDelegate:delegate];
5633 [packages_ setDelegate:delegate];
5640 /* Add Source Controller {{{ */
5641 @interface AddSourceController : CYViewController {
5642 _transient Database *database_;
5645 - (id) initWithDatabase:(Database *)database;
5649 @implementation AddSourceController
5651 - (id) initWithDatabase:(Database *)database {
5652 if ((self = [super init]) != nil) {
5653 database_ = database;
5659 /* Source Cell {{{ */
5660 @interface SourceCell : UITableViewCell <
5665 NSString *description_;
5667 ContentView *content_;
5670 - (void) setSource:(Source *)source;
5674 @implementation SourceCell
5676 - (void) clearSource {
5679 [description_ release];
5688 - (void) setSource:(Source *)source {
5692 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5694 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5695 icon_ = [icon_ retain];
5697 origin_ = [[source name] retain];
5698 label_ = [[source uri] retain];
5699 description_ = [[source description] retain];
5701 [content_ setNeedsDisplay];
5710 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5711 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5712 UIView *content([self contentView]);
5713 CGRect bounds([content bounds]);
5715 content_ = [[ContentView alloc] initWithFrame:bounds];
5716 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5717 [content_ setBackgroundColor:[UIColor whiteColor]];
5718 [content addSubview:content_];
5720 [content_ setDelegate:self];
5721 [content_ setOpaque:YES];
5725 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5726 [super setSelected:selected animated:animated];
5727 [content_ setNeedsDisplay];
5730 - (void) drawContentRect:(CGRect)rect {
5731 bool selected([self isSelected]);
5732 float width(rect.size.width);
5735 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5742 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5746 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5750 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5755 /* Source Table {{{ */
5756 @interface SourceTable : CYViewController <
5757 UITableViewDataSource,
5760 _transient Database *database_;
5762 NSMutableArray *sources_;
5766 UIProgressHUD *hud_;
5769 //NSURLConnection *installer_;
5770 NSURLConnection *trivial_;
5771 NSURLConnection *trivial_bz2_;
5772 NSURLConnection *trivial_gz_;
5773 //NSURLConnection *automatic_;
5778 - (id) initWithDatabase:(Database *)database;
5780 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5784 @implementation SourceTable
5786 - (void) _releaseConnection:(NSURLConnection *)connection {
5787 if (connection != nil) {
5788 [connection cancel];
5789 //[connection setDelegate:nil];
5790 [connection release];
5802 //[self _releaseConnection:installer_];
5803 [self _releaseConnection:trivial_];
5804 [self _releaseConnection:trivial_gz_];
5805 [self _releaseConnection:trivial_bz2_];
5806 //[self _releaseConnection:automatic_];
5813 - (void) viewDidAppear:(BOOL)animated {
5814 [super viewDidAppear:animated];
5815 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5818 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5819 return offset_ == 0 ? 1 : 2;
5822 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5823 switch (section + (offset_ == 0 ? 1 : 0)) {
5824 case 0: return UCLocalize("ENTERED_BY_USER");
5825 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5831 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5832 int count = [sources_ count];
5834 case 0: return (offset_ == 0 ? count : offset_);
5835 case 1: return count - offset_;
5841 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5843 switch (indexPath.section) {
5844 case 0: idx = indexPath.row; break;
5845 case 1: idx = indexPath.row + offset_; break;
5849 return [sources_ objectAtIndex:idx];
5852 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5853 Source *source = [self sourceAtIndexPath:indexPath];
5854 return [source description] == nil ? 56 : 73;
5857 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5858 static NSString *cellIdentifier = @"SourceCell";
5860 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5861 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5862 [cell setSource:[self sourceAtIndexPath:indexPath]];
5867 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5868 return UITableViewCellAccessoryDisclosureIndicator;
5871 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5872 Source *source = [self sourceAtIndexPath:indexPath];
5874 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5875 initWithDatabase:database_
5876 title:[source label]
5877 filter:@selector(isVisibleInSource:)
5881 [packages setDelegate:delegate_];
5883 [[self navigationController] pushViewController:packages animated:YES];
5886 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5887 Source *source = [self sourceAtIndexPath:indexPath];
5888 return [source record] != nil;
5891 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5892 Source *source = [self sourceAtIndexPath:indexPath];
5893 [Sources_ removeObjectForKey:[source key]];
5894 [delegate_ syncData];
5898 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5901 @"./", @"Distribution",
5902 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5904 [delegate_ syncData];
5907 - (NSString *) getWarning {
5908 NSString *href(href_);
5909 NSRange colon([href rangeOfString:@"://"]);
5910 if (colon.location != NSNotFound)
5911 href = [href substringFromIndex:(colon.location + 3)];
5912 href = [href stringByAddingPercentEscapes];
5913 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5914 href = [href stringByCachingURLWithCurrentCDN];
5916 NSURL *url([NSURL URLWithString:href]);
5918 NSStringEncoding encoding;
5919 NSError *error(nil);
5921 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5922 return [warning length] == 0 ? nil : warning;
5926 - (void) _endConnection:(NSURLConnection *)connection {
5927 // XXX: the memory management in this method is horribly awkward
5929 NSURLConnection **field = NULL;
5930 if (connection == trivial_)
5932 else if (connection == trivial_bz2_)
5933 field = &trivial_bz2_;
5934 else if (connection == trivial_gz_)
5935 field = &trivial_gz_;
5936 _assert(field != NULL);
5937 [connection release];
5942 trivial_bz2_ == nil &&
5948 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5951 UIAlertView *alert = [[[UIAlertView alloc]
5952 initWithTitle:UCLocalize("SOURCE_WARNING")
5955 cancelButtonTitle:UCLocalize("CANCEL")
5956 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5959 [alert setContext:@"warning"];
5960 [alert setNumberOfRows:1];
5964 } else if (error_ != nil) {
5965 UIAlertView *alert = [[[UIAlertView alloc]
5966 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5967 message:[error_ localizedDescription]
5969 cancelButtonTitle:UCLocalize("OK")
5970 otherButtonTitles:nil
5973 [alert setContext:@"urlerror"];
5976 UIAlertView *alert = [[[UIAlertView alloc]
5977 initWithTitle:UCLocalize("NOT_REPOSITORY")
5978 message:UCLocalize("NOT_REPOSITORY_EX")
5980 cancelButtonTitle:UCLocalize("OK")
5981 otherButtonTitles:nil
5984 [alert setContext:@"trivial"];
5988 [delegate_ setStatusBarShowsProgress:NO];
5989 [delegate_ removeProgressHUD:hud_];
5999 if (error_ != nil) {
6006 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6007 switch ([response statusCode]) {
6013 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6014 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6016 error_ = [error retain];
6017 [self _endConnection:connection];
6020 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6021 [self _endConnection:connection];
6024 - (NSString *) title { return UCLocalize("SOURCES"); }
6026 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6027 NSMutableURLRequest *request = [NSMutableURLRequest
6028 requestWithURL:[NSURL URLWithString:href]
6029 cachePolicy:NSURLRequestUseProtocolCachePolicy
6030 timeoutInterval:120.0
6033 [request setHTTPMethod:method];
6035 if (Machine_ != NULL)
6036 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6037 if (UniqueID_ != nil)
6038 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6040 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6042 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6045 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6046 NSString *context([alert context]);
6048 if ([context isEqualToString:@"source"]) {
6051 NSString *href = [[alert textField] text];
6053 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6055 if (![href hasSuffix:@"/"])
6056 href_ = [href stringByAppendingString:@"/"];
6059 href_ = [href_ retain];
6061 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6062 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6063 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6064 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6068 // XXX: this is stupid
6069 hud_ = [[delegate_ addProgressHUD] retain];
6070 [hud_ setText:UCLocalize("VERIFYING_URL")];
6079 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6080 } else if ([context isEqualToString:@"trivial"])
6081 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6082 else if ([context isEqualToString:@"urlerror"])
6083 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6084 else if ([context isEqualToString:@"warning"]) {
6099 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6103 - (id) initWithDatabase:(Database *)database {
6104 if ((self = [super init]) != nil) {
6105 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6106 [self updateButtonsForEditingStatus:NO animated:NO];
6108 database_ = database;
6109 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6111 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6112 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6113 [[self view] addSubview:list_];
6115 [list_ setDataSource:self];
6116 [list_ setDelegate:self];
6122 - (void) reloadData {
6124 if (!list.ReadMainList())
6127 [sources_ removeAllObjects];
6128 [sources_ addObjectsFromArray:[database_ sources]];
6130 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6133 int count([sources_ count]);
6135 for (int i = 0; i != count; i++) {
6136 if ([[sources_ objectAtIndex:i] record] == nil)
6141 [list_ setEditing:NO];
6142 [self updateButtonsForEditingStatus:NO animated:NO];
6146 - (void) addButtonClicked {
6147 /*[book_ pushPage:[[[AddSourceController alloc]
6152 UIAlertView *alert = [[[UIAlertView alloc]
6153 initWithTitle:UCLocalize("ENTER_APT_URL")
6156 cancelButtonTitle:UCLocalize("CANCEL")
6157 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6160 [alert setContext:@"source"];
6161 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6163 [alert setNumberOfRows:1];
6164 [alert addTextFieldWithValue:@"http://" label:@""];
6166 UITextInputTraits *traits = [[alert textField] textInputTraits];
6167 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6168 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6169 [traits setKeyboardType:UIKeyboardTypeURL];
6170 // XXX: UIReturnKeyDone
6171 [traits setReturnKeyType:UIReturnKeyNext];
6176 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6177 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6178 initWithTitle:UCLocalize("ADD")
6179 style:UIBarButtonItemStylePlain
6181 action:@selector(addButtonClicked)
6182 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6184 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6185 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6186 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6188 action:@selector(editButtonClicked)
6189 ] autorelease] animated:animated];
6191 if (IsWildcat_ && !editing)
6192 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6193 initWithTitle:UCLocalize("SETTINGS")
6194 style:UIBarButtonItemStylePlain
6196 action:@selector(settingsButtonClicked)
6200 - (void) settingsButtonClicked {
6201 [delegate_ showSettings];
6204 - (void) editButtonClicked {
6205 [list_ setEditing:![list_ isEditing] animated:YES];
6207 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6213 /* Installed Controller {{{ */
6214 @interface InstalledController : FilteredPackageController {
6218 - (id) initWithDatabase:(Database *)database;
6220 - (void) updateRoleButton;
6221 - (void) queueStatusDidChange;
6225 @implementation InstalledController
6231 - (NSString *) title { return UCLocalize("INSTALLED"); }
6233 - (id) initWithDatabase:(Database *)database {
6234 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6235 [self updateRoleButton];
6236 [self queueStatusDidChange];
6241 - (void) queueButtonClicked {
6246 - (void) queueStatusDidChange {
6250 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6251 initWithTitle:UCLocalize("QUEUE")
6252 style:UIBarButtonItemStyleDone
6254 action:@selector(queueButtonClicked)
6257 [[self navigationItem] setLeftBarButtonItem:nil];
6263 - (void) reloadData {
6264 [packages_ reloadData];
6267 - (void) updateRoleButton {
6268 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6269 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6270 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6271 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6273 action:@selector(roleButtonClicked)
6277 - (void) roleButtonClicked {
6278 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6279 [packages_ reloadData];
6282 [self updateRoleButton];
6285 - (void) setDelegate:(id)delegate {
6286 [super setDelegate:delegate];
6287 [packages_ setDelegate:delegate];
6293 /* Home Controller {{{ */
6294 @interface HomeController : CYBrowserController {
6299 @implementation HomeController
6301 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6302 [super _setMoreHeaders:request];
6305 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6306 if (UniqueID_ != nil)
6307 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6309 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6312 - (void) aboutButtonClicked {
6313 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6315 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6316 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6317 [alert setCancelButtonIndex:0];
6320 @"Copyright (C) 2008-2010\n"
6321 "Jay Freeman (saurik)\n"
6322 "saurik@saurik.com\n"
6323 "http://www.saurik.com/"
6329 - (void) viewWillAppear:(BOOL)animated {
6330 [super viewWillAppear:animated];
6331 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6334 - (void) viewWillDisappear:(BOOL)animated {
6335 [super viewWillDisappear:animated];
6336 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6340 if ((self = [super init]) != nil) {
6341 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6342 initWithTitle:UCLocalize("ABOUT")
6343 style:UIBarButtonItemStylePlain
6345 action:@selector(aboutButtonClicked)
6352 /* Manage Controller {{{ */
6353 @interface ManageController : CYBrowserController {
6356 - (void) queueStatusDidChange;
6359 @implementation ManageController
6362 if ((self = [super init]) != nil) {
6363 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6365 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6366 initWithTitle:UCLocalize("SETTINGS")
6367 style:UIBarButtonItemStylePlain
6369 action:@selector(settingsButtonClicked)
6372 [self queueStatusDidChange];
6376 - (void) settingsButtonClicked {
6377 [delegate_ showSettings];
6381 - (void) queueButtonClicked {
6385 - (void) applyLoadingTitle {
6386 // No "Loading" title.
6389 - (void) applyRightButton {
6394 - (void) queueStatusDidChange {
6396 if (!IsWildcat_ && Queuing_) {
6397 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6398 initWithTitle:UCLocalize("QUEUE")
6399 style:UIBarButtonItemStyleDone
6401 action:@selector(queueButtonClicked)
6404 [[self navigationItem] setRightBarButtonItem:nil];
6409 - (bool) isLoading {
6416 /* Refresh Bar {{{ */
6417 @interface RefreshBar : UINavigationBar {
6418 UIProgressIndicator *indicator_;
6419 UITextLabel *prompt_;
6420 UIProgressBar *progress_;
6421 UINavigationButton *cancel_;
6426 @implementation RefreshBar
6429 [indicator_ release];
6431 [progress_ release];
6436 - (void) positionViews {
6437 CGRect frame = [cancel_ frame];
6438 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6439 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6440 [cancel_ setFrame:frame];
6442 CGSize prgsize = {75, 100};
6444 [self frame].size.width - prgsize.width - 10,
6445 ([self frame].size.height - prgsize.height) / 2
6447 [progress_ setFrame:prgrect];
6449 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6450 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6451 CGRect indrect = {{indoffset, indoffset}, indsize};
6452 [indicator_ setFrame:indrect];
6454 CGSize prmsize = {215, indsize.height + 4};
6456 indoffset * 2 + indsize.width,
6457 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6459 [prompt_ setFrame:prmrect];
6462 - (void)setFrame:(CGRect)frame {
6463 [super setFrame:frame];
6465 [self positionViews];
6468 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6469 if ((self = [super initWithFrame:frame])) {
6470 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6472 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6473 [self setBarStyle:UIBarStyleBlack];
6475 UIBarStyle barstyle([self _barStyle:NO]);
6476 bool ugly(barstyle == UIBarStyleDefault);
6478 UIProgressIndicatorStyle style = ugly ?
6479 UIProgressIndicatorStyleMediumBrown :
6480 UIProgressIndicatorStyleMediumWhite;
6482 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6483 [indicator_ setStyle:style];
6484 [indicator_ startAnimation];
6485 [self addSubview:indicator_];
6487 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6488 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6489 [prompt_ setBackgroundColor:[UIColor clearColor]];
6490 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6491 [self addSubview:prompt_];
6493 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6494 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6495 [progress_ setStyle:0];
6496 [self addSubview:progress_];
6498 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6499 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6500 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6501 [cancel_ setBarStyle:barstyle];
6503 [self positionViews];
6508 [cancel_ removeFromSuperview];
6512 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6513 [progress_ setProgress:0];
6514 [self addSubview:cancel_];
6518 [cancel_ removeFromSuperview];
6521 - (void) setPrompt:(NSString *)prompt {
6522 [prompt_ setText:prompt];
6525 - (void) setProgress:(float)progress {
6526 [progress_ setProgress:progress];
6532 @class CYNavigationController;
6534 /* Cydia Tab Bar Controller {{{ */
6535 @interface CYTabBarController : UITabBarController {
6536 _transient Database *database_;
6541 @implementation CYTabBarController
6543 /* XXX: some logic should probably go here related to
6544 freeing the view controllers on tab change */
6546 - (void) reloadData {
6547 size_t count([[self viewControllers] count]);
6548 for (size_t i(0); i != count; ++i) {
6549 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6554 - (id) initWithDatabase:(Database *)database {
6555 if ((self = [super init]) != nil) {
6556 database_ = database;
6563 /* Cydia Navigation Controller {{{ */
6564 @interface CYNavigationController : UINavigationController {
6565 _transient Database *database_;
6566 _transient id<UINavigationControllerDelegate> delegate_;
6569 - (id) initWithDatabase:(Database *)database;
6570 - (void) reloadData;
6575 @implementation CYNavigationController
6577 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6578 // Inherit autorotation settings for modal parents.
6579 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6580 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6582 return [super shouldAutorotateToInterfaceOrientation:orientation];
6590 - (void) reloadData {
6591 size_t count([[self viewControllers] count]);
6592 for (size_t i(0); i != count; ++i) {
6593 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6598 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6599 delegate_ = delegate;
6602 - (id) initWithDatabase:(Database *)database {
6603 if ((self = [super init]) != nil) {
6604 database_ = database;
6610 /* Cydia:// Protocol {{{ */
6611 @interface CydiaURLProtocol : NSURLProtocol {
6616 @implementation CydiaURLProtocol
6618 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6619 NSURL *url([request URL]);
6622 NSString *scheme([[url scheme] lowercaseString]);
6623 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6628 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6632 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6633 id<NSURLProtocolClient> client([self client]);
6635 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6637 NSData *data(UIImagePNGRepresentation(icon));
6639 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6640 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6641 [client URLProtocol:self didLoadData:data];
6642 [client URLProtocolDidFinishLoading:self];
6646 - (void) startLoading {
6647 id<NSURLProtocolClient> client([self client]);
6648 NSURLRequest *request([self request]);
6650 NSURL *url([request URL]);
6651 NSString *href([url absoluteString]);
6653 NSString *path([href substringFromIndex:8]);
6654 NSRange slash([path rangeOfString:@"/"]);
6657 if (slash.location == NSNotFound) {
6661 command = [path substringToIndex:slash.location];
6662 path = [path substringFromIndex:(slash.location + 1)];
6665 Database *database([Database sharedInstance]);
6667 if ([command isEqualToString:@"package-icon"]) {
6670 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6671 Package *package([database packageWithName:path]);
6674 UIImage *icon([package icon]);
6675 [self _returnPNGWithImage:icon forRequest:request];
6676 } else if ([command isEqualToString:@"source-icon"]) {
6679 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6680 NSString *source(Simplify(path));
6681 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6683 icon = [UIImage applicationImageNamed:@"unknown.png"];
6684 [self _returnPNGWithImage:icon forRequest:request];
6685 } else if ([command isEqualToString:@"uikit-image"]) {
6688 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6689 UIImage *icon(_UIImageWithName(path));
6690 [self _returnPNGWithImage:icon forRequest:request];
6691 } else if ([command isEqualToString:@"section-icon"]) {
6694 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6695 NSString *section(Simplify(path));
6696 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6698 icon = [UIImage applicationImageNamed:@"unknown.png"];
6699 [self _returnPNGWithImage:icon forRequest:request];
6701 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6705 - (void) stopLoading {
6711 /* Sections Controller {{{ */
6712 @interface SectionsController : CYViewController <
6713 UITableViewDataSource,
6716 _transient Database *database_;
6717 NSMutableArray *sections_;
6718 NSMutableArray *filtered_;
6724 - (id) initWithDatabase:(Database *)database;
6725 - (void) reloadData;
6728 - (void) editButtonClicked;
6732 @implementation SectionsController
6735 [list_ setDataSource:nil];
6736 [list_ setDelegate:nil];
6738 [sections_ release];
6739 [filtered_ release];
6741 [accessory_ release];
6745 - (void) viewDidAppear:(BOOL)animated {
6746 [super viewDidAppear:animated];
6747 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6750 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6751 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6755 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6756 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6759 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6763 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6764 static NSString *reuseIdentifier = @"SectionCell";
6766 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6768 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6770 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6775 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6779 Section *section = [self sectionAtIndexPath:indexPath];
6780 NSString *name = [section name];
6783 if ([indexPath row] == 0) {
6786 title = UCLocalize("ALL_PACKAGES");
6789 name = [NSString stringWithString:name];
6790 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6793 title = UCLocalize("NO_SECTION");
6797 FilteredPackageController *table = [[[FilteredPackageController alloc]
6798 initWithDatabase:database_
6800 filter:@selector(isVisibleInSection:)
6804 [table setDelegate:delegate_];
6806 [[self navigationController] pushViewController:table animated:YES];
6809 - (NSString *) title { return UCLocalize("SECTIONS"); }
6811 - (id) initWithDatabase:(Database *)database {
6812 if ((self = [super init]) != nil) {
6813 database_ = database;
6815 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6817 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6818 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6820 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6821 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6822 [list_ setRowHeight:45.0f];
6823 [[self view] addSubview:list_];
6825 [list_ setDataSource:self];
6826 [list_ setDelegate:self];
6832 - (void) reloadData {
6833 NSArray *packages = [database_ packages];
6835 [sections_ removeAllObjects];
6836 [filtered_ removeAllObjects];
6839 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6840 SectionMap sections;
6841 sections.resize(64);
6843 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6847 for (Package *package in packages) {
6848 NSString *name([package section]);
6849 NSString *key(name == nil ? @"" : name);
6854 _profile(SectionsView$reloadData$Section)
6855 section = §ions[key];
6856 if (*section == nil) {
6857 _profile(SectionsView$reloadData$Section$Allocate)
6858 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6863 [*section addToCount];
6865 _profile(SectionsView$reloadData$Filter)
6866 if (![package valid] || ![package visible])
6870 [*section addToRow];
6874 _profile(SectionsView$reloadData$Section)
6875 section = [sections objectForKey:key];
6876 if (section == nil) {
6877 _profile(SectionsView$reloadData$Section$Allocate)
6878 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6879 [sections setObject:section forKey:key];
6884 [section addToCount];
6886 _profile(SectionsView$reloadData$Filter)
6887 if (![package valid] || ![package visible])
6897 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6898 [sections_ addObject:i->second];
6900 [sections_ addObjectsFromArray:[sections allValues]];
6903 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6905 for (Section *section in sections_) {
6906 size_t count([section row]);
6910 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6911 [section setCount:count];
6912 [filtered_ addObject:section];
6915 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6916 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
6917 style:UIBarButtonItemStylePlain
6919 action:@selector(editButtonClicked)
6920 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6926 - (void) resetView {
6928 [self editButtonClicked];
6931 - (void) editButtonClicked {
6932 if ((editing_ = !editing_))
6935 [delegate_ updateData];
6937 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6938 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6939 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6942 - (UIView *) accessoryView {
6948 /* Changes Controller {{{ */
6949 @interface ChangesController : CYViewController <
6950 UITableViewDataSource,
6953 _transient Database *database_;
6954 CFMutableArrayRef packages_;
6955 NSMutableArray *sections_;
6958 BOOL hasSentFirstLoad_;
6961 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6962 - (void) reloadData;
6966 @implementation ChangesController
6969 [list_ setDelegate:nil];
6970 [list_ setDataSource:nil];
6972 CFRelease(packages_);
6974 [sections_ release];
6979 - (void) viewDidAppear:(BOOL)animated {
6980 [super viewDidAppear:animated];
6981 if (!hasSentFirstLoad_) {
6982 hasSentFirstLoad_ = YES;
6983 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6985 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6989 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6990 NSInteger count([sections_ count]);
6991 return count == 0 ? 1 : count;
6994 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6995 if ([sections_ count] == 0)
6997 return [[sections_ objectAtIndex:section] name];
7000 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7001 if ([sections_ count] == 0)
7003 return [[sections_ objectAtIndex:section] count];
7006 - (Package *) packageAtIndex:(NSUInteger)index {
7007 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7010 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7011 Section *section([sections_ objectAtIndex:[path section]]);
7012 NSInteger row([path row]);
7013 return [self packageAtIndex:([section row] + row)];
7016 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7017 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7019 cell = [[[PackageCell alloc] init] autorelease];
7020 [cell setPackage:[self packageAtIndexPath:path]];
7024 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7025 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7028 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7029 Package *package([self packageAtIndexPath:path]);
7030 PackageController *view([delegate_ packageController]);
7031 [view setDelegate:delegate_];
7032 [view setPackage:package];
7033 [[self navigationController] pushViewController:view animated:YES];
7037 - (void) refreshButtonClicked {
7038 [delegate_ beginUpdate];
7039 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7042 - (void) upgradeButtonClicked {
7043 [delegate_ distUpgrade];
7046 - (NSString *) title { return UCLocalize("CHANGES"); }
7048 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7049 if ((self = [super init]) != nil) {
7050 database_ = database;
7051 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7053 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7055 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7057 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7058 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7059 [list_ setRowHeight:73.0f];
7060 [[self view] addSubview:list_];
7062 [list_ setDataSource:self];
7063 [list_ setDelegate:self];
7065 delegate_ = delegate;
7069 - (void) _reloadPackages:(NSArray *)packages {
7071 for (Package *package in packages)
7073 [package uninstalled] && [package valid] && [package visible] ||
7074 [package upgradableAndEssential:YES]
7076 CFArrayAppendValue(packages_, package);
7079 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7083 - (void) reloadData {
7084 NSArray *packages = [database_ packages];
7086 CFArrayRemoveAllValues(packages_);
7088 [sections_ removeAllObjects];
7091 UIProgressHUD *hud([delegate_ addProgressHUD]);
7093 [hud setText:@"Loading Changes"];
7094 //NSLog(@"HUD:%@::%@", delegate_, hud);
7095 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7096 [delegate_ removeProgressHUD:hud];
7098 [self _reloadPackages:packages];
7101 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7102 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7103 Section *section = nil;
7107 bool unseens = false;
7109 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7111 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7112 Package *package = [self packageAtIndex:offset];
7114 BOOL uae = [package upgradableAndEssential:YES];
7120 _profile(ChangesController$reloadData$Remember)
7121 seen = [package seen];
7124 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7129 name = UCLocalize("UNKNOWN");
7131 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7135 _profile(ChangesController$reloadData$Allocate)
7136 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7137 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7138 [sections_ addObject:section];
7142 [section addToCount];
7143 } else if ([package ignored])
7144 [ignored addToCount];
7147 [upgradable addToCount];
7152 CFRelease(formatter);
7155 Section *last = [sections_ lastObject];
7156 size_t count = [last count];
7157 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7158 [sections_ removeLastObject];
7161 if ([ignored count] != 0)
7162 [sections_ insertObject:ignored atIndex:0];
7164 [sections_ insertObject:upgradable atIndex:0];
7169 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7170 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7171 style:UIBarButtonItemStylePlain
7173 action:@selector(upgradeButtonClicked)
7176 if (![delegate_ updating])
7177 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7178 initWithTitle:UCLocalize("REFRESH")
7179 style:UIBarButtonItemStylePlain
7181 action:@selector(refreshButtonClicked)
7187 /* Search Controller {{{ */
7188 @interface SearchController : FilteredPackageController <
7191 UISearchBar *search_;
7194 - (id) initWithDatabase:(Database *)database;
7195 - (void) reloadData;
7199 @implementation SearchController
7206 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7207 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7208 [search_ resignFirstResponder];
7212 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7213 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7217 - (NSString *) title { return nil; }
7219 - (id) initWithDatabase:(Database *)database {
7220 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7223 - (void)viewDidAppear:(BOOL)animated {
7224 [super viewDidAppear:animated];
7226 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7227 [search_ layoutSubviews];
7228 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7229 UITextField *textField = [search_ searchField];
7230 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7231 [search_ setDelegate:self];
7232 [textField setEnablesReturnKeyAutomatically:NO];
7233 [[self navigationItem] setTitleView:textField];
7237 - (void) _reloadData {
7240 - (void) reloadData {
7241 _profile(SearchController$reloadData)
7242 [packages_ reloadData];
7245 [packages_ resetCursor];
7248 - (void) didSelectPackage:(Package *)package {
7249 [search_ resignFirstResponder];
7250 [super didSelectPackage:package];
7255 /* Settings Controller {{{ */
7256 @interface SettingsController : CYViewController <
7257 UITableViewDataSource,
7260 _transient Database *database_;
7263 UITableView *table_;
7264 UISwitch *subscribedSwitch_;
7265 UISwitch *ignoredSwitch_;
7266 UITableViewCell *subscribedCell_;
7267 UITableViewCell *ignoredCell_;
7270 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7274 @implementation SettingsController
7278 if (package_ != nil)
7281 [subscribedSwitch_ release];
7282 [ignoredSwitch_ release];
7283 [subscribedCell_ release];
7284 [ignoredCell_ release];
7289 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7290 if (package_ == nil)
7296 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7297 if (package_ == nil)
7303 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7304 return UCLocalize("SHOW_ALL_CHANGES_EX");
7307 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7308 if (package_ == nil)
7311 NSMutableDictionary *metadata([package_ metadata]);
7314 if (NSNumber *number = [metadata objectForKey:key])
7315 before = [number boolValue];
7319 if (value != before) {
7320 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7322 [delegate_ updateData];
7326 - (void) onSubscribed:(id)control {
7327 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7330 - (void) onIgnored:(id)control {
7331 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
7334 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7335 if (package_ == nil)
7338 switch ([indexPath row]) {
7339 case 0: return subscribedCell_;
7340 case 1: return ignoredCell_;
7348 - (NSString *) title { return UCLocalize("SETTINGS"); }
7350 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7351 if ((self = [super init])) {
7352 database_ = database;
7353 name_ = [package retain];
7355 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7357 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7358 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7359 [[self view] addSubview:table_];
7361 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7362 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7363 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7365 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7366 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7367 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7369 subscribedCell_ = [[UITableViewCell alloc] init];
7370 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7371 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7372 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7374 ignoredCell_ = [[UITableViewCell alloc] init];
7375 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7376 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7377 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7379 [table_ setDataSource:self];
7380 [table_ setDelegate:self];
7385 - (void) reloadData {
7386 if (package_ != nil)
7387 [package_ autorelease];
7388 package_ = [database_ packageWithName:name_];
7389 if (package_ != nil) {
7391 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7392 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7395 [table_ reloadData];
7400 /* Signature Controller {{{ */
7401 @interface SignatureController : CYBrowserController {
7402 _transient Database *database_;
7406 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7410 @implementation SignatureController
7417 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7419 [super webView:view didClearWindowObject:window forFrame:frame];
7422 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7423 if ((self = [super init]) != nil) {
7424 database_ = database;
7425 package_ = [package retain];
7430 - (void) reloadData {
7431 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7437 /* Role Controller {{{ */
7438 @interface RoleController : CYViewController <
7439 UITableViewDataSource,
7442 _transient Database *database_;
7443 // XXX: ok, "roledelegate_"?...
7444 _transient id roledelegate_;
7445 UITableView *table_;
7446 UISegmentedControl *segment_;
7450 - (void) showDoneButton;
7451 - (void) resizeSegmentedControl;
7455 @implementation RoleController
7459 [container_ release];
7464 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7465 if ((self = [super init])) {
7466 database_ = database;
7467 roledelegate_ = delegate;
7469 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7471 NSArray *items = [NSArray arrayWithObjects:
7473 UCLocalize("HACKER"),
7474 UCLocalize("DEVELOPER"),
7476 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7477 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7478 [container_ addSubview:segment_];
7481 if ([Role_ isEqualToString:@"User"]) index = 0;
7482 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7483 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7485 [segment_ setSelectedSegmentIndex:index];
7486 [self showDoneButton];
7489 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7490 [self resizeSegmentedControl];
7492 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7493 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7494 [table_ setDelegate:self];
7495 [table_ setDataSource:self];
7496 [[self view] addSubview:table_];
7497 [table_ reloadData];
7501 - (void) resizeSegmentedControl {
7502 CGFloat width = [[self view] frame].size.width;
7503 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7506 - (void) viewWillAppear:(BOOL)animated {
7507 [super viewWillAppear:animated];
7509 [self resizeSegmentedControl];
7512 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7513 [self resizeSegmentedControl];
7516 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7517 [self resizeSegmentedControl];
7521 NSString *role(nil);
7523 switch ([segment_ selectedSegmentIndex]) {
7524 case 0: role = @"User"; break;
7525 case 1: role = @"Hacker"; break;
7526 case 2: role = @"Developer"; break;
7531 if (![role isEqualToString:Role_]) {
7532 bool rolling(Role_ == nil);
7535 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7539 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7544 [roledelegate_ loadData];
7546 [roledelegate_ updateData];
7550 - (void) segmentChanged:(UISegmentedControl *)control {
7551 [self showDoneButton];
7554 - (void) saveAndClose {
7557 [[self navigationItem] setRightBarButtonItem:nil];
7558 [[self navigationController] dismissModalViewControllerAnimated:YES];
7561 - (void) doneButtonClicked {
7562 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7563 [spinner startAnimating];
7564 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7565 [[self navigationItem] setRightBarButtonItem:spinItem];
7567 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7570 - (void) showDoneButton {
7571 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7572 initWithTitle:UCLocalize("DONE")
7573 style:UIBarButtonItemStyleDone
7575 action:@selector(doneButtonClicked)
7576 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
7579 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7580 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7584 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7588 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7589 return nil; // This method is required by the protocol.
7592 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7594 return UCLocalize("ROLE_EX");
7596 return [NSString stringWithFormat:
7597 @"%@: %@\n%@: %@\n%@: %@",
7598 UCLocalize("USER"), UCLocalize("USER_EX"),
7599 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7600 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7605 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7606 return section == 3 ? 44.0f : 0;
7609 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7610 return section == 3 ? container_ : nil;
7615 /* Stash Controller {{{ */
7616 @interface CYStashController : CYViewController {
7617 // XXX: just delete these things
7618 _transient UIActivityIndicatorView *spinner_;
7619 _transient UILabel *status_;
7620 _transient UILabel *caption_;
7624 @implementation CYStashController
7626 if ((self = [super init])) {
7627 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7629 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
7630 CGRect spinrect = [spinner_ frame];
7631 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7632 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7633 [spinner_ setFrame:spinrect];
7634 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7635 [[self view] addSubview:spinner_];
7636 [spinner_ startAnimating];
7639 captrect.size.width = [[self view] frame].size.width;
7640 captrect.size.height = 40.0f;
7641 captrect.origin.x = 0;
7642 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7643 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
7644 [caption_ setText:@"Initializing Filesystem"];
7645 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7646 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7647 [caption_ setTextColor:[UIColor whiteColor]];
7648 [caption_ setBackgroundColor:[UIColor clearColor]];
7649 [caption_ setShadowColor:[UIColor blackColor]];
7650 [caption_ setTextAlignment:UITextAlignmentCenter];
7651 [[self view] addSubview:caption_];
7654 statusrect.size.width = [[self view] frame].size.width;
7655 statusrect.size.height = 30.0f;
7656 statusrect.origin.x = 0;
7657 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7658 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
7659 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7660 [status_ setText:@"(Cydia will exit when complete.)"];
7661 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7662 [status_ setTextColor:[UIColor whiteColor]];
7663 [status_ setBackgroundColor:[UIColor clearColor]];
7664 [status_ setShadowColor:[UIColor blackColor]];
7665 [status_ setTextAlignment:UITextAlignmentCenter];
7666 [[self view] addSubview:status_];
7670 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7671 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7676 /* Cydia Container {{{ */
7677 @interface CYContainer : UIViewController <ProgressDelegate> {
7678 _transient Database *database_;
7679 RefreshBar *refreshbar_;
7683 // XXX: ok, "updatedelegate_"?...
7684 _transient NSObject<CydiaDelegate> *updatedelegate_;
7685 // XXX: can't we query for this variable when we need it?
7686 _transient UITabBarController *root_;
7689 - (void) setTabBarController:(UITabBarController *)controller;
7691 - (void) dropBar:(BOOL)animated;
7692 - (void) beginUpdate;
7693 - (void) raiseBar:(BOOL)animated;
7698 @implementation CYContainer
7700 - (BOOL) _reallyWantsFullScreenLayout {
7704 // NOTE: UIWindow only sends the top controller these messages,
7705 // So we have to forward them on.
7707 - (void) viewDidAppear:(BOOL)animated {
7708 [super viewDidAppear:animated];
7709 [root_ viewDidAppear:animated];
7712 - (void) viewWillAppear:(BOOL)animated {
7713 [super viewWillAppear:animated];
7714 [root_ viewWillAppear:animated];
7717 - (void) viewDidDisappear:(BOOL)animated {
7718 [super viewDidDisappear:animated];
7719 [root_ viewDidDisappear:animated];
7722 - (void) viewWillDisappear:(BOOL)animated {
7723 [super viewWillDisappear:animated];
7724 [root_ viewWillDisappear:animated];
7727 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7728 return ![updatedelegate_ hudIsShowing] && (IsWildcat_ || orientation == UIInterfaceOrientationPortrait);
7731 - (void) setTabBarController:(UITabBarController *)controller {
7733 [[self view] addSubview:[root_ view]];
7736 - (void) setUpdate:(NSDate *)date {
7740 - (void) beginUpdate {
7742 [refreshbar_ start];
7747 detachNewThreadSelector:@selector(performUpdate)
7753 - (void) performUpdate { _pooled
7755 status.setDelegate(self);
7756 [database_ updateWithStatus:status];
7759 performSelectorOnMainThread:@selector(completeUpdate)
7765 - (void) completeUpdate {
7770 [self raiseBar:YES];
7772 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7775 - (void) cancelUpdate {
7777 [self raiseBar:YES];
7779 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7782 - (void) cancelPressed {
7783 [self cancelUpdate];
7790 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7791 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7794 - (void) startProgress {
7797 - (void) setProgressTitle:(NSString *)title {
7799 performSelectorOnMainThread:@selector(_setProgressTitle:)
7805 - (bool) isCancelling:(size_t)received {
7809 - (void) setProgressPercent:(float)percent {
7811 performSelectorOnMainThread:@selector(_setProgressPercent:)
7812 withObject:[NSNumber numberWithFloat:percent]
7817 - (void) addProgressOutput:(NSString *)output {
7819 performSelectorOnMainThread:@selector(_addProgressOutput:)
7825 - (void) _setProgressTitle:(NSString *)title {
7826 [refreshbar_ setPrompt:title];
7829 - (void) _setProgressPercent:(NSNumber *)percent {
7830 [refreshbar_ setProgress:[percent floatValue]];
7833 - (void) _addProgressOutput:(NSString *)output {
7836 - (void) setUpdateDelegate:(id)delegate {
7837 updatedelegate_ = delegate;
7840 - (CGFloat) statusBarHeight {
7841 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7842 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7844 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7848 - (void) dropBar:(BOOL)animated {
7853 [[self view] addSubview:refreshbar_];
7855 CGFloat sboffset = [self statusBarHeight];
7857 CGRect barframe = [refreshbar_ frame];
7858 barframe.origin.y = sboffset;
7859 [refreshbar_ setFrame:barframe];
7862 [UIView beginAnimations:nil context:NULL];
7863 CGRect viewframe = [[root_ view] frame];
7864 viewframe.origin.y += barframe.size.height + sboffset;
7865 viewframe.size.height -= barframe.size.height + sboffset;
7866 [[root_ view] setFrame:viewframe];
7868 [UIView commitAnimations];
7870 // Ensure bar has the proper width for our view, it might have changed
7871 barframe.size.width = viewframe.size.width;
7872 [refreshbar_ setFrame:barframe];
7874 // XXX: fix Apple's layout bug
7875 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7878 - (void) raiseBar:(BOOL)animated {
7883 [refreshbar_ removeFromSuperview];
7885 CGFloat sboffset = [self statusBarHeight];
7888 [UIView beginAnimations:nil context:NULL];
7889 CGRect barframe = [refreshbar_ frame];
7890 CGRect viewframe = [[root_ view] frame];
7891 viewframe.origin.y -= barframe.size.height + sboffset;
7892 viewframe.size.height += barframe.size.height + sboffset;
7893 [[root_ view] setFrame:viewframe];
7895 [UIView commitAnimations];
7897 // XXX: fix Apple's layout bug
7898 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7901 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7902 // XXX: fix Apple's layout bug
7903 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7906 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7912 // XXX: fix Apple's layout bug
7913 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7916 - (void) statusBarFrameChanged:(NSNotification *)notification {
7924 [refreshbar_ release];
7925 [[NSNotificationCenter defaultCenter] removeObserver:self];
7929 - (id) initWithDatabase:(Database *)database {
7930 if ((self = [super init]) != nil) {
7931 database_ = database;
7933 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7934 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7936 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7953 @interface Cydia : UIApplication <
7954 ConfirmationControllerDelegate,
7955 ProgressControllerDelegate,
7957 UINavigationControllerDelegate,
7958 UITabBarControllerDelegate
7960 // XXX: evaluate all fields for _transient
7963 CYContainer *container_;
7964 CYTabBarController *tabbar_;
7966 NSMutableArray *essential_;
7967 NSMutableArray *broken_;
7969 Database *database_;
7973 UIKeyboard *keyboard_;
7976 SectionsController *sections_;
7977 ChangesController *changes_;
7978 ManageController *manage_;
7979 SearchController *search_;
7980 SourceTable *sources_;
7981 InstalledController *installed_;
7984 CYStashController *stash_;
7989 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7990 - (void) setPage:(CYViewController *)page;
7995 static _finline void _setHomePage(Cydia *self) {
7996 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7999 @implementation Cydia
8001 - (void) beginUpdate {
8002 [container_ beginUpdate];
8006 return [container_ updating];
8009 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
8014 if ([broken_ count] != 0) {
8015 int count = [broken_ count];
8017 UIAlertView *alert = [[[UIAlertView alloc]
8018 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8019 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8021 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8022 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8025 [alert setContext:@"fixhalf"];
8027 } else if (!Ignored_ && [essential_ count] != 0) {
8028 int count = [essential_ count];
8030 UIAlertView *alert = [[[UIAlertView alloc]
8031 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8032 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8034 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8035 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8038 [alert setContext:@"upgrade"];
8043 - (void) _saveConfig {
8046 NSString *error(nil);
8047 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8049 NSError *error(nil);
8050 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8051 NSLog(@"failure to save metadata data: %@", error);
8054 NSLog(@"failure to serialize metadata: %@", error);
8062 - (void) _updateData {
8065 /* XXX: this is just stupid */
8066 if (tag_ != 1 && sections_ != nil)
8067 [sections_ reloadData];
8068 if (tag_ != 2 && changes_ != nil)
8069 [changes_ reloadData];
8070 if (tag_ != 4 && search_ != nil)
8071 [search_ reloadData];
8073 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8076 - (int)indexOfTabWithTag:(int)tag {
8078 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8079 if ([[controller tabBarItem] tag] == tag)
8087 - (void) _refreshIfPossible {
8088 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8090 bool recently = false;
8091 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8092 if (update != nil) {
8093 NSTimeInterval interval([update timeIntervalSinceNow]);
8094 if (interval <= 0 && interval > -(15*60))
8098 // Don't automatic refresh if:
8099 // - We already refreshed recently.
8100 // - We already auto-refreshed this launch.
8101 // - Auto-refresh is disabled.
8102 if (recently || loaded_ || ManualRefresh) {
8103 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8105 // If we are cancelling due to ManualRefresh or a recent refresh
8106 // we need to make sure it knows it's already loaded.
8110 // We are going to load, so remember that.
8114 SCNetworkReachabilityFlags flags; {
8115 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8116 SCNetworkReachabilityGetFlags(reachability, &flags);
8117 CFRelease(reachability);
8120 // XXX: this elaborate mess is what Apple is using to determine this? :(
8121 // XXX: do we care if the user has to intervene? maybe that's ok?
8123 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8124 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8125 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8126 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8127 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8128 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8132 // If we can reach the server, auto-refresh!
8134 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8139 - (void) refreshIfPossible {
8140 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8143 - (void) _reloadData {
8144 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8145 [hud setText:UCLocalize("RELOADING_DATA")];
8147 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8150 [self removeProgressHUD:hud];
8154 [essential_ removeAllObjects];
8155 [broken_ removeAllObjects];
8157 NSArray *packages([database_ packages]);
8158 for (Package *package in packages) {
8160 [broken_ addObject:package];
8161 if ([package upgradableAndEssential:NO]) {
8162 if ([package essential])
8163 [essential_ addObject:package];
8168 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8170 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8171 [changesItem setBadgeValue:badge];
8172 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8174 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8175 [self setApplicationBadge:badge];
8177 [self setApplicationBadgeString:badge];
8179 [changesItem setBadgeValue:nil];
8180 [changesItem setAnimatedBadge:NO];
8182 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8183 [self removeApplicationBadge];
8184 else // XXX: maybe use setApplicationBadgeString also?
8185 [self setApplicationIconBadgeNumber:0];
8190 [self refreshIfPossible];
8193 - (void) updateData {
8194 [database_ setVisible];
8203 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8204 _assert(file != NULL);
8206 for (NSString *key in [Sources_ allKeys]) {
8207 NSDictionary *source([Sources_ objectForKey:key]);
8209 fprintf(file, "%s %s %s\n",
8210 [[source objectForKey:@"Type"] UTF8String],
8211 [[source objectForKey:@"URI"] UTF8String],
8212 [[source objectForKey:@"Distribution"] UTF8String]
8220 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8221 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8223 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8224 [container_ presentModalViewController:navigation animated:YES];
8227 detachNewThreadSelector:@selector(update_)
8230 title:UCLocalize("UPDATING_SOURCES")
8234 - (void) reloadData {
8235 @synchronized (self) {
8241 pkgProblemResolver *resolver = [database_ resolver];
8243 resolver->InstallProtect();
8244 if (!resolver->Resolve(true))
8248 - (CGRect) popUpBounds {
8249 return [[tabbar_ view] bounds];
8253 if (![database_ prepare])
8256 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8257 [page setDelegate:self];
8258 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8259 [confirm_ setDelegate:self];
8262 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8263 [container_ presentModalViewController:confirm_ animated:YES];
8269 @synchronized (self) {
8274 - (void) clearPackage:(Package *)package {
8275 @synchronized (self) {
8282 - (void) installPackages:(NSArray *)packages {
8283 @synchronized (self) {
8284 for (Package *package in packages)
8291 - (void) installPackage:(Package *)package {
8292 @synchronized (self) {
8299 - (void) removePackage:(Package *)package {
8300 @synchronized (self) {
8307 - (void) distUpgrade {
8308 @synchronized (self) {
8309 if (![database_ upgrade])
8316 @synchronized (self) {
8321 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8322 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8324 if (navigation != nil) {
8325 [navigation pushViewController:progress animated:YES];
8327 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8329 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8330 [container_ presentModalViewController:navigation animated:YES];
8334 detachNewThreadSelector:@selector(perform)
8337 title:UCLocalize("RUNNING")
8341 - (void) progressControllerIsComplete:(ProgressController *)progress {
8345 - (void) setPage:(CYViewController *)page {
8346 [page setDelegate:self];
8348 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8349 [navController setViewControllers:[NSArray arrayWithObject:page]];
8350 for (CYNavigationController *page in [tabbar_ viewControllers])
8351 if (page != navController)
8352 [page setViewControllers:nil];
8355 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8356 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8357 [browser loadURL:url];
8361 - (SectionsController *) sectionsController {
8362 if (sections_ == nil)
8363 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8367 - (ChangesController *) changesController {
8368 if (changes_ == nil)
8369 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8373 - (ManageController *) manageController {
8374 if (manage_ == nil) {
8375 manage_ = (ManageController *) [[self
8376 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8377 withClass:[ManageController class]
8380 queueDelegate_ = manage_;
8385 - (SearchController *) searchController {
8387 search_ = [[SearchController alloc] initWithDatabase:database_];
8391 - (SourceTable *) sourcesController {
8392 if (sources_ == nil)
8393 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8397 - (InstalledController *) installedController {
8398 if (installed_ == nil) {
8399 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8401 queueDelegate_ = installed_;
8406 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8407 int tag = [[viewController tabBarItem] tag];
8409 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8411 } else if (tag_ == 1) {
8412 [[self sectionsController] resetView];
8416 case kCydiaTag: _setHomePage(self); break;
8418 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8419 case kChangesTag: [self setPage:[self changesController]]; break;
8420 case kManageTag: [self setPage:[self manageController]]; break;
8421 case kInstalledTag: [self setPage:[self installedController]]; break;
8422 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8423 case kSearchTag: [self setPage:[self searchController]]; break;
8431 - (void) showSettings {
8432 RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease];
8433 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8435 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8436 [container_ presentModalViewController:nav animated:YES];
8439 - (void) setPackageController:(PackageController *)view {
8441 [view setPackage:nil];
8445 - (PackageController *) _packageController {
8446 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8449 - (PackageController *) packageController {
8450 return [self _packageController];
8453 // Returns the navigation controller for the queuing badge.
8454 - (id) queueBadgeController {
8455 int index = [self indexOfTabWithTag:kManageTag];
8457 index = [self indexOfTabWithTag:kInstalledTag];
8459 return [[tabbar_ viewControllers] objectAtIndex:index];
8462 - (void) cancelAndClear:(bool)clear {
8463 @synchronized (self) {
8469 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
8473 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8477 [queueDelegate_ queueStatusDidChange];
8481 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8482 NSString *context([alert context]);
8484 if ([context isEqualToString:@"fixhalf"]) {
8485 if (button == [alert firstOtherButtonIndex]) {
8486 @synchronized (self) {
8487 for (Package *broken in broken_) {
8490 NSString *id = [broken id];
8491 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8492 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8493 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8494 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8500 } else if (button == [alert cancelButtonIndex]) {
8501 [broken_ removeAllObjects];
8505 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8506 } else if ([context isEqualToString:@"upgrade"]) {
8507 if (button == [alert firstOtherButtonIndex]) {
8508 @synchronized (self) {
8509 for (Package *essential in essential_)
8510 [essential install];
8515 } else if (button == [alert firstOtherButtonIndex] + 1) {
8517 } else if (button == [alert cancelButtonIndex]) {
8521 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8525 - (void) system:(NSString *)command { _pooled
8526 system([command UTF8String]);
8529 - (void) applicationWillSuspend {
8531 [super applicationWillSuspend];
8534 - (BOOL) hudIsShowing {
8538 - (void) applicationSuspend:(__GSEvent *)event {
8539 // Use external process status API internally.
8540 // This is probably a really bad idea.
8541 uint64_t status = 0;
8543 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8544 notify_get_state(notify_token, &status);
8545 notify_cancel(notify_token);
8548 if (![self hudIsShowing] && status == 0)
8549 [super applicationSuspend:event];
8552 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8553 if (![self hudIsShowing])
8554 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8557 - (void) _setSuspended:(BOOL)value {
8558 if (![self hudIsShowing])
8559 [super _setSuspended:value];
8562 - (UIProgressHUD *) addProgressHUD {
8563 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8564 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8566 [window_ setUserInteractionEnabled:NO];
8569 UIViewController *target = container_;
8570 while ([target modalViewController] != nil) target = [target modalViewController];
8571 [[target view] addSubview:hud];
8577 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8579 [hud removeFromSuperview];
8580 [window_ setUserInteractionEnabled:YES];
8584 - (CYViewController *) pageForPackage:(NSString *)name {
8585 if (Package *package = [database_ packageWithName:name]) {
8586 PackageController *view([self packageController]);
8587 [view setPackage:package];
8590 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8591 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8592 return [self _pageForURL:url withClass:[CYBrowserController class]];
8596 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8600 NSString *href([url absoluteString]);
8601 if ([href hasPrefix:@"apptapp://package/"])
8602 return [self pageForPackage:[href substringFromIndex:18]];
8604 NSString *scheme([[url scheme] lowercaseString]);
8605 if (![scheme isEqualToString:@"cydia"])
8607 NSString *path([url absoluteString]);
8608 if ([path length] < 8)
8610 path = [path substringFromIndex:8];
8611 if (![path hasPrefix:@"/"])
8612 path = [@"/" stringByAppendingString:path];
8614 if ([path isEqualToString:@"/add-source"])
8615 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8616 else if ([path isEqualToString:@"/storage"])
8617 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8618 else if ([path isEqualToString:@"/sources"])
8619 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8620 else if ([path isEqualToString:@"/packages"])
8621 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8622 else if ([path hasPrefix:@"/url/"])
8623 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8624 else if ([path hasPrefix:@"/launch/"])
8625 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8626 else if ([path hasPrefix:@"/package-settings/"])
8627 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8628 else if ([path hasPrefix:@"/package-signature/"])
8629 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8630 else if ([path hasPrefix:@"/package/"])
8631 return [self pageForPackage:[path substringFromIndex:9]];
8632 else if ([path hasPrefix:@"/files/"]) {
8633 NSString *name = [path substringFromIndex:7];
8635 if (Package *package = [database_ packageWithName:name]) {
8636 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8637 [files setPackage:package];
8645 - (void) applicationOpenURL:(NSURL *)url {
8646 [super applicationOpenURL:url];
8648 if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
8649 [self setPage:page];
8651 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8655 - (void) applicationWillResignActive:(UIApplication *)application {
8656 // Stop refreshing if you get a phone call or lock the device.
8657 if ([container_ updating])
8658 [container_ cancelUpdate];
8660 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8661 [super applicationWillResignActive:application];
8664 - (void) addStashController {
8665 stash_ = [[CYStashController alloc] init];
8666 [window_ addSubview:[stash_ view]];
8669 - (void) removeStashController {
8670 [[stash_ view] removeFromSuperview];
8675 [self setIdleTimerDisabled:YES];
8677 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8678 [self setStatusBarShowsProgress:YES];
8679 UpdateExternalStatus(1);
8681 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8683 UpdateExternalStatus(0);
8684 [self setStatusBarShowsProgress:NO];
8686 [self removeStashController];
8688 if (ExecFork() == 0) {
8689 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8690 perror("launchctl stop");
8694 - (void) setupTabBarController {
8695 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8696 [tabbar_ setDelegate:self];
8698 NSMutableArray *items([NSMutableArray arrayWithObjects:
8699 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8700 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8701 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8702 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8706 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8707 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8709 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8712 NSMutableArray *controllers([NSMutableArray array]);
8714 for (UITabBarItem *item in items) {
8715 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8716 [controller setTabBarItem:item];
8717 [controllers addObject:controller];
8720 [tabbar_ setViewControllers:controllers];
8723 - (void) applicationDidFinishLaunching:(id)unused {
8724 [CYBrowserController _initialize];
8726 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8728 Font12_ = [[UIFont systemFontOfSize:12] retain];
8729 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8730 Font14_ = [[UIFont systemFontOfSize:14] retain];
8731 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8732 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8736 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8737 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8739 UIScreen *screen([UIScreen mainScreen]);
8741 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8742 [window_ orderFront:self];
8743 [window_ makeKey:self];
8744 [window_ setHidden:NO];
8747 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8748 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8749 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8750 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8751 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8752 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8753 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8754 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8755 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8758 [self addStashController];
8759 // XXX: this would be much cleaner as a yieldToSelector:
8760 // that way the removeStashController could happen right here inline
8761 // we also could no longer require the useless stash_ field anymore
8762 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8766 database_ = [Database sharedInstance];
8768 [self setupTabBarController];
8770 container_ = [[CYContainer alloc] initWithDatabase:database_];
8771 [container_ setUpdateDelegate:self];
8772 [container_ setTabBarController:tabbar_];
8773 [window_ addSubview:[container_ view]];
8775 // Show pinstripes while loading data.
8776 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8778 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8785 [self showSettings];
8789 [window_ setUserInteractionEnabled:NO];
8791 UIView *container = [[[UIView alloc] init] autorelease];
8792 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8794 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
8795 [spinner startAnimating];
8796 [container addSubview:spinner];
8798 UILabel *label = [[[UILabel alloc] init] autorelease];
8799 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8800 [label setBackgroundColor:[UIColor clearColor]];
8801 [label setTextColor:[UIColor blackColor]];
8802 [label setShadowColor:[UIColor whiteColor]];
8803 [label setShadowOffset:CGSizeMake(0, 1)];
8804 [label setText:UCLocalize("LOADING_DATA")];
8805 [container addSubview:label];
8807 CGSize viewsize = [[tabbar_ view] frame].size;
8808 CGSize spinnersize = [spinner bounds].size;
8809 CGSize textsize = [[label text] sizeWithFont:[label font]];
8810 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8812 CGRect containrect = {
8813 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8814 CGSizeMake(bothwidth, spinnersize.height)
8817 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8825 [container setFrame:containrect];
8826 [spinner setFrame:spinrect];
8827 [label setFrame:textrect];
8828 [[container_ view] addSubview:container];
8833 // Show the home page
8834 [tabbar_ setSelectedIndex:0];
8836 [window_ setUserInteractionEnabled:YES];
8838 // XXX: does this actually slow anything down?
8839 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8840 [container removeFromSuperview];
8843 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8844 if (item != nil && IsWildcat_) {
8845 [sheet showFromBarButtonItem:item animated:YES];
8847 [sheet showInView:window_];
8854 id Alloc_(id self, SEL selector) {
8855 id object = alloc_(self, selector);
8856 lprintf("[%s]A-%p\n", self->isa->name, object);
8861 id Dealloc_(id self, SEL selector) {
8862 id object = dealloc_(self, selector);
8863 lprintf("[%s]D-%p\n", self->isa->name, object);
8867 Class $WebDefaultUIKitDelegate;
8869 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8870 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8871 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8872 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8875 static NSNumber *shouldPlayKeyboardSounds;
8879 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8881 case 1104: // Keyboard Button Clicked
8882 case 1105: // Keyboard Delete Repeated
8883 if (shouldPlayKeyboardSounds == nil) {
8884 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8885 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8888 if (![shouldPlayKeyboardSounds boolValue])
8892 _UIHardware$_playSystemSound$(self, _cmd, sound);
8896 int main(int argc, char *argv[]) { _pooled
8899 if (Class $UIDevice = objc_getClass("UIDevice")) {
8900 UIDevice *device([$UIDevice currentDevice]);
8901 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8905 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8907 /* Library Hacks {{{ */
8908 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8910 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8911 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8912 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8913 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8914 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8917 $UIHardware = objc_getClass("UIHardware");
8918 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8919 if (UIHardware$_playSystemSound$ != NULL) {
8920 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8921 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8924 /* Set Locale {{{ */
8925 Locale_ = CFLocaleCopyCurrent();
8926 Languages_ = [NSLocale preferredLanguages];
8927 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8928 //NSLog(@"%@", [Languages_ description]);
8931 if (Languages_ == nil || [Languages_ count] == 0)
8932 // XXX: consider just setting to C and then falling through?
8935 lang = [[Languages_ objectAtIndex:0] UTF8String];
8936 setenv("LANG", lang, true);
8939 //std::setlocale(LC_ALL, lang);
8940 NSLog(@"Setting Language: %s", lang);
8943 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8945 /* Parse Arguments {{{ */
8946 bool substrate(false);
8952 for (int argi(1); argi != argc; ++argi)
8953 if (strcmp(argv[argi], "--") == 0) {
8955 argv[argi] = argv[0];
8961 for (int argi(1); argi != arge; ++argi)
8962 if (strcmp(args[argi], "--substrate") == 0)
8965 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8969 App_ = [[NSBundle mainBundle] bundlePath];
8970 Home_ = NSHomeDirectory();
8976 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8977 alloc_ = alloc->method_imp;
8978 alloc->method_imp = (IMP) &Alloc_;*/
8980 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8981 dealloc_ = dealloc->method_imp;
8982 dealloc->method_imp = (IMP) &Dealloc_;*/
8984 /* System Information {{{ */
8988 size = sizeof(maxproc);
8989 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8990 perror("sysctlbyname(\"kern.maxproc\", ?)");
8991 else if (maxproc < 64) {
8993 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8994 perror("sysctlbyname(\"kern.maxproc\", #)");
8997 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8998 char *osversion = new char[size];
8999 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9000 perror("sysctlbyname(\"kern.osversion\", ?)");
9002 System_ = [NSString stringWithUTF8String:osversion];
9004 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9005 char *machine = new char[size];
9006 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9007 perror("sysctlbyname(\"hw.machine\", ?)");
9011 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9012 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9013 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9014 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9018 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9019 NSData *data((NSData *) ecid);
9020 size_t length([data length]);
9021 uint8_t bytes[length];
9022 [data getBytes:bytes];
9023 char string[length * 2 + 1];
9024 for (size_t i(0); i != length; ++i)
9025 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9026 ChipID_ = [NSString stringWithUTF8String:string];
9030 IOObjectRelease(service);
9034 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9036 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9037 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9038 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9040 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9041 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9042 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9044 if (mcc != NULL && mnc != NULL)
9045 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9052 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9053 Build_ = [system objectForKey:@"ProductBuildVersion"];
9054 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9055 Product_ = [info objectForKey:@"SafariProductVersion"];
9056 Safari_ = [info objectForKey:@"CFBundleVersion"];
9059 /* Load Database {{{ */
9061 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9063 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9065 if (Metadata_ == NULL)
9066 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9068 Settings_ = [Metadata_ objectForKey:@"Settings"];
9070 Packages_ = [Metadata_ objectForKey:@"Packages"];
9071 Sections_ = [Metadata_ objectForKey:@"Sections"];
9072 Sources_ = [Metadata_ objectForKey:@"Sources"];
9074 Token_ = [Metadata_ objectForKey:@"Token"];
9077 if (Settings_ != nil)
9078 Role_ = [Settings_ objectForKey:@"Role"];
9080 if (Packages_ == nil) {
9081 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
9082 [Metadata_ setObject:Packages_ forKey:@"Packages"];
9085 if (Sections_ == nil) {
9086 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9087 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9090 if (Sources_ == nil) {
9091 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9092 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9096 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9098 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9099 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9100 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9101 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9102 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9103 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9105 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9107 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9108 unlink("/tmp/.cydia.fw");
9110 } else if (access("/User", F_OK) != 0 || version < 2) {
9113 system("/usr/libexec/cydia/firmware.sh");
9117 _assert([[NSFileManager defaultManager]
9118 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9119 withIntermediateDirectories:YES
9124 if (access("/tmp/cydia.chk", F_OK) == 0) {
9125 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9126 _assert(errno == ENOENT);
9127 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9128 _assert(errno == ENOENT);
9131 /* APT Initialization {{{ */
9132 _assert(pkgInitConfig(*_config));
9133 _assert(pkgInitSystem(*_config, _system));
9136 _config->Set("APT::Acquire::Translation", lang);
9138 // XXX: this timeout might be important :(
9139 //_config->Set("Acquire::http::Timeout", 15);
9141 _config->Set("Acquire::http::MaxParallel", 3);
9143 /* Color Choices {{{ */
9144 space_ = CGColorSpaceCreateDeviceRGB();
9146 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9147 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9148 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9149 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9150 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9151 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9152 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9153 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9154 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9156 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9157 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9159 /* UIKit Configuration {{{ */
9160 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9161 if ($GSFontSetUseLegacyFontMetrics != NULL)
9162 $GSFontSetUseLegacyFontMetrics(YES);
9164 // XXX: I have a feeling this was important
9165 //UIKeyboardDisableAutomaticAppearance();
9168 Colon_ = UCLocalize("COLON_DELIMITED");
9169 Error_ = UCLocalize("ERROR");
9170 Warning_ = UCLocalize("WARNING");
9173 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9175 CGColorSpaceRelease(space_);