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 NSArray *relationships_;
1738 NSMutableDictionary *metadata_;
1739 _transient NSDate *firstSeen_;
1740 _transient NSDate *lastSeen_;
1744 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1745 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1747 - (pkgCache::PkgIterator) iterator;
1750 - (NSString *) section;
1751 - (NSString *) simpleSection;
1753 - (NSString *) longSection;
1754 - (NSString *) shortSection;
1758 - (Address *) maintainer;
1760 - (NSString *) longDescription;
1761 - (NSString *) shortDescription;
1764 - (NSMutableDictionary *) metadata;
1766 - (BOOL) subscribed;
1769 - (NSString *) latest;
1770 - (NSString *) installed;
1771 - (BOOL) uninstalled;
1774 - (BOOL) upgradableAndEssential:(BOOL)essential;
1777 - (BOOL) unfiltered;
1781 - (BOOL) halfConfigured;
1782 - (BOOL) halfInstalled;
1784 - (NSString *) mode;
1786 - (void) setVisible;
1789 - (NSString *) name;
1791 - (NSString *) homepage;
1792 - (NSString *) depiction;
1793 - (Address *) author;
1795 - (NSString *) support;
1797 - (NSArray *) files;
1798 - (NSArray *) relationships;
1799 - (NSArray *) warnings;
1800 - (NSArray *) applications;
1802 - (Source *) source;
1803 - (NSString *) role;
1805 - (BOOL) matches:(NSString *)text;
1807 - (bool) hasSupportingRole;
1808 - (BOOL) hasTag:(NSString *)tag;
1809 - (NSString *) primaryPurpose;
1810 - (NSArray *) purposes;
1811 - (bool) isCommercial;
1813 - (CYString &) cyname;
1815 - (uint32_t) compareBySection:(NSArray *)sections;
1817 - (uint32_t) compareForChanges;
1822 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1823 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1824 - (bool) isInstalledAndVisible:(NSNumber *)number;
1825 - (bool) isVisibleInSection:(NSString *)section;
1826 - (bool) isVisibleInSource:(Source *)source;
1830 uint32_t PackageChangesRadix(Package *self, void *) {
1835 uint32_t timestamp : 30;
1836 uint32_t ignored : 1;
1837 uint32_t upgradable : 1;
1841 bool upgradable([self upgradableAndEssential:YES]);
1842 value.bits.upgradable = upgradable ? 1 : 0;
1845 value.bits.timestamp = 0;
1846 value.bits.ignored = [self ignored] ? 0 : 1;
1847 value.bits.upgradable = 1;
1849 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1850 value.bits.ignored = 0;
1851 value.bits.upgradable = 0;
1854 return _not(uint32_t) - value.key;
1857 _finline static void Stifle(uint8_t &value) {
1860 uint32_t PackagePrefixRadix(Package *self, void *context) {
1861 size_t offset(reinterpret_cast<size_t>(context));
1862 CYString &name([self cyname]);
1864 size_t size(name.size());
1867 char *text(name.data());
1870 if (!isdigit(text[0]))
1874 while (size != digits && isdigit(text[digits]))
1884 if (offset == 0 && zeros != 0) {
1885 memset(data, '0', zeros);
1886 memcpy(data + zeros, text, 4 - zeros);
1888 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1889 if (size <= offset - zeros)
1892 text += offset - zeros;
1893 size -= offset - zeros;
1896 memcpy(data, text, 4);
1898 memcpy(data, text, size);
1899 memset(data + size, 0, 4 - size);
1902 for (size_t i(0); i != 4; ++i)
1903 if (isalpha(data[i]))
1911 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1913 /* XXX: ntohl may be more honest */
1914 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1917 CYString &(*PackageName)(Package *self, SEL sel);
1919 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1920 _profile(PackageNameCompare)
1921 CYString &lhi(PackageName(lhs, @selector(cyname)));
1922 CYString &rhi(PackageName(rhs, @selector(cyname)));
1923 CFStringRef lhn(lhi), rhn(rhi);
1926 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1927 else if (rhn == NULL)
1928 return NSOrderedDescending;
1930 _profile(PackageNameCompare$NumbersLast)
1931 if (!lhi.empty() && !rhi.empty()) {
1932 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1933 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1934 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1935 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1936 return lha ? NSOrderedAscending : NSOrderedDescending;
1940 CFIndex length = CFStringGetLength(lhn);
1942 _profile(PackageNameCompare$Compare)
1943 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1948 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1949 return PackageNameCompare(*lhs, *rhs, context);
1952 struct PackageNameOrdering :
1953 std::binary_function<Package *, Package *, bool>
1955 _finline bool operator ()(Package *lhs, Package *rhs) const {
1956 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1960 @implementation Package
1962 - (NSString *) description {
1963 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1973 if (sponsor$_ != nil)
1974 [sponsor$_ release];
1975 if (author$_ != nil)
1982 if (relationships_ != nil)
1983 [relationships_ release];
1984 if (metadata_ != nil)
1985 [metadata_ release];
1990 + (NSString *) webScriptNameForSelector:(SEL)selector {
1991 if (selector == @selector(hasTag:))
1997 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1998 return [self webScriptNameForSelector:selector] == nil;
2001 + (NSArray *) _attributeKeys {
2002 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];
2005 - (NSArray *) attributeKeys {
2006 return [[self class] _attributeKeys];
2009 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2010 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2020 _profile(Package$parse)
2021 pkgRecords::Parser *parser;
2023 _profile(Package$parse$Lookup)
2024 parser = &[database_ records]->Lookup(file_);
2029 _profile(Package$parse$Find)
2035 {"depiction", &depiction_},
2036 {"homepage", &homepage_},
2037 {"website", &website},
2039 {"support", &support_},
2040 {"sponsor", &sponsor_},
2041 {"author", &author_},
2044 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2045 const char *start, *end;
2047 if (parser->Find(names[i].name_, start, end)) {
2048 CYString &value(*names[i].value_);
2049 _profile(Package$parse$Value)
2050 value.set(pool_, start, end - start);
2056 _profile(Package$parse$Tagline)
2057 const char *start, *end;
2058 if (parser->ShortDesc(start, end)) {
2059 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2062 while (stop != start && stop[-1] == '\r')
2064 tagline_.set(pool_, start, stop - start);
2068 _profile(Package$parse$Retain)
2069 if (homepage_.empty())
2070 homepage_ = website;
2071 if (homepage_ == depiction_)
2077 - (void) setVisible {
2078 visible_ = required_ && [self unfiltered];
2081 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2082 if ((self = [super init]) != nil) {
2083 _profile(Package$initWithVersion)
2084 era_ = [database era];
2089 _profile(Package$initWithVersion$ParentPkg)
2090 iterator_ = version.ParentPkg();
2093 database_ = database;
2095 _profile(Package$initWithVersion$Latest)
2096 const char *latest(StripVersion_(version_.VerStr()));
2097 latest_ = (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(latest), strlen(latest), kCFStringEncodingASCII, NO);
2100 pkgCache::VerIterator current;
2101 _profile(Package$initWithVersion$Versions)
2102 current = iterator_.CurrentVer();
2104 installed_.set(pool_, StripVersion_(current.VerStr()));
2106 if (!version_.end())
2107 file_ = version_.FileList();
2109 pkgCache &cache([database_ cache]);
2110 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2114 _profile(Package$initWithVersion$Name)
2115 id_.set(pool_, iterator_.Name());
2116 name_.set(pool, iterator_.Display());
2119 _profile(Package$initWithVersion$lowercaseString)
2120 char *data(id_.data());
2121 for (size_t i(0), e(id_.size()); i != e; ++i)
2122 // XXX: do not use tolower() as this is not locale-specific? :(
2127 _profile(Package$initWithVersion$Source)
2128 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2134 _profile(Package$initWithVersion$Tags)
2135 pkgCache::TagIterator tag(iterator_.TagList());
2137 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2139 const char *name(tag.Name());
2140 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2141 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2142 role_ = (NSString *) CYStringCreate(name + 6);
2143 if (required_ && strncmp(name, "require::", 9) == 0 && (
2148 } while (!tag.end());
2152 bool changed(false);
2154 _profile(Package$initWithVersion$Metadata)
2155 metadata_ = [Packages_ objectForKey:id_];
2157 if (metadata_ == nil) {
2160 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2161 firstSeen_, @"FirstSeen",
2162 latest_, @"LastVersion",
2167 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2168 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2170 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2171 subscribed_ = [subscribed boolValue];
2173 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2175 if (firstSeen_ == nil) {
2176 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2177 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2181 if (version == nil) {
2182 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2184 } else if (![version isEqualToString:latest_]) {
2185 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2187 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2192 metadata_ = [metadata_ retain];
2195 [Packages_ setObject:metadata_ forKey:id_];
2200 _profile(Package$initWithVersion$Section)
2201 section_.set(pool_, iterator_.Section());
2204 _profile(Package$initWithVersion$hasTag)
2205 obsolete_ = [self hasTag:@"cydia::obsolete"];
2206 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2209 _profile(Package$initWithVersion$setVisible)
2215 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2216 pkgCache::VerIterator version;
2218 _profile(Package$packageWithIterator$GetCandidateVer)
2219 version = [database policy]->GetCandidateVer(iterator);
2225 return [[[Package alloc]
2226 initWithVersion:version
2233 - (pkgCache::PkgIterator) iterator {
2237 - (NSString *) section {
2238 if (section$_ == nil) {
2239 if (section_.empty())
2242 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2243 NSString *name(section_);
2246 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2247 if (NSString *rename = [value objectForKey:@"Rename"]) {
2256 - (NSString *) simpleSection {
2257 if (NSString *section = [self section])
2258 return Simplify(section);
2263 - (NSString *) longSection {
2264 return LocalizeSection([self section]);
2267 - (NSString *) shortSection {
2268 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2271 - (NSString *) uri {
2274 pkgIndexFile *index;
2275 pkgCache::PkgFileIterator file(file_.File());
2276 if (![database_ list].FindIndex(file, index))
2278 return [NSString stringWithUTF8String:iterator_->Path];
2279 //return [NSString stringWithUTF8String:file.Site()];
2280 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2284 - (Address *) maintainer {
2287 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2288 const std::string &maintainer(parser->Maintainer());
2289 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2293 return version_.end() ? 0 : version_->InstalledSize;
2296 - (NSString *) longDescription {
2297 @synchronized (database_) {
2298 if ([database_ era] != era_ || file_.end())
2301 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2302 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2304 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2305 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2306 if ([lines count] < 2)
2309 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2310 for (size_t i(1), e([lines count]); i != e; ++i) {
2311 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2312 [trimmed addObject:trim];
2315 return [trimmed componentsJoinedByString:@"\n"];
2318 - (NSString *) shortDescription {
2323 _profile(Package$index)
2324 CFStringRef name((CFStringRef) [self name]);
2325 if (CFStringGetLength(name) == 0)
2327 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2328 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2330 return toupper(character);
2334 - (NSMutableDictionary *) metadata {
2339 if (subscribed_ && lastSeen_ != nil)
2344 - (BOOL) subscribed {
2349 NSDictionary *metadata([self metadata]);
2350 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2351 return [ignored boolValue];
2356 - (NSString *) latest {
2360 - (NSString *) installed {
2364 - (BOOL) uninstalled {
2365 return installed_.empty();
2369 return !version_.end();
2372 - (BOOL) upgradableAndEssential:(BOOL)essential {
2373 _profile(Package$upgradableAndEssential)
2374 pkgCache::VerIterator current(iterator_.CurrentVer());
2376 return essential && essential_ && visible_;
2378 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2382 - (BOOL) essential {
2387 return [database_ cache][iterator_].InstBroken();
2390 - (BOOL) unfiltered {
2391 _profile(Package$unfiltered$obsolete)
2396 _profile(Package$unfiltered$hasSupportingRole)
2397 if (![self hasSupportingRole])
2403 _profile(Package$unfiltered$section)
2404 section = [self section];
2407 _profile(Package$unfiltered$isSectionVisible)
2408 if (section != nil && !isSectionVisible(section))
2420 unsigned char current(iterator_->CurrentState);
2421 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2424 - (BOOL) halfConfigured {
2425 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2428 - (BOOL) halfInstalled {
2429 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2433 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2434 return state.Mode != pkgDepCache::ModeKeep;
2437 - (NSString *) mode {
2438 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2440 switch (state.Mode) {
2441 case pkgDepCache::ModeDelete:
2442 if ((state.iFlags & pkgDepCache::Purge) != 0)
2446 case pkgDepCache::ModeKeep:
2447 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2448 return @"REINSTALL";
2449 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2453 case pkgDepCache::ModeInstall:
2454 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2455 return @"REINSTALL";
2456 else*/ switch (state.Status) {
2458 return @"DOWNGRADE";
2464 return @"NEW_INSTALL";
2475 - (NSString *) name {
2476 return name_.empty() ? id_ : name_;
2479 - (UIImage *) icon {
2480 NSString *section = [self simpleSection];
2484 if ([static_cast<id>(icon_) hasPrefix:@"file:///"])
2485 // XXX: correct escaping
2486 icon = [UIImage imageAtPath:[static_cast<id>(icon_) substringFromIndex:7]];
2487 if (icon == nil) if (section != nil)
2488 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2489 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2490 if ([dicon hasPrefix:@"file:///"])
2491 // XXX: correct escaping
2492 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2494 icon = [UIImage applicationImageNamed:@"unknown.png"];
2498 - (NSString *) homepage {
2502 - (NSString *) depiction {
2503 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2506 - (Address *) sponsor {
2507 if (sponsor$_ == nil) {
2508 if (sponsor_.empty())
2510 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2514 - (Address *) author {
2515 if (author$_ == nil) {
2516 if (author_.empty())
2518 author$_ = [[Address addressWithString:author_] retain];
2522 - (NSString *) support {
2523 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2526 - (NSArray *) files {
2527 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2528 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2531 fin.open([path UTF8String]);
2536 while (std::getline(fin, line))
2537 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2542 - (NSArray *) relationships {
2543 return relationships_;
2546 - (NSArray *) warnings {
2547 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2548 const char *name(iterator_.Name());
2550 size_t length(strlen(name));
2551 if (length < 2) invalid:
2552 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2553 else for (size_t i(0); i != length; ++i)
2555 /* XXX: technically this is not allowed */
2556 (name[i] < 'A' || name[i] > 'Z') &&
2557 (name[i] < 'a' || name[i] > 'z') &&
2558 (name[i] < '0' || name[i] > '9') &&
2559 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2562 if (strcmp(name, "cydia") != 0) {
2565 bool _private = false;
2568 bool repository = [[self section] isEqualToString:@"Repositories"];
2570 if (NSArray *files = [self files])
2571 for (NSString *file in files)
2572 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2574 else if (!user && [file isEqualToString:@"/User"])
2576 else if (!_private && [file isEqualToString:@"/private"])
2578 else if (!stash && [file isEqualToString:@"/var/stash"])
2581 /* XXX: this is not sensitive enough. only some folders are valid. */
2582 if (cydia && !repository)
2583 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2585 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2587 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2589 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2592 return [warnings count] == 0 ? nil : warnings;
2595 - (NSArray *) applications {
2596 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2598 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2600 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2601 if (NSArray *files = [self files])
2602 for (NSString *file in files)
2603 if (application_r(file)) {
2604 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2605 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2606 if ([id isEqualToString:me])
2609 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2611 display = application_r[1];
2613 NSString *bundle([file stringByDeletingLastPathComponent]);
2614 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2615 if (icon == nil || [icon length] == 0)
2617 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2619 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2620 [applications addObject:application];
2622 [application addObject:id];
2623 [application addObject:display];
2624 [application addObject:url];
2627 return [applications count] == 0 ? nil : applications;
2630 - (Source *) source {
2631 if (source_ == nil) {
2632 @synchronized (database_) {
2633 if ([database_ era] != era_ || file_.end())
2634 source_ = (Source *) [NSNull null];
2636 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2640 return source_ == (Source *) [NSNull null] ? nil : source_;
2643 - (NSString *) role {
2647 - (BOOL) matches:(NSString *)text {
2653 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2654 if (range.location != NSNotFound)
2657 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2658 if (range.location != NSNotFound)
2661 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2662 if (range.location != NSNotFound)
2668 - (bool) hasSupportingRole {
2671 if ([role_ isEqualToString:@"enduser"])
2673 if ([Role_ isEqualToString:@"User"])
2675 if ([role_ isEqualToString:@"hacker"])
2677 if ([Role_ isEqualToString:@"Hacker"])
2679 if ([role_ isEqualToString:@"developer"])
2681 if ([Role_ isEqualToString:@"Developer"])
2686 - (BOOL) hasTag:(NSString *)tag {
2687 return tags_ == nil ? NO : [tags_ containsObject:tag];
2690 - (NSString *) primaryPurpose {
2691 for (NSString *tag in tags_)
2692 if ([tag hasPrefix:@"purpose::"])
2693 return [tag substringFromIndex:9];
2697 - (NSArray *) purposes {
2698 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2699 for (NSString *tag in tags_)
2700 if ([tag hasPrefix:@"purpose::"])
2701 [purposes addObject:[tag substringFromIndex:9]];
2702 return [purposes count] == 0 ? nil : purposes;
2705 - (bool) isCommercial {
2706 return [self hasTag:@"cydia::commercial"];
2709 - (CYString &) cyname {
2710 return name_.empty() ? id_ : name_;
2713 - (uint32_t) compareBySection:(NSArray *)sections {
2714 NSString *section([self section]);
2715 for (size_t i(0), e([sections count]); i != e; ++i) {
2716 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2720 return _not(uint32_t);
2723 - (uint32_t) compareForChanges {
2728 uint32_t timestamp : 30;
2729 uint32_t ignored : 1;
2730 uint32_t upgradable : 1;
2734 bool upgradable([self upgradableAndEssential:YES]);
2735 value.bits.upgradable = upgradable ? 1 : 0;
2738 value.bits.timestamp = 0;
2739 value.bits.ignored = [self ignored] ? 0 : 1;
2740 value.bits.upgradable = 1;
2742 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2743 value.bits.ignored = 0;
2744 value.bits.upgradable = 0;
2747 return _not(uint32_t) - value.key;
2751 pkgProblemResolver *resolver = [database_ resolver];
2752 resolver->Clear(iterator_);
2753 resolver->Protect(iterator_);
2757 pkgProblemResolver *resolver = [database_ resolver];
2758 resolver->Clear(iterator_);
2759 resolver->Protect(iterator_);
2760 pkgCacheFile &cache([database_ cache]);
2761 cache->MarkInstall(iterator_, false);
2762 pkgDepCache::StateCache &state((*cache)[iterator_]);
2763 if (!state.Install())
2764 cache->SetReInstall(iterator_, true);
2768 pkgProblemResolver *resolver = [database_ resolver];
2769 resolver->Clear(iterator_);
2770 resolver->Protect(iterator_);
2771 resolver->Remove(iterator_);
2772 [database_ cache]->MarkDelete(iterator_, true);
2775 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2776 _profile(Package$isUnfilteredAndSearchedForBy)
2779 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2780 value &= [self unfiltered];
2783 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2784 value &= [self matches:search];
2791 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2792 if ([search length] == 0)
2795 _profile(Package$isUnfilteredAndSelectedForBy)
2798 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2799 value &= [self unfiltered];
2802 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2803 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2810 - (bool) isInstalledAndVisible:(NSNumber *)number {
2811 return ((![number boolValue] && ![role_ isEqualToString:@"cydia"]) || [self visible]) && ![self uninstalled];
2814 - (bool) isVisibleInSection:(NSString *)name {
2815 NSString *section = [self section];
2820 section == nil && [name length] == 0 ||
2821 [name isEqualToString:section]
2825 - (bool) isVisibleInSource:(Source *)source {
2826 return [self source] == source && [self visible];
2831 /* Section Class {{{ */
2832 @interface Section : NSObject {
2837 NSString *localized_;
2840 - (NSComparisonResult) compareByLocalized:(Section *)section;
2841 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2842 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2843 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2844 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2845 - (NSString *) name;
2852 - (void) addToCount;
2854 - (void) setCount:(size_t)count;
2855 - (NSString *) localized;
2859 @implementation Section
2863 if (localized_ != nil)
2864 [localized_ release];
2868 - (NSComparisonResult) compareByLocalized:(Section *)section {
2869 NSString *lhs(localized_);
2870 NSString *rhs([section localized]);
2872 /*if ([lhs length] != 0 && [rhs length] != 0) {
2873 unichar lhc = [lhs characterAtIndex:0];
2874 unichar rhc = [rhs characterAtIndex:0];
2876 if (isalpha(lhc) && !isalpha(rhc))
2877 return NSOrderedAscending;
2878 else if (!isalpha(lhc) && isalpha(rhc))
2879 return NSOrderedDescending;
2882 return [lhs compare:rhs options:LaxCompareOptions_];
2885 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2886 if ((self = [self initWithName:name localize:NO]) != nil) {
2887 if (localized != nil)
2888 localized_ = [localized retain];
2892 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2893 return [self initWithName:name row:0 localize:localize];
2896 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2897 if ((self = [super init]) != nil) {
2898 name_ = [name retain];
2902 localized_ = [LocalizeSection(name_) retain];
2906 /* XXX: localize the index thingees */
2907 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2908 if ((self = [super init]) != nil) {
2909 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2915 - (NSString *) name {
2935 - (void) addToCount {
2939 - (void) setCount:(size_t)count {
2943 - (NSString *) localized {
2950 static NSString *Colon_;
2951 static NSString *Error_;
2952 static NSString *Warning_;
2954 /* Database Implementation {{{ */
2955 @implementation Database
2957 + (Database *) sharedInstance {
2958 static Database *instance;
2959 if (instance == nil)
2960 instance = [[Database alloc] init];
2969 // XXX: actually implement this thing
2971 NSRecycleZone(zone_);
2972 // XXX: malloc_destroy_zone(zone_);
2973 apr_pool_destroy(pool_);
2977 - (void) _readCydia:(NSNumber *)fd { _pooled
2978 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2979 std::istream is(&ib);
2982 static Pcre finish_r("^finish:([^:]*)$");
2984 while (std::getline(is, line)) {
2985 const char *data(line.c_str());
2986 size_t size = line.size();
2987 lprintf("C:%s\n", data);
2989 if (finish_r(data, size)) {
2990 NSString *finish = finish_r[1];
2991 int index = [Finishes_ indexOfObject:finish];
2992 if (index != INT_MAX && index > Finish_)
3000 - (void) _readStatus:(NSNumber *)fd { _pooled
3001 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3002 std::istream is(&ib);
3005 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3006 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3008 while (std::getline(is, line)) {
3009 const char *data(line.c_str());
3010 size_t size(line.size());
3011 lprintf("S:%s\n", data);
3013 if (conffile_r(data, size)) {
3014 [delegate_ setConfigurationData:conffile_r[1]];
3015 } else if (strncmp(data, "status: ", 8) == 0) {
3016 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3017 [delegate_ setProgressTitle:string];
3018 } else if (pmstatus_r(data, size)) {
3019 std::string type([pmstatus_r[1] UTF8String]);
3020 NSString *id = pmstatus_r[2];
3022 float percent([pmstatus_r[3] floatValue]);
3023 [delegate_ setProgressPercent:(percent / 100)];
3025 NSString *string = pmstatus_r[4];
3027 if (type == "pmerror")
3028 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3029 withObject:[NSArray arrayWithObjects:string, id, nil]
3032 else if (type == "pmstatus") {
3033 [delegate_ setProgressTitle:string];
3034 } else if (type == "pmconffile")
3035 [delegate_ setConfigurationData:string];
3037 lprintf("E:unknown pmstatus\n");
3039 lprintf("E:unknown status\n");
3045 - (void) _readOutput:(NSNumber *)fd { _pooled
3046 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3047 std::istream is(&ib);
3050 while (std::getline(is, line)) {
3051 lprintf("O:%s\n", line.c_str());
3052 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3062 - (Package *) packageWithName:(NSString *)name {
3063 @synchronized (self) {
3064 if (static_cast<pkgDepCache *>(cache_) == NULL)
3066 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3067 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3071 if ((self = [super init]) != nil) {
3078 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3079 apr_pool_create(&pool_, NULL);
3081 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
3085 _assert(pipe(fds) != -1);
3088 _config->Set("APT::Keep-Fds::", cydiafd_);
3089 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3092 detachNewThreadSelector:@selector(_readCydia:)
3094 withObject:[NSNumber numberWithInt:fds[0]]
3097 _assert(pipe(fds) != -1);
3101 detachNewThreadSelector:@selector(_readStatus:)
3103 withObject:[NSNumber numberWithInt:fds[0]]
3106 _assert(pipe(fds) != -1);
3107 _assert(dup2(fds[0], 0) != -1);
3108 _assert(close(fds[0]) != -1);
3110 input_ = fdopen(fds[1], "a");
3112 _assert(pipe(fds) != -1);
3113 _assert(dup2(fds[1], 1) != -1);
3114 _assert(close(fds[1]) != -1);
3117 detachNewThreadSelector:@selector(_readOutput:)
3119 withObject:[NSNumber numberWithInt:fds[0]]
3124 - (pkgCacheFile &) cache {
3128 - (pkgDepCache::Policy *) policy {
3132 - (pkgRecords *) records {
3136 - (pkgProblemResolver *) resolver {
3140 - (pkgAcquire &) fetcher {
3144 - (pkgSourceList &) list {
3148 - (NSArray *) packages {
3149 return (NSArray *) packages_;
3152 - (NSArray *) sources {
3153 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3154 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3155 [sources addObject:i->second];
3159 - (NSArray *) issues {
3160 if (cache_->BrokenCount() == 0)
3163 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3165 for (Package *package in [self packages]) {
3166 if (![package broken])
3168 pkgCache::PkgIterator pkg([package iterator]);
3170 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3171 [entry addObject:[package name]];
3172 [issues addObject:entry];
3174 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3178 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3179 pkgCache::DepIterator start;
3180 pkgCache::DepIterator end;
3181 dep.GlobOr(start, end); // ++dep
3183 if (!cache_->IsImportantDep(end))
3185 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3188 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3189 [entry addObject:failure];
3190 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3192 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3193 if (Package *package = [self packageWithName:name])
3194 name = [package name];
3195 [failure addObject:name];
3197 pkgCache::PkgIterator target(start.TargetPkg());
3198 if (target->ProvidesList != 0)
3199 [failure addObject:@"?"];
3201 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3203 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3204 else if (!cache_[target].CandidateVerIter(cache_).end())
3205 [failure addObject:@"-"];
3206 else if (target->ProvidesList == 0)
3207 [failure addObject:@"!"];
3209 [failure addObject:@"%"];
3213 if (start.TargetVer() != 0)
3214 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3225 - (bool) popErrorWithTitle:(NSString *)title {
3227 std::string message;
3229 while (!_error->empty()) {
3231 bool warning(!_error->PopMessage(error));
3235 size_t size(error.size());
3236 if (size == 0 || error[size - 1] != '\n')
3238 error.resize(size - 1);
3240 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3242 if (!message.empty())
3247 if (fatal && !message.empty())
3248 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3253 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3254 return [self popErrorWithTitle:title] || !success;
3257 - (void) reloadData { CYPoolStart() {
3258 @synchronized (self) {
3261 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3262 CFArrayRemoveAllValues(packages_);
3289 apr_pool_clear(pool_);
3290 NSRecycleZone(zone_);
3292 int chk(creat("/tmp/cydia.chk", 0644));
3296 NSString *title(UCLocalize("DATABASE"));
3299 if (!cache_.Open(progress_, true)) { pop:
3301 bool warning(!_error->PopMessage(error));
3302 lprintf("cache_.Open():[%s]\n", error.c_str());
3304 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3305 [delegate_ repairWithSelector:@selector(configure)];
3306 else if (error == "The package lists or status file could not be parsed or opened.")
3307 [delegate_ repairWithSelector:@selector(update)];
3308 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3309 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3310 // else if (error == "The list of sources could not be read.")
3312 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3321 unlink("/tmp/cydia.chk");
3323 now_ = [[NSDate date] retain];
3325 policy_ = new pkgDepCache::Policy();
3326 records_ = new pkgRecords(cache_);
3327 resolver_ = new pkgProblemResolver(cache_);
3328 fetcher_ = new pkgAcquire(&status_);
3331 list_ = new pkgSourceList();
3332 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3335 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3336 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3340 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3343 if (cache_->BrokenCount() != 0) {
3344 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3347 if (cache_->BrokenCount() != 0) {
3348 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3352 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3356 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3357 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3358 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3359 // XXX: this could be more intelligent
3360 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3361 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3363 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3368 /*std::vector<Package *> packages;
3369 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3370 [packages_ release];
3375 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3376 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3377 //packages.push_back(package);
3378 CFArrayAppendValue(packages_, [package retain]);
3382 /*if (packages.empty())
3383 packages_ = [[NSArray alloc] init];
3385 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3388 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3389 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3390 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3398 /*if (!packages.empty())
3399 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3400 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3402 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3404 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3406 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3410 } } CYPoolEnd() _trace(); }
3412 - (void) configure {
3413 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3414 system([dpkg UTF8String]);
3418 // XXX: I don't remember this condition
3423 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3425 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3427 if ([self popErrorWithTitle:title])
3431 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3434 public pkgArchiveCleaner
3437 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3442 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3449 fetcher_->Shutdown();
3451 pkgRecords records(cache_);
3453 lock_ = new FileFd();
3454 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3456 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3458 if ([self popErrorWithTitle:title])
3462 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3465 manager_ = (_system->CreatePM(cache_));
3466 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3473 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3475 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3477 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3479 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3480 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3483 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3488 bool failed = false;
3489 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3490 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3492 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3495 std::string uri = (*item)->DescURI();
3496 std::string error = (*item)->ErrorText;
3498 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3501 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3502 withObject:[NSArray arrayWithObjects:
3503 [NSString stringWithUTF8String:error.c_str()],
3515 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3517 if (_error->PendingError()) {
3522 if (result == pkgPackageManager::Failed) {
3527 if (result != pkgPackageManager::Completed) {
3532 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3534 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3536 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3537 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3540 if (![before isEqualToArray:after])
3545 NSString *title(UCLocalize("UPGRADE"));
3546 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3552 [self updateWithStatus:status_];
3555 - (void) setVisible {
3556 for (Package *package in [self packages])
3557 [package setVisible];
3560 - (void) updateWithStatus:(Status &)status {
3561 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3562 NSString *title(UCLocalize("REFRESHING_DATA"));
3565 if (!list.ReadMainList())
3566 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3569 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3570 if ([self popErrorWithTitle:title])
3573 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3574 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3575 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3577 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3581 - (void) setDelegate:(id)delegate {
3582 delegate_ = delegate;
3583 status_.setDelegate(delegate);
3584 progress_.setDelegate(delegate);
3587 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3588 SourceMap::const_iterator i(sources_.find(file->ID));
3589 return i == sources_.end() ? nil : i->second;
3595 /* Confirmation Controller {{{ */
3596 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3597 if (!iterator.end())
3598 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3599 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3601 pkgCache::PkgIterator package(dep.TargetPkg());
3604 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3612 /* Web Scripting {{{ */
3613 @interface CydiaObject : NSObject {
3615 _transient id delegate_;
3618 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3621 @implementation CydiaObject
3624 [indirect_ release];
3628 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3629 if ((self = [super init]) != nil) {
3630 indirect_ = [indirect retain];
3634 - (void) setDelegate:(id)delegate {
3635 delegate_ = delegate;
3638 + (NSArray *) _attributeKeys {
3639 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3642 - (NSArray *) attributeKeys {
3643 return [[self class] _attributeKeys];
3646 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3647 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3650 - (NSString *) device {
3651 return [[UIDevice currentDevice] uniqueIdentifier];
3654 #if 0 // XXX: implement!
3655 - (NSString *) mac {
3656 if (![indirect_ promptForSensitive:@"Mac Address"])
3660 - (NSString *) serial {
3661 if (![indirect_ promptForSensitive:@"Serial #"])
3665 - (NSString *) firewire {
3666 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3670 - (NSString *) imei {
3671 if (![indirect_ promptForSensitive:@"IMEI"])
3676 + (NSString *) webScriptNameForSelector:(SEL)selector {
3677 if (selector == @selector(close))
3679 else if (selector == @selector(getInstalledPackages))
3680 return @"getInstalledPackages";
3681 else if (selector == @selector(getPackageById:))
3682 return @"getPackageById";
3683 else if (selector == @selector(installPackages:))
3684 return @"installPackages";
3685 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3686 return @"setButtonImage";
3687 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3688 return @"setButtonTitle";
3689 else if (selector == @selector(setPopupHook:))
3690 return @"setPopupHook";
3691 else if (selector == @selector(setSpecial:))
3692 return @"setSpecial";
3693 else if (selector == @selector(setToken:))
3695 else if (selector == @selector(setViewportWidth:))
3696 return @"setViewportWidth";
3697 else if (selector == @selector(supports:))
3699 else if (selector == @selector(stringWithFormat:arguments:))
3701 else if (selector == @selector(localizedStringForKey:value:table:))
3703 else if (selector == @selector(du:))
3705 else if (selector == @selector(statfs:))
3711 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3712 return [self webScriptNameForSelector:selector] == nil;
3715 - (BOOL) supports:(NSString *)feature {
3716 return [feature isEqualToString:@"window.open"];
3719 - (NSArray *) getInstalledPackages {
3720 NSArray *packages([[Database sharedInstance] packages]);
3721 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3722 for (Package *package in packages)
3723 if ([package installed] != nil)
3724 [installed addObject:package];
3728 - (Package *) getPackageById:(NSString *)id {
3729 Package *package([[Database sharedInstance] packageWithName:id]);
3734 - (NSArray *) statfs:(NSString *)path {
3737 if (path == nil || statfs([path UTF8String], &stat) == -1)
3740 return [NSArray arrayWithObjects:
3741 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3742 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3743 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3747 - (NSNumber *) du:(NSString *)path {
3748 NSNumber *value(nil);
3751 _assert(pipe(fds) != -1);
3753 pid_t pid(ExecFork());
3755 _assert(dup2(fds[1], 1) != -1);
3756 _assert(close(fds[0]) != -1);
3757 _assert(close(fds[1]) != -1);
3758 /* XXX: this should probably not use du */
3759 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3764 _assert(close(fds[1]) != -1);
3766 if (FILE *du = fdopen(fds[0], "r")) {
3768 while (fgets(line, sizeof(line), du) != NULL) {
3769 size_t length(strlen(line));
3770 while (length != 0 && line[length - 1] == '\n')
3771 line[--length] = '\0';
3772 if (char *tab = strchr(line, '\t')) {
3774 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3779 } else _assert(close(fds[0]));
3783 if (waitpid(pid, &status, 0) == -1)
3786 else _assert(false);
3795 - (void) installPackages:(NSArray *)packages {
3796 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3799 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3800 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3803 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3804 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3807 - (void) setSpecial:(id)function {
3808 [indirect_ setSpecial:function];
3811 - (void) setToken:(NSString *)token {
3814 Token_ = [token retain];
3816 [Metadata_ setObject:Token_ forKey:@"Token"];
3820 - (void) setPopupHook:(id)function {
3821 [indirect_ setPopupHook:function];
3824 - (void) setViewportWidth:(float)width {
3825 [indirect_ setViewportWidth:width];
3828 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3829 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3830 unsigned count([arguments count]);
3832 for (unsigned i(0); i != count; ++i)
3833 values[i] = [arguments objectAtIndex:i];
3834 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3837 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3838 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3840 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3842 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3848 /* Cydia Browser Controller {{{ */
3849 @interface CYBrowserController : BrowserController {
3850 CydiaObject *cydia_;
3855 @implementation CYBrowserController
3862 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3865 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3866 [super webView:view didClearWindowObject:window forFrame:frame];
3868 WebDataSource *source([frame dataSource]);
3869 NSURLResponse *response([source response]);
3870 NSURL *url([response URL]);
3871 NSString *scheme([url scheme]);
3873 NSHTTPURLResponse *http;
3874 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3875 http = (NSHTTPURLResponse *) response;
3879 NSDictionary *headers([http allHeaderFields]);
3880 NSString *host([url host]);
3881 [self setHeaders:headers forHost:host];
3884 [host isEqualToString:@"cydia.saurik.com"] ||
3885 [host hasSuffix:@".cydia.saurik.com"] ||
3886 [scheme isEqualToString:@"file"]
3888 [window setValue:cydia_ forKey:@"cydia"];
3891 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3892 if (System_ != NULL)
3893 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3894 if (Machine_ != NULL)
3895 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3897 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3899 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3902 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3903 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3904 [self _setMoreHeaders:copy];
3908 - (void) setDelegate:(id)delegate {
3909 [super setDelegate:delegate];
3910 [cydia_ setDelegate:delegate];
3914 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3915 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3917 WebView *webview([[webview_ _documentView] webView]);
3919 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3921 NSString *application = package == nil ? @"Cydia" : [NSString
3922 stringWithFormat:@"Cydia/%@",
3927 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3929 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3930 if (Product_ != nil)
3931 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3933 [webview setApplicationNameForUserAgent:application];
3940 /* Confirmation {{{ */
3941 @protocol ConfirmationControllerDelegate
3942 - (void) cancelAndClear:(bool)clear;
3943 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3947 @interface ConfirmationController : CYBrowserController {
3948 _transient Database *database_;
3949 UIAlertView *essential_;
3956 - (id) initWithDatabase:(Database *)database;
3960 @implementation ConfirmationController
3967 if (essential_ != nil)
3968 [essential_ release];
3972 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3973 NSString *context([alert context]);
3975 if ([context isEqualToString:@"remove"]) {
3976 if (button == [alert cancelButtonIndex]) {
3977 [self dismissModalViewControllerAnimated:YES];
3978 } else if (button == [alert firstOtherButtonIndex]) {
3981 [delegate_ confirmWithNavigationController:[self navigationController]];
3984 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3985 } else if ([context isEqualToString:@"unable"]) {
3986 [self dismissModalViewControllerAnimated:YES];
3987 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3989 [super alertView:alert clickedButtonAtIndex:button];
3993 - (void) _doContinue {
3994 [self dismissModalViewControllerAnimated:YES];
3995 [delegate_ cancelAndClear:NO];
3998 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
3999 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4003 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4004 [super webView:view didClearWindowObject:window forFrame:frame];
4005 [window setValue:changes_ forKey:@"changes"];
4006 [window setValue:issues_ forKey:@"issues"];
4007 [window setValue:sizes_ forKey:@"sizes"];
4008 [window setValue:self forKey:@"queue"];
4011 - (id) initWithDatabase:(Database *)database {
4012 if ((self = [super init]) != nil) {
4013 database_ = database;
4015 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4017 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4018 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4019 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4020 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4021 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4025 pkgDepCache::Policy *policy([database_ policy]);
4027 pkgCacheFile &cache([database_ cache]);
4028 NSArray *packages = [database_ packages];
4029 for (Package *package in packages) {
4030 pkgCache::PkgIterator iterator = [package iterator];
4031 pkgDepCache::StateCache &state(cache[iterator]);
4033 NSString *name([package name]);
4035 if (state.NewInstall())
4036 [installing addObject:name];
4037 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4038 [reinstalling addObject:name];
4039 else if (state.Upgrade())
4040 [upgrading addObject:name];
4041 else if (state.Downgrade())
4042 [downgrading addObject:name];
4043 else if (state.Delete()) {
4044 if ([package essential])
4046 [removing addObject:name];
4049 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4050 substrate_ |= DepSubstrate(iterator.CurrentVer());
4055 else if (Advanced_) {
4056 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4058 essential_ = [[UIAlertView alloc]
4059 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4060 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4062 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4063 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4066 [essential_ setContext:@"remove"];
4068 essential_ = [[UIAlertView alloc]
4069 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4070 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4072 cancelButtonTitle:UCLocalize("OKAY")
4073 otherButtonTitles:nil
4076 [essential_ setContext:@"unable"];
4079 changes_ = [[NSArray alloc] initWithObjects:
4087 issues_ = [database_ issues];
4089 issues_ = [issues_ retain];
4091 sizes_ = [[NSArray alloc] initWithObjects:
4092 SizeString([database_ fetcher].FetchNeeded()),
4093 SizeString([database_ fetcher].PartialPresent()),
4096 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4098 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4099 initWithTitle:UCLocalize("CANCEL")
4100 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4101 style:UIBarButtonItemStylePlain
4103 action:@selector(cancelButtonClicked)
4108 - (void) applyRightButton {
4109 #if !AlwaysReload && !IgnoreInstall
4110 if (issues_ == nil && ![self isLoading])
4111 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4112 initWithTitle:UCLocalize("CONFIRM")
4113 style:UIBarButtonItemStylePlain
4115 action:@selector(confirmButtonClicked)
4118 [super applyRightButton];
4120 [[self navigationItem] setRightBarButtonItem:nil];
4124 - (void) cancelButtonClicked {
4125 [self dismissModalViewControllerAnimated:YES];
4126 [delegate_ cancelAndClear:YES];
4130 - (void) confirmButtonClicked {
4134 if (essential_ != nil)
4139 [delegate_ confirmWithNavigationController:[self navigationController]];
4147 /* Progress Data {{{ */
4148 @interface ProgressData : NSObject {
4150 // XXX: should these really both be _transient?
4151 _transient id target_;
4152 _transient id object_;
4155 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4162 @implementation ProgressData
4164 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4165 if ((self = [super init]) != nil) {
4166 selector_ = selector;
4186 /* Progress Controller {{{ */
4187 @interface ProgressController : CYViewController <
4188 ConfigurationDelegate,
4191 _transient Database *database_;
4192 UIProgressBar *progress_;
4193 UITextView *output_;
4194 UITextLabel *status_;
4195 UIPushButton *close_;
4197 SHA1SumValue springlist_;
4198 SHA1SumValue notifyconf_;
4202 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4204 - (void) _retachThread;
4205 - (void) _detachNewThreadData:(ProgressData *)data;
4206 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4212 @protocol ProgressControllerDelegate
4213 - (void) progressControllerIsComplete:(ProgressController *)sender;
4216 @implementation ProgressController
4219 [database_ setDelegate:nil];
4220 [progress_ release];
4229 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4230 if ((self = [super init]) != nil) {
4231 database_ = database;
4232 [database_ setDelegate:self];
4233 delegate_ = delegate;
4235 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4237 progress_ = [[UIProgressBar alloc] init];
4238 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4239 [progress_ setStyle:0];
4241 status_ = [[UITextLabel alloc] init];
4242 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4243 [status_ setColor:[UIColor whiteColor]];
4244 [status_ setBackgroundColor:[UIColor clearColor]];
4245 [status_ setCentersHorizontally:YES];
4246 //[status_ setFont:font];
4248 output_ = [[UITextView alloc] init];
4250 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4251 //[output_ setTextFont:@"Courier New"];
4252 [output_ setFont:[[output_ font] fontWithSize:12]];
4253 [output_ setTextColor:[UIColor whiteColor]];
4254 [output_ setBackgroundColor:[UIColor clearColor]];
4255 [output_ setMarginTop:0];
4256 [output_ setAllowsRubberBanding:YES];
4257 [output_ setEditable:NO];
4258 [[self view] addSubview:output_];
4260 close_ = [[UIPushButton alloc] init];
4261 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4262 [close_ setAutosizesToFit:NO];
4263 [close_ setDrawsShadow:YES];
4264 [close_ setStretchBackground:YES];
4265 [close_ setEnabled:YES];
4266 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4267 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4268 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4269 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4273 - (void) positionViews {
4274 CGRect bounds = [[self view] bounds];
4275 CGSize prgsize = [UIProgressBar defaultSize];
4278 (bounds.size.width - prgsize.width) / 2,
4279 bounds.size.height - prgsize.height - 20
4282 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4284 [progress_ setFrame:prgrect];
4285 [status_ setFrame:CGRectMake(
4287 bounds.size.height - prgsize.height - 50,
4288 bounds.size.width - 20,
4291 [output_ setFrame:CGRectMake(
4294 bounds.size.width - 20,
4295 bounds.size.height - 62
4297 [close_ setFrame:CGRectMake(
4298 (bounds.size.width - closewidth) / 2,
4299 bounds.size.height - prgsize.height - 50,
4305 - (void) viewWillAppear:(BOOL)animated {
4306 [super viewDidAppear:animated];
4307 [[self navigationItem] setHidesBackButton:YES];
4308 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4310 [self positionViews];
4313 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4314 [self positionViews];
4317 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4318 NSString *context([alert context]);
4320 if ([context isEqualToString:@"conffile"]) {
4321 FILE *input = [database_ input];
4322 if (button == [alert cancelButtonIndex])
4323 fprintf(input, "N\n");
4324 else if (button == [alert firstOtherButtonIndex])
4325 fprintf(input, "Y\n");
4330 - (void) closeButtonPushed {
4333 UpdateExternalStatus(0);
4337 [self dismissModalViewControllerAnimated:YES];
4341 [delegate_ terminateWithSuccess];
4342 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4343 [delegate_ suspendWithAnimation:YES];
4345 [delegate_ suspend];*/
4349 system("launchctl stop com.apple.SpringBoard");
4353 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4362 - (void) _retachThread {
4363 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4365 [[self view] addSubview:close_];
4366 [progress_ removeFromSuperview];
4367 [status_ removeFromSuperview];
4369 [database_ popErrorWithTitle:title_];
4370 [delegate_ progressControllerIsComplete:self];
4374 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4377 MMap mmap(file, MMap::ReadOnly);
4379 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4380 if (!(notifyconf_ == sha1.Result()))
4387 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4390 MMap mmap(file, MMap::ReadOnly);
4392 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4393 if (!(springlist_ == sha1.Result()))
4399 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4400 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4401 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4402 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4403 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4406 system("su -c /usr/bin/uicache mobile");
4408 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4410 [delegate_ setStatusBarShowsProgress:NO];
4413 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4414 [[data target] performSelector:[data selector] withObject:[data object]];
4415 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4418 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4419 UpdateExternalStatus(1);
4426 title_ = [title retain];
4428 [[self navigationItem] setTitle:title_];
4430 [status_ setText:nil];
4431 [output_ setText:@""];
4432 [progress_ setProgress:0];
4434 [close_ removeFromSuperview];
4435 [[self view] addSubview:progress_];
4436 [[self view] addSubview:status_];
4438 [delegate_ setStatusBarShowsProgress:YES];
4443 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4446 MMap mmap(file, MMap::ReadOnly);
4448 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4449 notifyconf_ = sha1.Result();
4455 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4458 MMap mmap(file, MMap::ReadOnly);
4460 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4461 springlist_ = sha1.Result();
4466 detachNewThreadSelector:@selector(_detachNewThreadData:)
4468 withObject:[[[ProgressData alloc]
4469 initWithSelector:selector
4476 - (void) repairWithSelector:(SEL)selector {
4478 detachNewThreadSelector:selector
4481 title:UCLocalize("REPAIRING")
4485 - (void) setConfigurationData:(NSString *)data {
4487 performSelectorOnMainThread:@selector(_setConfigurationData:)
4493 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4494 CYActionSheet *sheet([[[CYActionSheet alloc]
4496 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4497 defaultButtonIndex:0
4500 [sheet setMessage:error];
4501 [sheet yieldToPopupAlertAnimated:YES];
4505 - (void) setProgressTitle:(NSString *)title {
4507 performSelectorOnMainThread:@selector(_setProgressTitle:)
4513 - (void) setProgressPercent:(float)percent {
4515 performSelectorOnMainThread:@selector(_setProgressPercent:)
4516 withObject:[NSNumber numberWithFloat:percent]
4521 - (void) startProgress {
4524 - (void) addProgressOutput:(NSString *)output {
4526 performSelectorOnMainThread:@selector(_addProgressOutput:)
4532 - (bool) isCancelling:(size_t)received {
4536 - (void) _setConfigurationData:(NSString *)data {
4537 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4539 if (!conffile_r(data)) {
4540 lprintf("E:invalid conffile\n");
4544 NSString *ofile = conffile_r[1];
4545 //NSString *nfile = conffile_r[2];
4547 UIAlertView *alert = [[[UIAlertView alloc]
4548 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4549 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4551 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4552 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4553 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4557 [alert setContext:@"conffile"];
4561 - (void) _setProgressTitle:(NSString *)title {
4562 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4563 for (size_t i(0), e([words count]); i != e; ++i) {
4564 NSString *word([words objectAtIndex:i]);
4565 if (Package *package = [database_ packageWithName:word])
4566 [words replaceObjectAtIndex:i withObject:[package name]];
4569 [status_ setText:[words componentsJoinedByString:@" "]];
4572 - (void) _setProgressPercent:(NSNumber *)percent {
4573 [progress_ setProgress:[percent floatValue]];
4576 - (void) _addProgressOutput:(NSString *)output {
4577 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4578 CGSize size = [output_ contentSize];
4579 CGRect rect = {{0, size.height}, {size.width, 0}};
4580 [output_ scrollRectToVisible:rect animated:YES];
4583 - (BOOL) isRunning {
4590 /* Cell Content View {{{ */
4591 @protocol ContentDelegate
4592 - (void) drawContentRect:(CGRect)rect;
4595 @interface ContentView : UIView {
4596 _transient id<ContentDelegate> delegate_;
4601 @implementation ContentView
4602 - (id) initWithFrame:(CGRect)frame {
4603 if ((self = [super initWithFrame:frame]) != nil) {
4604 /* Fix landscape stretching. */
4605 [self setNeedsDisplayOnBoundsChange:YES];
4609 - (void) setDelegate:(id<ContentDelegate>)delegate {
4610 delegate_ = delegate;
4613 - (void) drawRect:(CGRect)rect {
4614 [super drawRect:rect];
4615 [delegate_ drawContentRect:rect];
4619 /* Package Cell {{{ */
4620 @interface PackageCell : UITableViewCell <
4625 NSString *description_;
4631 ContentView *content_;
4637 - (PackageCell *) init;
4638 - (void) setPackage:(Package *)package;
4640 + (int) heightForPackage:(Package *)package;
4641 - (void) drawContentRect:(CGRect)rect;
4645 @implementation PackageCell
4647 - (void) clearPackage {
4658 if (description_ != nil) {
4659 [description_ release];
4663 if (source_ != nil) {
4668 if (badge_ != nil) {
4673 if (placard_ != nil) {
4683 [self clearPackage];
4690 return faded_ ? [self selectionPercent] : fade_;
4693 - (PackageCell *) init {
4694 CGRect frame(CGRectMake(0, 0, 320, 74));
4695 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4696 UIView *content([self contentView]);
4697 CGRect bounds([content bounds]);
4699 content_ = [[ContentView alloc] initWithFrame:bounds];
4700 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4701 [content addSubview:content_];
4703 [content_ setDelegate:self];
4704 [content_ setOpaque:YES];
4705 if ([self respondsToSelector:@selector(selectionPercent)])
4710 - (void) _setBackgroundColor {
4712 if (NSString *mode = [package_ mode]) {
4713 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4714 color = remove ? RemovingColor_ : InstallingColor_;
4716 color = [UIColor whiteColor];
4718 [content_ setBackgroundColor:color];
4719 [self setNeedsDisplay];
4722 - (void) setPackage:(Package *)package {
4723 [self clearPackage];
4726 Source *source = [package source];
4728 icon_ = [[package icon] retain];
4729 name_ = [[package name] retain];
4732 description_ = [package longDescription];
4733 if (description_ == nil)
4734 description_ = [package shortDescription];
4735 if (description_ != nil)
4736 description_ = [description_ retain];
4738 commercial_ = [package isCommercial];
4740 package_ = [package retain];
4742 NSString *label = nil;
4743 bool trusted = false;
4745 if (source != nil) {
4746 label = [source label];
4747 trusted = [source trusted];
4748 } else if ([[package id] isEqualToString:@"firmware"])
4749 label = UCLocalize("APPLE");
4751 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4753 NSString *from(label);
4755 NSString *section = [package simpleSection];
4756 if (section != nil && ![section isEqualToString:label]) {
4757 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4758 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4761 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4762 source_ = [from retain];
4764 if (NSString *purpose = [package primaryPurpose])
4765 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4766 badge_ = [badge_ retain];
4768 if ([package installed] != nil)
4769 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4770 placard_ = [placard_ retain];
4772 [self _setBackgroundColor];
4773 [content_ setNeedsDisplay];
4776 - (void) drawContentRect:(CGRect)rect {
4777 bool selected([self isSelected]);
4778 float width([self bounds].size.width);
4781 CGContextRef context(UIGraphicsGetCurrentContext());
4782 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4783 CGContextFillRect(context, rect);
4788 rect.size = [icon_ size];
4790 rect.size.width /= 2;
4791 rect.size.height /= 2;
4793 rect.origin.x = 25 - rect.size.width / 2;
4794 rect.origin.y = 25 - rect.size.height / 2;
4796 [icon_ drawInRect:rect];
4799 if (badge_ != nil) {
4800 CGSize size = [badge_ size];
4802 [badge_ drawAtPoint:CGPointMake(
4803 36 - size.width / 2,
4804 36 - size.height / 2
4812 UISetColor(commercial_ ? Purple_ : Black_);
4813 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4814 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4817 UISetColor(commercial_ ? Purplish_ : Gray_);
4818 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4820 if (placard_ != nil)
4821 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4824 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4825 //[self _setBackgroundColor];
4826 [super setSelected:selected animated:fade];
4827 [content_ setNeedsDisplay];
4830 + (int) heightForPackage:(Package *)package {
4836 /* Section Cell {{{ */
4837 @interface SectionCell : UITableViewCell <
4845 ContentView *content_;
4850 - (void) setSection:(Section *)section editing:(BOOL)editing;
4854 @implementation SectionCell
4856 - (void) clearSection {
4857 if (basic_ != nil) {
4862 if (section_ != nil) {
4872 if (count_ != nil) {
4879 [self clearSection];
4887 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4888 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4889 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4890 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4891 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4893 UIView *content([self contentView]);
4894 CGRect bounds([content bounds]);
4896 content_ = [[ContentView alloc] initWithFrame:bounds];
4897 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4898 [content addSubview:content_];
4899 [content_ setBackgroundColor:[UIColor whiteColor]];
4901 [content_ setDelegate:self];
4905 - (void) onSwitch:(id)sender {
4906 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4907 if (metadata == nil) {
4908 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4909 [Sections_ setObject:metadata forKey:basic_];
4913 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4916 - (void) setSection:(Section *)section editing:(BOOL)editing {
4917 if (editing != editing_) {
4919 [switch_ removeFromSuperview];
4921 [self addSubview:switch_];
4925 [self clearSection];
4927 if (section == nil) {
4928 name_ = [UCLocalize("ALL_PACKAGES") retain];
4931 basic_ = [section name];
4933 basic_ = [basic_ retain];
4935 section_ = [section localized];
4936 if (section_ != nil)
4937 section_ = [section_ retain];
4939 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4940 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4943 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4946 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4947 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
4949 [content_ setNeedsDisplay];
4952 - (void) setFrame:(CGRect)frame {
4953 [super setFrame:frame];
4955 CGRect rect([switch_ frame]);
4956 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4959 - (void) drawContentRect:(CGRect)rect {
4960 BOOL selected = [self isSelected];
4962 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4970 float width(rect.size.width);
4974 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4976 CGSize size = [count_ sizeWithFont:Font14_];
4980 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4986 /* File Table {{{ */
4987 @interface FileTable : CYViewController <
4988 UITableViewDataSource,
4991 _transient Database *database_;
4994 NSMutableArray *files_;
4998 - (id) initWithDatabase:(Database *)database;
4999 - (void) setPackage:(Package *)package;
5003 @implementation FileTable
5006 if (package_ != nil)
5015 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5016 return files_ == nil ? 0 : [files_ count];
5019 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5023 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5024 static NSString *reuseIdentifier = @"Cell";
5026 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5028 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5029 [cell setFont:[UIFont systemFontOfSize:16]];
5031 [cell setText:[files_ objectAtIndex:indexPath.row]];
5032 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5037 - (id) initWithDatabase:(Database *)database {
5038 if ((self = [super init]) != nil) {
5039 database_ = database;
5041 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5043 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5045 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5046 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5047 [list_ setRowHeight:24.0f];
5048 [[self view] addSubview:list_];
5050 [list_ setDataSource:self];
5051 [list_ setDelegate:self];
5055 - (void) setPackage:(Package *)package {
5056 if (package_ != nil) {
5057 [package_ autorelease];
5066 [files_ removeAllObjects];
5068 if (package != nil) {
5069 package_ = [package retain];
5070 name_ = [[package id] retain];
5072 if (NSArray *files = [package files])
5073 [files_ addObjectsFromArray:files];
5075 if ([files_ count] != 0) {
5076 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5077 [files_ removeObjectAtIndex:0];
5078 [files_ sortUsingSelector:@selector(compareByPath:)];
5080 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5081 [stack addObject:@"/"];
5083 for (int i(0), e([files_ count]); i != e; ++i) {
5084 NSString *file = [files_ objectAtIndex:i];
5085 while (![file hasPrefix:[stack lastObject]])
5086 [stack removeLastObject];
5087 NSString *directory = [stack lastObject];
5088 [stack addObject:[file stringByAppendingString:@"/"]];
5089 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5090 ([stack count] - 2) * 3, "",
5091 [file substringFromIndex:[directory length]]
5100 - (void) reloadData {
5101 [self setPackage:[database_ packageWithName:name_]];
5106 /* Package Controller {{{ */
5107 @interface PackageController : CYBrowserController <
5108 UIActionSheetDelegate
5110 _transient Database *database_;
5114 NSMutableArray *buttons_;
5115 UIBarButtonItem *button_;
5118 - (id) initWithDatabase:(Database *)database;
5119 - (void) setPackage:(Package *)package;
5123 @implementation PackageController
5126 if (package_ != nil)
5140 if ([self retainCount] == 1)
5141 [delegate_ setPackageController:self];
5145 /* XXX: this is not safe at all... localization of /fail/ */
5146 - (void) _clickButtonWithName:(NSString *)name {
5147 if ([name isEqualToString:UCLocalize("CLEAR")])
5148 [delegate_ clearPackage:package_];
5149 else if ([name isEqualToString:UCLocalize("INSTALL")])
5150 [delegate_ installPackage:package_];
5151 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5152 [delegate_ installPackage:package_];
5153 else if ([name isEqualToString:UCLocalize("REMOVE")])
5154 [delegate_ removePackage:package_];
5155 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5156 [delegate_ installPackage:package_];
5157 else _assert(false);
5160 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5161 NSString *context([sheet context]);
5163 if ([context isEqualToString:@"modify"]) {
5164 if (button != [sheet cancelButtonIndex]) {
5165 NSString *buttonName = [buttons_ objectAtIndex:button];
5166 [self _clickButtonWithName:buttonName];
5169 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5173 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5174 [super webView:view didClearWindowObject:window forFrame:frame];
5175 [window setValue:package_ forKey:@"package"];
5178 - (bool) _allowJavaScriptPanel {
5183 - (void) _customButtonClicked {
5184 int count([buttons_ count]);
5189 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5191 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5192 [buttons addObjectsFromArray:buttons_];
5194 UIActionSheet *sheet = [[[UIActionSheet alloc]
5197 cancelButtonTitle:nil
5198 destructiveButtonTitle:nil
5199 otherButtonTitles:nil
5202 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5204 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5205 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5207 [sheet setContext:@"modify"];
5209 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5213 // We don't want to allow non-commercial packages to do custom things to the install button,
5214 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5215 - (void) customButtonClicked {
5217 [super customButtonClicked];
5219 [self _customButtonClicked];
5222 - (void) reloadButtonClicked {
5223 // Don't reload a package view by clicking the button.
5226 - (void) applyLoadingTitle {
5227 // Don't show "Loading" as the title. Ever.
5230 - (UIBarButtonItem *) rightButton {
5235 - (id) initWithDatabase:(Database *)database {
5236 if ((self = [super init]) != nil) {
5237 database_ = database;
5238 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5239 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5243 - (void) setPackage:(Package *)package {
5244 if (package_ != nil) {
5245 [package_ autorelease];
5254 [buttons_ removeAllObjects];
5256 if (package != nil) {
5259 package_ = [package retain];
5260 name_ = [[package id] retain];
5261 commercial_ = [package isCommercial];
5263 if ([package_ mode] != nil)
5264 [buttons_ addObject:UCLocalize("CLEAR")];
5265 if ([package_ source] == nil);
5266 else if ([package_ upgradableAndEssential:NO])
5267 [buttons_ addObject:UCLocalize("UPGRADE")];
5268 else if ([package_ uninstalled])
5269 [buttons_ addObject:UCLocalize("INSTALL")];
5271 [buttons_ addObject:UCLocalize("REINSTALL")];
5272 if (![package_ uninstalled])
5273 [buttons_ addObject:UCLocalize("REMOVE")];
5280 switch ([buttons_ count]) {
5281 case 0: title = nil; break;
5282 case 1: title = [buttons_ objectAtIndex:0]; break;
5283 default: title = UCLocalize("MODIFY"); break;
5286 button_ = [[UIBarButtonItem alloc]
5288 style:UIBarButtonItemStylePlain
5290 action:@selector(customButtonClicked)
5294 - (bool) isLoading {
5295 return commercial_ ? [super isLoading] : false;
5298 - (void) reloadData {
5299 [self setPackage:[database_ packageWithName:name_]];
5304 /* Package Table {{{ */
5305 @interface PackageTable : UIView <
5306 UITableViewDataSource,
5309 _transient Database *database_;
5310 NSMutableArray *packages_;
5311 NSMutableArray *sections_;
5313 NSMutableArray *index_;
5314 NSMutableDictionary *indices_;
5315 // XXX: this target_ seems to be delegate_. :(
5316 _transient id target_;
5318 // XXX: why do we even have this delegate_?
5319 _transient id delegate_;
5322 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5324 - (void) setDelegate:(id)delegate;
5326 - (void) reloadData;
5327 - (void) resetCursor;
5329 - (UITableView *) list;
5331 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5333 - (void) deselectWithAnimation:(BOOL)animated;
5337 @implementation PackageTable
5340 [packages_ release];
5341 [sections_ release];
5349 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5350 NSInteger count([sections_ count]);
5351 return count == 0 ? 1 : count;
5354 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5355 if ([sections_ count] == 0)
5357 return [[sections_ objectAtIndex:section] name];
5360 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5361 if ([sections_ count] == 0)
5363 return [[sections_ objectAtIndex:section] count];
5366 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5367 Section *section([sections_ objectAtIndex:[path section]]);
5368 NSInteger row([path row]);
5369 Package *package([packages_ objectAtIndex:([section row] + row)]);
5373 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5374 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5376 cell = [[[PackageCell alloc] init] autorelease];
5377 [cell setPackage:[self packageAtIndexPath:path]];
5381 - (void) deselectWithAnimation:(BOOL)animated {
5382 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5385 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5386 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5389 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5390 Package *package([self packageAtIndexPath:path]);
5391 package = [database_ packageWithName:[package id]];
5392 [target_ performSelector:action_ withObject:package];
5396 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5397 return [packages_ count] > 20 ? index_ : nil;
5400 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5404 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5405 if ((self = [super initWithFrame:frame]) != nil) {
5406 database_ = database;
5411 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5412 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5414 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5415 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5417 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5418 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5419 [list_ setRowHeight:73.0f];
5420 [self addSubview:list_];
5422 [list_ setDataSource:self];
5423 [list_ setDelegate:self];
5427 - (void) setDelegate:(id)delegate {
5428 delegate_ = delegate;
5431 - (bool) hasPackage:(Package *)package {
5435 - (void) reloadData {
5436 NSArray *packages = [database_ packages];
5438 [packages_ removeAllObjects];
5439 [sections_ removeAllObjects];
5441 _profile(PackageTable$reloadData$Filter)
5442 for (Package *package in packages)
5443 if ([self hasPackage:package])
5444 [packages_ addObject:package];
5447 [index_ removeAllObjects];
5448 [indices_ removeAllObjects];
5450 Section *section = nil;
5452 _profile(PackageTable$reloadData$Section)
5453 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5457 _profile(PackageTable$reloadData$Section$Package)
5458 package = [packages_ objectAtIndex:offset];
5459 index = [package index];
5462 if (section == nil || [section index] != index) {
5463 _profile(PackageTable$reloadData$Section$Allocate)
5464 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5467 [index_ addObject:[section name]];
5468 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5470 _profile(PackageTable$reloadData$Section$Add)
5471 [sections_ addObject:section];
5475 [section addToCount];
5479 _profile(PackageTable$reloadData$List)
5484 - (void) resetCursor {
5485 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5488 - (UITableView *) list {
5492 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5493 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5498 /* Filtered Package Table {{{ */
5499 @interface FilteredPackageTable : PackageTable {
5505 - (void) setObject:(id)object;
5506 - (void) setObject:(id)object forFilter:(SEL)filter;
5508 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5512 @implementation FilteredPackageTable
5520 - (void) setFilter:(SEL)filter {
5523 /* XXX: this is an unsafe optimization of doomy hell */
5524 Method method(class_getInstanceMethod([Package class], filter));
5525 _assert(method != NULL);
5526 imp_ = method_getImplementation(method);
5527 _assert(imp_ != NULL);
5530 - (void) setObject:(id)object {
5536 object_ = [object retain];
5539 - (void) setObject:(id)object forFilter:(SEL)filter {
5540 [self setFilter:filter];
5541 [self setObject:object];
5544 - (bool) hasPackage:(Package *)package {
5545 _profile(FilteredPackageTable$hasPackage)
5546 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5550 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5551 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5552 [self setFilter:filter];
5553 object_ = [object retain];
5561 /* Filtered Package Controller {{{ */
5562 @interface FilteredPackageController : CYViewController {
5563 _transient Database *database_;
5564 FilteredPackageTable *packages_;
5568 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5572 @implementation FilteredPackageController
5575 [packages_ release];
5581 - (void) viewDidAppear:(BOOL)animated {
5582 [super viewDidAppear:animated];
5583 [packages_ deselectWithAnimation:animated];
5586 - (void) didSelectPackage:(Package *)package {
5587 PackageController *view([delegate_ packageController]);
5588 [view setPackage:package];
5589 [view setDelegate:delegate_];
5590 [[self navigationController] pushViewController:view animated:YES];
5593 - (NSString *) title { return title_; }
5595 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5596 if ((self = [super init]) != nil) {
5597 database_ = database;
5598 title_ = [title copy];
5599 [[self navigationItem] setTitle:title_];
5601 packages_ = [[FilteredPackageTable alloc]
5602 initWithFrame:[[self view] bounds]
5605 action:@selector(didSelectPackage:)
5610 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5611 [[self view] addSubview:packages_];
5615 - (void) reloadData {
5616 [packages_ reloadData];
5619 - (void) setDelegate:(id)delegate {
5620 [super setDelegate:delegate];
5621 [packages_ setDelegate:delegate];
5628 /* Add Source Controller {{{ */
5629 @interface AddSourceController : CYViewController {
5630 _transient Database *database_;
5633 - (id) initWithDatabase:(Database *)database;
5637 @implementation AddSourceController
5639 - (id) initWithDatabase:(Database *)database {
5640 if ((self = [super init]) != nil) {
5641 database_ = database;
5647 /* Source Cell {{{ */
5648 @interface SourceCell : UITableViewCell <
5653 NSString *description_;
5655 ContentView *content_;
5658 - (void) setSource:(Source *)source;
5662 @implementation SourceCell
5664 - (void) clearSource {
5667 [description_ release];
5676 - (void) setSource:(Source *)source {
5680 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5682 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5683 icon_ = [icon_ retain];
5685 origin_ = [[source name] retain];
5686 label_ = [[source uri] retain];
5687 description_ = [[source description] retain];
5689 [content_ setNeedsDisplay];
5698 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5699 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5700 UIView *content([self contentView]);
5701 CGRect bounds([content bounds]);
5703 content_ = [[ContentView alloc] initWithFrame:bounds];
5704 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5705 [content_ setBackgroundColor:[UIColor whiteColor]];
5706 [content addSubview:content_];
5708 [content_ setDelegate:self];
5709 [content_ setOpaque:YES];
5713 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5714 [super setSelected:selected animated:animated];
5715 [content_ setNeedsDisplay];
5718 - (void) drawContentRect:(CGRect)rect {
5719 bool selected([self isSelected]);
5720 float width(rect.size.width);
5723 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5730 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5734 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5738 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5743 /* Source Table {{{ */
5744 @interface SourceTable : CYViewController <
5745 UITableViewDataSource,
5748 _transient Database *database_;
5750 NSMutableArray *sources_;
5754 UIProgressHUD *hud_;
5757 //NSURLConnection *installer_;
5758 NSURLConnection *trivial_;
5759 NSURLConnection *trivial_bz2_;
5760 NSURLConnection *trivial_gz_;
5761 //NSURLConnection *automatic_;
5766 - (id) initWithDatabase:(Database *)database;
5768 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5772 @implementation SourceTable
5774 - (void) _releaseConnection:(NSURLConnection *)connection {
5775 if (connection != nil) {
5776 [connection cancel];
5777 //[connection setDelegate:nil];
5778 [connection release];
5790 //[self _releaseConnection:installer_];
5791 [self _releaseConnection:trivial_];
5792 [self _releaseConnection:trivial_gz_];
5793 [self _releaseConnection:trivial_bz2_];
5794 //[self _releaseConnection:automatic_];
5801 - (void) viewDidAppear:(BOOL)animated {
5802 [super viewDidAppear:animated];
5803 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5806 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5807 return offset_ == 0 ? 1 : 2;
5810 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5811 switch (section + (offset_ == 0 ? 1 : 0)) {
5812 case 0: return UCLocalize("ENTERED_BY_USER");
5813 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5819 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5820 int count = [sources_ count];
5822 case 0: return (offset_ == 0 ? count : offset_);
5823 case 1: return count - offset_;
5829 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5831 switch (indexPath.section) {
5832 case 0: idx = indexPath.row; break;
5833 case 1: idx = indexPath.row + offset_; break;
5837 return [sources_ objectAtIndex:idx];
5840 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5841 Source *source = [self sourceAtIndexPath:indexPath];
5842 return [source description] == nil ? 56 : 73;
5845 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5846 static NSString *cellIdentifier = @"SourceCell";
5848 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5849 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5850 [cell setSource:[self sourceAtIndexPath:indexPath]];
5855 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5856 return UITableViewCellAccessoryDisclosureIndicator;
5859 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5860 Source *source = [self sourceAtIndexPath:indexPath];
5862 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5863 initWithDatabase:database_
5864 title:[source label]
5865 filter:@selector(isVisibleInSource:)
5869 [packages setDelegate:delegate_];
5871 [[self navigationController] pushViewController:packages animated:YES];
5874 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5875 Source *source = [self sourceAtIndexPath:indexPath];
5876 return [source record] != nil;
5879 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5880 Source *source = [self sourceAtIndexPath:indexPath];
5881 [Sources_ removeObjectForKey:[source key]];
5882 [delegate_ syncData];
5886 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5889 @"./", @"Distribution",
5890 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5892 [delegate_ syncData];
5895 - (NSString *) getWarning {
5896 NSString *href(href_);
5897 NSRange colon([href rangeOfString:@"://"]);
5898 if (colon.location != NSNotFound)
5899 href = [href substringFromIndex:(colon.location + 3)];
5900 href = [href stringByAddingPercentEscapes];
5901 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5902 href = [href stringByCachingURLWithCurrentCDN];
5904 NSURL *url([NSURL URLWithString:href]);
5906 NSStringEncoding encoding;
5907 NSError *error(nil);
5909 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5910 return [warning length] == 0 ? nil : warning;
5914 - (void) _endConnection:(NSURLConnection *)connection {
5915 // XXX: the memory management in this method is horribly awkward
5917 NSURLConnection **field = NULL;
5918 if (connection == trivial_)
5920 else if (connection == trivial_bz2_)
5921 field = &trivial_bz2_;
5922 else if (connection == trivial_gz_)
5923 field = &trivial_gz_;
5924 _assert(field != NULL);
5925 [connection release];
5930 trivial_bz2_ == nil &&
5936 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5939 UIAlertView *alert = [[[UIAlertView alloc]
5940 initWithTitle:UCLocalize("SOURCE_WARNING")
5943 cancelButtonTitle:UCLocalize("CANCEL")
5944 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5947 [alert setContext:@"warning"];
5948 [alert setNumberOfRows:1];
5952 } else if (error_ != nil) {
5953 UIAlertView *alert = [[[UIAlertView alloc]
5954 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5955 message:[error_ localizedDescription]
5957 cancelButtonTitle:UCLocalize("OK")
5958 otherButtonTitles:nil
5961 [alert setContext:@"urlerror"];
5964 UIAlertView *alert = [[[UIAlertView alloc]
5965 initWithTitle:UCLocalize("NOT_REPOSITORY")
5966 message:UCLocalize("NOT_REPOSITORY_EX")
5968 cancelButtonTitle:UCLocalize("OK")
5969 otherButtonTitles:nil
5972 [alert setContext:@"trivial"];
5976 [delegate_ setStatusBarShowsProgress:NO];
5977 [delegate_ removeProgressHUD:hud_];
5987 if (error_ != nil) {
5994 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5995 switch ([response statusCode]) {
6001 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6002 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6004 error_ = [error retain];
6005 [self _endConnection:connection];
6008 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6009 [self _endConnection:connection];
6012 - (NSString *) title { return UCLocalize("SOURCES"); }
6014 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6015 NSMutableURLRequest *request = [NSMutableURLRequest
6016 requestWithURL:[NSURL URLWithString:href]
6017 cachePolicy:NSURLRequestUseProtocolCachePolicy
6018 timeoutInterval:120.0
6021 [request setHTTPMethod:method];
6023 if (Machine_ != NULL)
6024 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6025 if (UniqueID_ != nil)
6026 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6028 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6030 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6033 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6034 NSString *context([alert context]);
6036 if ([context isEqualToString:@"source"]) {
6039 NSString *href = [[alert textField] text];
6041 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6043 if (![href hasSuffix:@"/"])
6044 href_ = [href stringByAppendingString:@"/"];
6047 href_ = [href_ retain];
6049 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6050 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6051 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6052 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6056 // XXX: this is stupid
6057 hud_ = [[delegate_ addProgressHUD] retain];
6058 [hud_ setText:UCLocalize("VERIFYING_URL")];
6067 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6068 } else if ([context isEqualToString:@"trivial"])
6069 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6070 else if ([context isEqualToString:@"urlerror"])
6071 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6072 else if ([context isEqualToString:@"warning"]) {
6087 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6091 - (id) initWithDatabase:(Database *)database {
6092 if ((self = [super init]) != nil) {
6093 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6094 [self updateButtonsForEditingStatus:NO animated:NO];
6096 database_ = database;
6097 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6099 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6100 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6101 [[self view] addSubview:list_];
6103 [list_ setDataSource:self];
6104 [list_ setDelegate:self];
6110 - (void) reloadData {
6112 if (!list.ReadMainList())
6115 [sources_ removeAllObjects];
6116 [sources_ addObjectsFromArray:[database_ sources]];
6118 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6121 int count([sources_ count]);
6123 for (int i = 0; i != count; i++) {
6124 if ([[sources_ objectAtIndex:i] record] == nil)
6129 [list_ setEditing:NO];
6130 [self updateButtonsForEditingStatus:NO animated:NO];
6134 - (void) addButtonClicked {
6135 /*[book_ pushPage:[[[AddSourceController alloc]
6140 UIAlertView *alert = [[[UIAlertView alloc]
6141 initWithTitle:UCLocalize("ENTER_APT_URL")
6144 cancelButtonTitle:UCLocalize("CANCEL")
6145 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6148 [alert setContext:@"source"];
6149 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6151 [alert setNumberOfRows:1];
6152 [alert addTextFieldWithValue:@"http://" label:@""];
6154 UITextInputTraits *traits = [[alert textField] textInputTraits];
6155 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6156 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6157 [traits setKeyboardType:UIKeyboardTypeURL];
6158 // XXX: UIReturnKeyDone
6159 [traits setReturnKeyType:UIReturnKeyNext];
6164 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6165 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6166 initWithTitle:UCLocalize("ADD")
6167 style:UIBarButtonItemStylePlain
6169 action:@selector(addButtonClicked)
6170 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6172 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6173 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6174 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6176 action:@selector(editButtonClicked)
6177 ] autorelease] animated:animated];
6179 if (IsWildcat_ && !editing)
6180 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6181 initWithTitle:UCLocalize("SETTINGS")
6182 style:UIBarButtonItemStylePlain
6184 action:@selector(settingsButtonClicked)
6188 - (void) settingsButtonClicked {
6189 [delegate_ showSettings];
6192 - (void) editButtonClicked {
6193 [list_ setEditing:![list_ isEditing] animated:YES];
6195 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6201 /* Installed Controller {{{ */
6202 @interface InstalledController : FilteredPackageController {
6206 - (id) initWithDatabase:(Database *)database;
6208 - (void) updateRoleButton;
6209 - (void) queueStatusDidChange;
6213 @implementation InstalledController
6219 - (NSString *) title { return UCLocalize("INSTALLED"); }
6221 - (id) initWithDatabase:(Database *)database {
6222 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6223 [self updateRoleButton];
6224 [self queueStatusDidChange];
6229 - (void) queueButtonClicked {
6234 - (void) queueStatusDidChange {
6238 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6239 initWithTitle:UCLocalize("QUEUE")
6240 style:UIBarButtonItemStyleDone
6242 action:@selector(queueButtonClicked)
6245 [[self navigationItem] setLeftBarButtonItem:nil];
6251 - (void) reloadData {
6252 [packages_ reloadData];
6255 - (void) updateRoleButton {
6256 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6257 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6258 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6259 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6261 action:@selector(roleButtonClicked)
6265 - (void) roleButtonClicked {
6266 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6267 [packages_ reloadData];
6270 [self updateRoleButton];
6273 - (void) setDelegate:(id)delegate {
6274 [super setDelegate:delegate];
6275 [packages_ setDelegate:delegate];
6281 /* Home Controller {{{ */
6282 @interface HomeController : CYBrowserController {
6287 @implementation HomeController
6289 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6290 [super _setMoreHeaders:request];
6293 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6294 if (UniqueID_ != nil)
6295 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6297 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6300 - (void) aboutButtonClicked {
6301 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6303 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6304 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6305 [alert setCancelButtonIndex:0];
6308 @"Copyright (C) 2008-2010\n"
6309 "Jay Freeman (saurik)\n"
6310 "saurik@saurik.com\n"
6311 "http://www.saurik.com/"
6317 - (void) viewWillAppear:(BOOL)animated {
6318 [super viewWillAppear:animated];
6319 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6322 - (void) viewWillDisappear:(BOOL)animated {
6323 [super viewWillDisappear:animated];
6324 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6328 if ((self = [super init]) != nil) {
6329 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6330 initWithTitle:UCLocalize("ABOUT")
6331 style:UIBarButtonItemStylePlain
6333 action:@selector(aboutButtonClicked)
6340 /* Manage Controller {{{ */
6341 @interface ManageController : CYBrowserController {
6344 - (void) queueStatusDidChange;
6347 @implementation ManageController
6350 if ((self = [super init]) != nil) {
6351 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6353 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6354 initWithTitle:UCLocalize("SETTINGS")
6355 style:UIBarButtonItemStylePlain
6357 action:@selector(settingsButtonClicked)
6360 [self queueStatusDidChange];
6364 - (void) settingsButtonClicked {
6365 [delegate_ showSettings];
6369 - (void) queueButtonClicked {
6373 - (void) applyLoadingTitle {
6374 // No "Loading" title.
6377 - (void) applyRightButton {
6382 - (void) queueStatusDidChange {
6384 if (!IsWildcat_ && Queuing_) {
6385 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6386 initWithTitle:UCLocalize("QUEUE")
6387 style:UIBarButtonItemStyleDone
6389 action:@selector(queueButtonClicked)
6392 [[self navigationItem] setRightBarButtonItem:nil];
6397 - (bool) isLoading {
6404 /* Refresh Bar {{{ */
6405 @interface RefreshBar : UINavigationBar {
6406 UIProgressIndicator *indicator_;
6407 UITextLabel *prompt_;
6408 UIProgressBar *progress_;
6409 UINavigationButton *cancel_;
6414 @implementation RefreshBar
6417 [indicator_ release];
6419 [progress_ release];
6424 - (void) positionViews {
6425 CGRect frame = [cancel_ frame];
6426 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6427 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6428 [cancel_ setFrame:frame];
6430 CGSize prgsize = {75, 100};
6432 [self frame].size.width - prgsize.width - 10,
6433 ([self frame].size.height - prgsize.height) / 2
6435 [progress_ setFrame:prgrect];
6437 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6438 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6439 CGRect indrect = {{indoffset, indoffset}, indsize};
6440 [indicator_ setFrame:indrect];
6442 CGSize prmsize = {215, indsize.height + 4};
6444 indoffset * 2 + indsize.width,
6445 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6447 [prompt_ setFrame:prmrect];
6450 - (void)setFrame:(CGRect)frame {
6451 [super setFrame:frame];
6453 [self positionViews];
6456 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6457 if ((self = [super initWithFrame:frame])) {
6458 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6460 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6461 [self setBarStyle:UIBarStyleBlack];
6463 UIBarStyle barstyle([self _barStyle:NO]);
6464 bool ugly(barstyle == UIBarStyleDefault);
6466 UIProgressIndicatorStyle style = ugly ?
6467 UIProgressIndicatorStyleMediumBrown :
6468 UIProgressIndicatorStyleMediumWhite;
6470 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6471 [indicator_ setStyle:style];
6472 [indicator_ startAnimation];
6473 [self addSubview:indicator_];
6475 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6476 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6477 [prompt_ setBackgroundColor:[UIColor clearColor]];
6478 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6479 [self addSubview:prompt_];
6481 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6482 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6483 [progress_ setStyle:0];
6484 [self addSubview:progress_];
6486 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6487 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6488 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6489 [cancel_ setBarStyle:barstyle];
6491 [self positionViews];
6496 [cancel_ removeFromSuperview];
6500 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6501 [progress_ setProgress:0];
6502 [self addSubview:cancel_];
6506 [cancel_ removeFromSuperview];
6509 - (void) setPrompt:(NSString *)prompt {
6510 [prompt_ setText:prompt];
6513 - (void) setProgress:(float)progress {
6514 [progress_ setProgress:progress];
6520 @class CYNavigationController;
6522 /* Cydia Tab Bar Controller {{{ */
6523 @interface CYTabBarController : UITabBarController {
6524 _transient Database *database_;
6529 @implementation CYTabBarController
6531 /* XXX: some logic should probably go here related to
6532 freeing the view controllers on tab change */
6534 - (void) reloadData {
6535 size_t count([[self viewControllers] count]);
6536 for (size_t i(0); i != count; ++i) {
6537 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6542 - (id) initWithDatabase:(Database *)database {
6543 if ((self = [super init]) != nil) {
6544 database_ = database;
6551 /* Cydia Navigation Controller {{{ */
6552 @interface CYNavigationController : UINavigationController {
6553 _transient Database *database_;
6554 _transient id<UINavigationControllerDelegate> delegate_;
6557 - (id) initWithDatabase:(Database *)database;
6558 - (void) reloadData;
6563 @implementation CYNavigationController
6565 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6566 // Inherit autorotation settings for modal parents.
6567 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6568 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6570 return [super shouldAutorotateToInterfaceOrientation:orientation];
6578 - (void) reloadData {
6579 size_t count([[self viewControllers] count]);
6580 for (size_t i(0); i != count; ++i) {
6581 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6586 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6587 delegate_ = delegate;
6590 - (id) initWithDatabase:(Database *)database {
6591 if ((self = [super init]) != nil) {
6592 database_ = database;
6598 /* Cydia:// Protocol {{{ */
6599 @interface CydiaURLProtocol : NSURLProtocol {
6604 @implementation CydiaURLProtocol
6606 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6607 NSURL *url([request URL]);
6610 NSString *scheme([[url scheme] lowercaseString]);
6611 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6616 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6620 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6621 id<NSURLProtocolClient> client([self client]);
6623 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6625 NSData *data(UIImagePNGRepresentation(icon));
6627 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6628 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6629 [client URLProtocol:self didLoadData:data];
6630 [client URLProtocolDidFinishLoading:self];
6634 - (void) startLoading {
6635 id<NSURLProtocolClient> client([self client]);
6636 NSURLRequest *request([self request]);
6638 NSURL *url([request URL]);
6639 NSString *href([url absoluteString]);
6641 NSString *path([href substringFromIndex:8]);
6642 NSRange slash([path rangeOfString:@"/"]);
6645 if (slash.location == NSNotFound) {
6649 command = [path substringToIndex:slash.location];
6650 path = [path substringFromIndex:(slash.location + 1)];
6653 Database *database([Database sharedInstance]);
6655 if ([command isEqualToString:@"package-icon"]) {
6658 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6659 Package *package([database packageWithName:path]);
6662 UIImage *icon([package icon]);
6663 [self _returnPNGWithImage:icon forRequest:request];
6664 } else if ([command isEqualToString:@"source-icon"]) {
6667 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6668 NSString *source(Simplify(path));
6669 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6671 icon = [UIImage applicationImageNamed:@"unknown.png"];
6672 [self _returnPNGWithImage:icon forRequest:request];
6673 } else if ([command isEqualToString:@"uikit-image"]) {
6676 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6677 UIImage *icon(_UIImageWithName(path));
6678 [self _returnPNGWithImage:icon forRequest:request];
6679 } else if ([command isEqualToString:@"section-icon"]) {
6682 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6683 NSString *section(Simplify(path));
6684 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6686 icon = [UIImage applicationImageNamed:@"unknown.png"];
6687 [self _returnPNGWithImage:icon forRequest:request];
6689 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6693 - (void) stopLoading {
6699 /* Sections Controller {{{ */
6700 @interface SectionsController : CYViewController <
6701 UITableViewDataSource,
6704 _transient Database *database_;
6705 NSMutableArray *sections_;
6706 NSMutableArray *filtered_;
6712 - (id) initWithDatabase:(Database *)database;
6713 - (void) reloadData;
6716 - (void) editButtonClicked;
6720 @implementation SectionsController
6723 [list_ setDataSource:nil];
6724 [list_ setDelegate:nil];
6726 [sections_ release];
6727 [filtered_ release];
6729 [accessory_ release];
6733 - (void) viewDidAppear:(BOOL)animated {
6734 [super viewDidAppear:animated];
6735 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6738 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6739 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6743 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6744 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6747 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6751 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6752 static NSString *reuseIdentifier = @"SectionCell";
6754 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6756 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6758 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6763 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6767 Section *section = [self sectionAtIndexPath:indexPath];
6768 NSString *name = [section name];
6771 if ([indexPath row] == 0) {
6774 title = UCLocalize("ALL_PACKAGES");
6777 name = [NSString stringWithString:name];
6778 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6781 title = UCLocalize("NO_SECTION");
6785 FilteredPackageController *table = [[[FilteredPackageController alloc]
6786 initWithDatabase:database_
6788 filter:@selector(isVisibleInSection:)
6792 [table setDelegate:delegate_];
6794 [[self navigationController] pushViewController:table animated:YES];
6797 - (NSString *) title { return UCLocalize("SECTIONS"); }
6799 - (id) initWithDatabase:(Database *)database {
6800 if ((self = [super init]) != nil) {
6801 database_ = database;
6803 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6805 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6806 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6808 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6809 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6810 [list_ setRowHeight:45.0f];
6811 [[self view] addSubview:list_];
6813 [list_ setDataSource:self];
6814 [list_ setDelegate:self];
6820 - (void) reloadData {
6821 NSArray *packages = [database_ packages];
6823 [sections_ removeAllObjects];
6824 [filtered_ removeAllObjects];
6827 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6828 SectionMap sections;
6829 sections.resize(64);
6831 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6835 for (Package *package in packages) {
6836 NSString *name([package section]);
6837 NSString *key(name == nil ? @"" : name);
6842 _profile(SectionsView$reloadData$Section)
6843 section = §ions[key];
6844 if (*section == nil) {
6845 _profile(SectionsView$reloadData$Section$Allocate)
6846 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6851 [*section addToCount];
6853 _profile(SectionsView$reloadData$Filter)
6854 if (![package valid] || ![package visible])
6858 [*section addToRow];
6862 _profile(SectionsView$reloadData$Section)
6863 section = [sections objectForKey:key];
6864 if (section == nil) {
6865 _profile(SectionsView$reloadData$Section$Allocate)
6866 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6867 [sections setObject:section forKey:key];
6872 [section addToCount];
6874 _profile(SectionsView$reloadData$Filter)
6875 if (![package valid] || ![package visible])
6885 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6886 [sections_ addObject:i->second];
6888 [sections_ addObjectsFromArray:[sections allValues]];
6891 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6893 for (Section *section in sections_) {
6894 size_t count([section row]);
6898 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6899 [section setCount:count];
6900 [filtered_ addObject:section];
6903 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6904 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
6905 style:UIBarButtonItemStylePlain
6907 action:@selector(editButtonClicked)
6908 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6914 - (void) resetView {
6916 [self editButtonClicked];
6919 - (void) editButtonClicked {
6920 if ((editing_ = !editing_))
6923 [delegate_ updateData];
6925 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6926 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6927 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6930 - (UIView *) accessoryView {
6936 /* Changes Controller {{{ */
6937 @interface ChangesController : CYViewController <
6938 UITableViewDataSource,
6941 _transient Database *database_;
6942 CFMutableArrayRef packages_;
6943 NSMutableArray *sections_;
6946 BOOL hasSentFirstLoad_;
6949 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6950 - (void) reloadData;
6954 @implementation ChangesController
6957 [list_ setDelegate:nil];
6958 [list_ setDataSource:nil];
6960 CFRelease(packages_);
6962 [sections_ release];
6967 - (void) viewDidAppear:(BOOL)animated {
6968 [super viewDidAppear:animated];
6969 if (!hasSentFirstLoad_) {
6970 hasSentFirstLoad_ = YES;
6971 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6973 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6977 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6978 NSInteger count([sections_ count]);
6979 return count == 0 ? 1 : count;
6982 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6983 if ([sections_ count] == 0)
6985 return [[sections_ objectAtIndex:section] name];
6988 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6989 if ([sections_ count] == 0)
6991 return [[sections_ objectAtIndex:section] count];
6994 - (Package *) packageAtIndex:(NSUInteger)index {
6995 return (Package *) CFArrayGetValueAtIndex(packages_, index);
6998 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6999 Section *section([sections_ objectAtIndex:[path section]]);
7000 NSInteger row([path row]);
7001 return [self packageAtIndex:([section row] + row)];
7004 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7005 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7007 cell = [[[PackageCell alloc] init] autorelease];
7008 [cell setPackage:[self packageAtIndexPath:path]];
7012 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7013 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7016 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7017 Package *package([self packageAtIndexPath:path]);
7018 PackageController *view([delegate_ packageController]);
7019 [view setDelegate:delegate_];
7020 [view setPackage:package];
7021 [[self navigationController] pushViewController:view animated:YES];
7025 - (void) refreshButtonClicked {
7026 [delegate_ beginUpdate];
7027 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7030 - (void) upgradeButtonClicked {
7031 [delegate_ distUpgrade];
7034 - (NSString *) title { return UCLocalize("CHANGES"); }
7036 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7037 if ((self = [super init]) != nil) {
7038 database_ = database;
7039 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7041 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7043 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7045 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7046 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7047 [list_ setRowHeight:73.0f];
7048 [[self view] addSubview:list_];
7050 [list_ setDataSource:self];
7051 [list_ setDelegate:self];
7053 delegate_ = delegate;
7057 - (void) _reloadPackages:(NSArray *)packages {
7059 for (Package *package in packages)
7061 [package uninstalled] && [package valid] && [package visible] ||
7062 [package upgradableAndEssential:YES]
7064 CFArrayAppendValue(packages_, package);
7067 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7071 - (void) reloadData {
7072 NSArray *packages = [database_ packages];
7074 CFArrayRemoveAllValues(packages_);
7076 [sections_ removeAllObjects];
7079 UIProgressHUD *hud([delegate_ addProgressHUD]);
7081 [hud setText:@"Loading Changes"];
7082 //NSLog(@"HUD:%@::%@", delegate_, hud);
7083 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7084 [delegate_ removeProgressHUD:hud];
7086 [self _reloadPackages:packages];
7089 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7090 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7091 Section *section = nil;
7095 bool unseens = false;
7097 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7099 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7100 Package *package = [self packageAtIndex:offset];
7102 BOOL uae = [package upgradableAndEssential:YES];
7108 _profile(ChangesController$reloadData$Remember)
7109 seen = [package seen];
7112 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7117 name = UCLocalize("UNKNOWN");
7119 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7123 _profile(ChangesController$reloadData$Allocate)
7124 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7125 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7126 [sections_ addObject:section];
7130 [section addToCount];
7131 } else if ([package ignored])
7132 [ignored addToCount];
7135 [upgradable addToCount];
7140 CFRelease(formatter);
7143 Section *last = [sections_ lastObject];
7144 size_t count = [last count];
7145 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7146 [sections_ removeLastObject];
7149 if ([ignored count] != 0)
7150 [sections_ insertObject:ignored atIndex:0];
7152 [sections_ insertObject:upgradable atIndex:0];
7157 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7158 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7159 style:UIBarButtonItemStylePlain
7161 action:@selector(upgradeButtonClicked)
7164 if (![delegate_ updating])
7165 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7166 initWithTitle:UCLocalize("REFRESH")
7167 style:UIBarButtonItemStylePlain
7169 action:@selector(refreshButtonClicked)
7175 /* Search Controller {{{ */
7176 @interface SearchController : FilteredPackageController <
7179 UISearchBar *search_;
7182 - (id) initWithDatabase:(Database *)database;
7183 - (void) reloadData;
7187 @implementation SearchController
7194 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7195 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7196 [search_ resignFirstResponder];
7200 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7201 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7205 - (NSString *) title { return nil; }
7207 - (id) initWithDatabase:(Database *)database {
7208 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7211 - (void)viewDidAppear:(BOOL)animated {
7212 [super viewDidAppear:animated];
7214 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7215 [search_ layoutSubviews];
7216 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7217 UITextField *textField = [search_ searchField];
7218 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7219 [search_ setDelegate:self];
7220 [textField setEnablesReturnKeyAutomatically:NO];
7221 [[self navigationItem] setTitleView:textField];
7225 - (void) _reloadData {
7228 - (void) reloadData {
7229 _profile(SearchController$reloadData)
7230 [packages_ reloadData];
7233 [packages_ resetCursor];
7236 - (void) didSelectPackage:(Package *)package {
7237 [search_ resignFirstResponder];
7238 [super didSelectPackage:package];
7243 /* Settings Controller {{{ */
7244 @interface SettingsController : CYViewController <
7245 UITableViewDataSource,
7248 _transient Database *database_;
7251 UITableView *table_;
7252 UISwitch *subscribedSwitch_;
7253 UISwitch *ignoredSwitch_;
7254 UITableViewCell *subscribedCell_;
7255 UITableViewCell *ignoredCell_;
7258 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7262 @implementation SettingsController
7266 if (package_ != nil)
7269 [subscribedSwitch_ release];
7270 [ignoredSwitch_ release];
7271 [subscribedCell_ release];
7272 [ignoredCell_ release];
7277 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7278 if (package_ == nil)
7284 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7285 if (package_ == nil)
7291 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7292 return UCLocalize("SHOW_ALL_CHANGES_EX");
7295 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7296 if (package_ == nil)
7299 NSMutableDictionary *metadata([package_ metadata]);
7302 if (NSNumber *number = [metadata objectForKey:key])
7303 before = [number boolValue];
7307 if (value != before) {
7308 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7310 [delegate_ updateData];
7314 - (void) onSubscribed:(id)control {
7315 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7318 - (void) onIgnored:(id)control {
7319 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
7322 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7323 if (package_ == nil)
7326 switch ([indexPath row]) {
7327 case 0: return subscribedCell_;
7328 case 1: return ignoredCell_;
7336 - (NSString *) title { return UCLocalize("SETTINGS"); }
7338 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7339 if ((self = [super init])) {
7340 database_ = database;
7341 name_ = [package retain];
7343 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7345 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7346 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7347 [[self view] addSubview:table_];
7349 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7350 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7351 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7353 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7354 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7355 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7357 subscribedCell_ = [[UITableViewCell alloc] init];
7358 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7359 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7360 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7362 ignoredCell_ = [[UITableViewCell alloc] init];
7363 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7364 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7365 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7367 [table_ setDataSource:self];
7368 [table_ setDelegate:self];
7373 - (void) reloadData {
7374 if (package_ != nil)
7375 [package_ autorelease];
7376 package_ = [database_ packageWithName:name_];
7377 if (package_ != nil) {
7379 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7380 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7383 [table_ reloadData];
7388 /* Signature Controller {{{ */
7389 @interface SignatureController : CYBrowserController {
7390 _transient Database *database_;
7394 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7398 @implementation SignatureController
7405 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7407 [super webView:view didClearWindowObject:window forFrame:frame];
7410 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7411 if ((self = [super init]) != nil) {
7412 database_ = database;
7413 package_ = [package retain];
7418 - (void) reloadData {
7419 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7425 /* Role Controller {{{ */
7426 @interface RoleController : CYViewController <
7427 UITableViewDataSource,
7430 _transient Database *database_;
7431 // XXX: ok, "roledelegate_"?...
7432 _transient id roledelegate_;
7433 UITableView *table_;
7434 UISegmentedControl *segment_;
7438 - (void) showDoneButton;
7439 - (void) resizeSegmentedControl;
7443 @implementation RoleController
7447 [container_ release];
7452 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7453 if ((self = [super init])) {
7454 database_ = database;
7455 roledelegate_ = delegate;
7457 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7459 NSArray *items = [NSArray arrayWithObjects:
7461 UCLocalize("HACKER"),
7462 UCLocalize("DEVELOPER"),
7464 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7465 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7466 [container_ addSubview:segment_];
7469 if ([Role_ isEqualToString:@"User"]) index = 0;
7470 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7471 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7473 [segment_ setSelectedSegmentIndex:index];
7474 [self showDoneButton];
7477 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7478 [self resizeSegmentedControl];
7480 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7481 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7482 [table_ setDelegate:self];
7483 [table_ setDataSource:self];
7484 [[self view] addSubview:table_];
7485 [table_ reloadData];
7489 - (void) resizeSegmentedControl {
7490 CGFloat width = [[self view] frame].size.width;
7491 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7494 - (void) viewWillAppear:(BOOL)animated {
7495 [super viewWillAppear:animated];
7497 [self resizeSegmentedControl];
7500 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7501 [self resizeSegmentedControl];
7504 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7505 [self resizeSegmentedControl];
7509 NSString *role(nil);
7511 switch ([segment_ selectedSegmentIndex]) {
7512 case 0: role = @"User"; break;
7513 case 1: role = @"Hacker"; break;
7514 case 2: role = @"Developer"; break;
7519 if (![role isEqualToString:Role_]) {
7520 bool rolling(Role_ == nil);
7523 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7527 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7532 [roledelegate_ loadData];
7534 [roledelegate_ updateData];
7538 - (void) segmentChanged:(UISegmentedControl *)control {
7539 [self showDoneButton];
7542 - (void) saveAndClose {
7545 [[self navigationItem] setRightBarButtonItem:nil];
7546 [[self navigationController] dismissModalViewControllerAnimated:YES];
7549 - (void) doneButtonClicked {
7550 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7551 [spinner startAnimating];
7552 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7553 [[self navigationItem] setRightBarButtonItem:spinItem];
7555 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7558 - (void) showDoneButton {
7559 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7560 initWithTitle:UCLocalize("DONE")
7561 style:UIBarButtonItemStyleDone
7563 action:@selector(doneButtonClicked)
7564 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
7567 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7568 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7572 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7576 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7577 return nil; // This method is required by the protocol.
7580 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7582 return UCLocalize("ROLE_EX");
7584 return [NSString stringWithFormat:
7585 @"%@: %@\n%@: %@\n%@: %@",
7586 UCLocalize("USER"), UCLocalize("USER_EX"),
7587 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7588 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7593 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7594 return section == 3 ? 44.0f : 0;
7597 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7598 return section == 3 ? container_ : nil;
7603 /* Stash Controller {{{ */
7604 @interface CYStashController : CYViewController {
7605 // XXX: just delete these things
7606 _transient UIActivityIndicatorView *spinner_;
7607 _transient UILabel *status_;
7608 _transient UILabel *caption_;
7612 @implementation CYStashController
7614 if ((self = [super init])) {
7615 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7617 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
7618 CGRect spinrect = [spinner_ frame];
7619 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7620 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7621 [spinner_ setFrame:spinrect];
7622 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7623 [[self view] addSubview:spinner_];
7624 [spinner_ startAnimating];
7627 captrect.size.width = [[self view] frame].size.width;
7628 captrect.size.height = 40.0f;
7629 captrect.origin.x = 0;
7630 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7631 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
7632 [caption_ setText:@"Initializing Filesystem"];
7633 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7634 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7635 [caption_ setTextColor:[UIColor whiteColor]];
7636 [caption_ setBackgroundColor:[UIColor clearColor]];
7637 [caption_ setShadowColor:[UIColor blackColor]];
7638 [caption_ setTextAlignment:UITextAlignmentCenter];
7639 [[self view] addSubview:caption_];
7642 statusrect.size.width = [[self view] frame].size.width;
7643 statusrect.size.height = 30.0f;
7644 statusrect.origin.x = 0;
7645 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7646 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
7647 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7648 [status_ setText:@"(Cydia will exit when complete.)"];
7649 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7650 [status_ setTextColor:[UIColor whiteColor]];
7651 [status_ setBackgroundColor:[UIColor clearColor]];
7652 [status_ setShadowColor:[UIColor blackColor]];
7653 [status_ setTextAlignment:UITextAlignmentCenter];
7654 [[self view] addSubview:status_];
7658 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7659 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7664 /* Cydia Container {{{ */
7665 @interface CYContainer : UIViewController <ProgressDelegate> {
7666 _transient Database *database_;
7667 RefreshBar *refreshbar_;
7671 // XXX: ok, "updatedelegate_"?...
7672 _transient NSObject<CydiaDelegate> *updatedelegate_;
7673 // XXX: can't we query for this variable when we need it?
7674 _transient UITabBarController *root_;
7677 - (void) setTabBarController:(UITabBarController *)controller;
7679 - (void) dropBar:(BOOL)animated;
7680 - (void) beginUpdate;
7681 - (void) raiseBar:(BOOL)animated;
7686 @implementation CYContainer
7688 - (BOOL) _reallyWantsFullScreenLayout {
7692 // NOTE: UIWindow only sends the top controller these messages,
7693 // So we have to forward them on.
7695 - (void) viewDidAppear:(BOOL)animated {
7696 [super viewDidAppear:animated];
7697 [root_ viewDidAppear:animated];
7700 - (void) viewWillAppear:(BOOL)animated {
7701 [super viewWillAppear:animated];
7702 [root_ viewWillAppear:animated];
7705 - (void) viewDidDisappear:(BOOL)animated {
7706 [super viewDidDisappear:animated];
7707 [root_ viewDidDisappear:animated];
7710 - (void) viewWillDisappear:(BOOL)animated {
7711 [super viewWillDisappear:animated];
7712 [root_ viewWillDisappear:animated];
7715 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7716 return ![updatedelegate_ hudIsShowing] && (IsWildcat_ || orientation == UIInterfaceOrientationPortrait);
7719 - (void) setTabBarController:(UITabBarController *)controller {
7721 [[self view] addSubview:[root_ view]];
7724 - (void) setUpdate:(NSDate *)date {
7728 - (void) beginUpdate {
7730 [refreshbar_ start];
7735 detachNewThreadSelector:@selector(performUpdate)
7741 - (void) performUpdate { _pooled
7743 status.setDelegate(self);
7744 [database_ updateWithStatus:status];
7747 performSelectorOnMainThread:@selector(completeUpdate)
7753 - (void) completeUpdate {
7758 [self raiseBar:YES];
7760 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7763 - (void) cancelUpdate {
7765 [self raiseBar:YES];
7767 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7770 - (void) cancelPressed {
7771 [self cancelUpdate];
7778 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7779 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7782 - (void) startProgress {
7785 - (void) setProgressTitle:(NSString *)title {
7787 performSelectorOnMainThread:@selector(_setProgressTitle:)
7793 - (bool) isCancelling:(size_t)received {
7797 - (void) setProgressPercent:(float)percent {
7799 performSelectorOnMainThread:@selector(_setProgressPercent:)
7800 withObject:[NSNumber numberWithFloat:percent]
7805 - (void) addProgressOutput:(NSString *)output {
7807 performSelectorOnMainThread:@selector(_addProgressOutput:)
7813 - (void) _setProgressTitle:(NSString *)title {
7814 [refreshbar_ setPrompt:title];
7817 - (void) _setProgressPercent:(NSNumber *)percent {
7818 [refreshbar_ setProgress:[percent floatValue]];
7821 - (void) _addProgressOutput:(NSString *)output {
7824 - (void) setUpdateDelegate:(id)delegate {
7825 updatedelegate_ = delegate;
7828 - (CGFloat) statusBarHeight {
7829 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7830 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7832 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7836 - (void) dropBar:(BOOL)animated {
7841 [[self view] addSubview:refreshbar_];
7843 CGFloat sboffset = [self statusBarHeight];
7845 CGRect barframe = [refreshbar_ frame];
7846 barframe.origin.y = sboffset;
7847 [refreshbar_ setFrame:barframe];
7850 [UIView beginAnimations:nil context:NULL];
7851 CGRect viewframe = [[root_ view] frame];
7852 viewframe.origin.y += barframe.size.height + sboffset;
7853 viewframe.size.height -= barframe.size.height + sboffset;
7854 [[root_ view] setFrame:viewframe];
7856 [UIView commitAnimations];
7858 // Ensure bar has the proper width for our view, it might have changed
7859 barframe.size.width = viewframe.size.width;
7860 [refreshbar_ setFrame:barframe];
7862 // XXX: fix Apple's layout bug
7863 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7866 - (void) raiseBar:(BOOL)animated {
7871 [refreshbar_ removeFromSuperview];
7873 CGFloat sboffset = [self statusBarHeight];
7876 [UIView beginAnimations:nil context:NULL];
7877 CGRect barframe = [refreshbar_ frame];
7878 CGRect viewframe = [[root_ view] frame];
7879 viewframe.origin.y -= barframe.size.height + sboffset;
7880 viewframe.size.height += barframe.size.height + sboffset;
7881 [[root_ view] setFrame:viewframe];
7883 [UIView commitAnimations];
7885 // XXX: fix Apple's layout bug
7886 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7889 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7890 // XXX: fix Apple's layout bug
7891 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7894 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7900 // XXX: fix Apple's layout bug
7901 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7904 - (void) statusBarFrameChanged:(NSNotification *)notification {
7912 [refreshbar_ release];
7913 [[NSNotificationCenter defaultCenter] removeObserver:self];
7917 - (id) initWithDatabase:(Database *)database {
7918 if ((self = [super init]) != nil) {
7919 database_ = database;
7921 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7922 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7924 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7941 @interface Cydia : UIApplication <
7942 ConfirmationControllerDelegate,
7943 ProgressControllerDelegate,
7945 UINavigationControllerDelegate,
7946 UITabBarControllerDelegate
7948 // XXX: evaluate all fields for _transient
7951 CYContainer *container_;
7952 CYTabBarController *tabbar_;
7954 NSMutableArray *essential_;
7955 NSMutableArray *broken_;
7957 Database *database_;
7961 UIKeyboard *keyboard_;
7964 SectionsController *sections_;
7965 ChangesController *changes_;
7966 ManageController *manage_;
7967 SearchController *search_;
7968 SourceTable *sources_;
7969 InstalledController *installed_;
7972 CYStashController *stash_;
7977 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7978 - (void) setPage:(CYViewController *)page;
7983 static _finline void _setHomePage(Cydia *self) {
7984 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7987 @implementation Cydia
7989 - (void) beginUpdate {
7990 [container_ beginUpdate];
7994 return [container_ updating];
7997 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
8002 if ([broken_ count] != 0) {
8003 int count = [broken_ count];
8005 UIAlertView *alert = [[[UIAlertView alloc]
8006 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8007 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8009 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8010 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8013 [alert setContext:@"fixhalf"];
8015 } else if (!Ignored_ && [essential_ count] != 0) {
8016 int count = [essential_ count];
8018 UIAlertView *alert = [[[UIAlertView alloc]
8019 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8020 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8022 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8023 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8026 [alert setContext:@"upgrade"];
8031 - (void) _saveConfig {
8034 NSString *error(nil);
8035 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8037 NSError *error(nil);
8038 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8039 NSLog(@"failure to save metadata data: %@", error);
8042 NSLog(@"failure to serialize metadata: %@", error);
8050 - (void) _updateData {
8053 /* XXX: this is just stupid */
8054 if (tag_ != 1 && sections_ != nil)
8055 [sections_ reloadData];
8056 if (tag_ != 2 && changes_ != nil)
8057 [changes_ reloadData];
8058 if (tag_ != 4 && search_ != nil)
8059 [search_ reloadData];
8061 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8064 - (int)indexOfTabWithTag:(int)tag {
8066 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8067 if ([[controller tabBarItem] tag] == tag)
8075 - (void) _refreshIfPossible {
8076 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8078 bool recently = false;
8079 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8080 if (update != nil) {
8081 NSTimeInterval interval([update timeIntervalSinceNow]);
8082 if (interval <= 0 && interval > -(15*60))
8086 // Don't automatic refresh if:
8087 // - We already refreshed recently.
8088 // - We already auto-refreshed this launch.
8089 // - Auto-refresh is disabled.
8090 if (recently || loaded_ || ManualRefresh) {
8091 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8093 // If we are cancelling due to ManualRefresh or a recent refresh
8094 // we need to make sure it knows it's already loaded.
8098 // We are going to load, so remember that.
8102 SCNetworkReachabilityFlags flags; {
8103 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8104 SCNetworkReachabilityGetFlags(reachability, &flags);
8105 CFRelease(reachability);
8108 // XXX: this elaborate mess is what Apple is using to determine this? :(
8109 // XXX: do we care if the user has to intervene? maybe that's ok?
8111 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8112 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8113 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8114 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8115 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8116 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8120 // If we can reach the server, auto-refresh!
8122 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8127 - (void) refreshIfPossible {
8128 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8131 - (void) _reloadData {
8132 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8133 [hud setText:UCLocalize("RELOADING_DATA")];
8135 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8138 [self removeProgressHUD:hud];
8142 [essential_ removeAllObjects];
8143 [broken_ removeAllObjects];
8145 NSArray *packages([database_ packages]);
8146 for (Package *package in packages) {
8148 [broken_ addObject:package];
8149 if ([package upgradableAndEssential:NO]) {
8150 if ([package essential])
8151 [essential_ addObject:package];
8156 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8158 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8159 [changesItem setBadgeValue:badge];
8160 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8162 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8163 [self setApplicationBadge:badge];
8165 [self setApplicationBadgeString:badge];
8167 [changesItem setBadgeValue:nil];
8168 [changesItem setAnimatedBadge:NO];
8170 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8171 [self removeApplicationBadge];
8172 else // XXX: maybe use setApplicationBadgeString also?
8173 [self setApplicationIconBadgeNumber:0];
8178 [self refreshIfPossible];
8181 - (void) updateData {
8182 [database_ setVisible];
8191 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8192 _assert(file != NULL);
8194 for (NSString *key in [Sources_ allKeys]) {
8195 NSDictionary *source([Sources_ objectForKey:key]);
8197 fprintf(file, "%s %s %s\n",
8198 [[source objectForKey:@"Type"] UTF8String],
8199 [[source objectForKey:@"URI"] UTF8String],
8200 [[source objectForKey:@"Distribution"] UTF8String]
8208 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8209 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8211 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8212 [container_ presentModalViewController:navigation animated:YES];
8215 detachNewThreadSelector:@selector(update_)
8218 title:UCLocalize("UPDATING_SOURCES")
8222 - (void) reloadData {
8223 @synchronized (self) {
8229 pkgProblemResolver *resolver = [database_ resolver];
8231 resolver->InstallProtect();
8232 if (!resolver->Resolve(true))
8236 - (CGRect) popUpBounds {
8237 return [[tabbar_ view] bounds];
8241 if (![database_ prepare])
8244 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8245 [page setDelegate:self];
8246 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8247 [confirm_ setDelegate:self];
8250 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8251 [container_ presentModalViewController:confirm_ animated:YES];
8257 @synchronized (self) {
8262 - (void) clearPackage:(Package *)package {
8263 @synchronized (self) {
8270 - (void) installPackages:(NSArray *)packages {
8271 @synchronized (self) {
8272 for (Package *package in packages)
8279 - (void) installPackage:(Package *)package {
8280 @synchronized (self) {
8287 - (void) removePackage:(Package *)package {
8288 @synchronized (self) {
8295 - (void) distUpgrade {
8296 @synchronized (self) {
8297 if (![database_ upgrade])
8304 @synchronized (self) {
8309 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8310 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8312 if (navigation != nil) {
8313 [navigation pushViewController:progress animated:YES];
8315 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8317 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8318 [container_ presentModalViewController:navigation animated:YES];
8322 detachNewThreadSelector:@selector(perform)
8325 title:UCLocalize("RUNNING")
8329 - (void) progressControllerIsComplete:(ProgressController *)progress {
8333 - (void) setPage:(CYViewController *)page {
8334 [page setDelegate:self];
8336 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8337 [navController setViewControllers:[NSArray arrayWithObject:page]];
8338 for (CYNavigationController *page in [tabbar_ viewControllers])
8339 if (page != navController)
8340 [page setViewControllers:nil];
8343 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8344 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8345 [browser loadURL:url];
8349 - (SectionsController *) sectionsController {
8350 if (sections_ == nil)
8351 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8355 - (ChangesController *) changesController {
8356 if (changes_ == nil)
8357 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8361 - (ManageController *) manageController {
8362 if (manage_ == nil) {
8363 manage_ = (ManageController *) [[self
8364 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8365 withClass:[ManageController class]
8368 queueDelegate_ = manage_;
8373 - (SearchController *) searchController {
8375 search_ = [[SearchController alloc] initWithDatabase:database_];
8379 - (SourceTable *) sourcesController {
8380 if (sources_ == nil)
8381 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8385 - (InstalledController *) installedController {
8386 if (installed_ == nil) {
8387 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8389 queueDelegate_ = installed_;
8394 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8395 int tag = [[viewController tabBarItem] tag];
8397 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8399 } else if (tag_ == 1) {
8400 [[self sectionsController] resetView];
8404 case kCydiaTag: _setHomePage(self); break;
8406 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8407 case kChangesTag: [self setPage:[self changesController]]; break;
8408 case kManageTag: [self setPage:[self manageController]]; break;
8409 case kInstalledTag: [self setPage:[self installedController]]; break;
8410 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8411 case kSearchTag: [self setPage:[self searchController]]; break;
8419 - (void) showSettings {
8420 RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease];
8421 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8423 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8424 [container_ presentModalViewController:nav animated:YES];
8427 - (void) setPackageController:(PackageController *)view {
8429 [view setPackage:nil];
8433 - (PackageController *) _packageController {
8434 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8437 - (PackageController *) packageController {
8438 return [self _packageController];
8441 // Returns the navigation controller for the queuing badge.
8442 - (id) queueBadgeController {
8443 int index = [self indexOfTabWithTag:kManageTag];
8445 index = [self indexOfTabWithTag:kInstalledTag];
8447 return [[tabbar_ viewControllers] objectAtIndex:index];
8450 - (void) cancelAndClear:(bool)clear {
8451 @synchronized (self) {
8454 pkgCacheFile &cache([database_ cache]);
8455 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
8456 // Unmark method taken from Synaptic Package Manager.
8457 // Thanks for being sane, unlike Aptitude.
8458 if (!cache[iterator].Keep()) {
8459 cache->MarkKeep(iterator, false);
8460 cache->SetReInstall(iterator, false);
8466 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
8470 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8473 // Show the changes in the current view.
8474 [(CYNavigationController *) [tabbar_ selectedViewController] reloadData];
8475 [queueDelegate_ queueStatusDidChange];
8479 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8480 NSString *context([alert context]);
8482 if ([context isEqualToString:@"fixhalf"]) {
8483 if (button == [alert firstOtherButtonIndex]) {
8484 @synchronized (self) {
8485 for (Package *broken in broken_) {
8488 NSString *id = [broken id];
8489 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8490 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8491 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8492 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8498 } else if (button == [alert cancelButtonIndex]) {
8499 [broken_ removeAllObjects];
8503 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8504 } else if ([context isEqualToString:@"upgrade"]) {
8505 if (button == [alert firstOtherButtonIndex]) {
8506 @synchronized (self) {
8507 for (Package *essential in essential_)
8508 [essential install];
8513 } else if (button == [alert firstOtherButtonIndex] + 1) {
8515 } else if (button == [alert cancelButtonIndex]) {
8519 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8523 - (void) system:(NSString *)command { _pooled
8524 system([command UTF8String]);
8527 - (void) applicationWillSuspend {
8529 [super applicationWillSuspend];
8532 - (BOOL) hudIsShowing {
8536 - (void) applicationSuspend:(__GSEvent *)event {
8537 // Use external process status API internally.
8538 // This is probably a really bad idea.
8539 uint64_t status = 0;
8541 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8542 notify_get_state(notify_token, &status);
8543 notify_cancel(notify_token);
8546 if (![self hudIsShowing] && status == 0)
8547 [super applicationSuspend:event];
8550 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8551 if (![self hudIsShowing])
8552 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8555 - (void) _setSuspended:(BOOL)value {
8556 if (![self hudIsShowing])
8557 [super _setSuspended:value];
8560 - (UIProgressHUD *) addProgressHUD {
8561 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8562 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8564 [window_ setUserInteractionEnabled:NO];
8567 UIViewController *target = container_;
8568 while ([target modalViewController] != nil) target = [target modalViewController];
8569 [[target view] addSubview:hud];
8575 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8577 [hud removeFromSuperview];
8578 [window_ setUserInteractionEnabled:YES];
8582 - (CYViewController *) pageForPackage:(NSString *)name {
8583 if (Package *package = [database_ packageWithName:name]) {
8584 PackageController *view([self packageController]);
8585 [view setPackage:package];
8588 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8589 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8590 return [self _pageForURL:url withClass:[CYBrowserController class]];
8594 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8598 NSString *href([url absoluteString]);
8599 if ([href hasPrefix:@"apptapp://package/"])
8600 return [self pageForPackage:[href substringFromIndex:18]];
8602 NSString *scheme([[url scheme] lowercaseString]);
8603 if (![scheme isEqualToString:@"cydia"])
8605 NSString *path([url absoluteString]);
8606 if ([path length] < 8)
8608 path = [path substringFromIndex:8];
8609 if (![path hasPrefix:@"/"])
8610 path = [@"/" stringByAppendingString:path];
8612 if ([path isEqualToString:@"/add-source"])
8613 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8614 else if ([path isEqualToString:@"/storage"])
8615 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8616 else if ([path isEqualToString:@"/sources"])
8617 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8618 else if ([path isEqualToString:@"/packages"])
8619 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8620 else if ([path hasPrefix:@"/url/"])
8621 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8622 else if ([path hasPrefix:@"/launch/"])
8623 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8624 else if ([path hasPrefix:@"/package-settings/"])
8625 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8626 else if ([path hasPrefix:@"/package-signature/"])
8627 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8628 else if ([path hasPrefix:@"/package/"])
8629 return [self pageForPackage:[path substringFromIndex:9]];
8630 else if ([path hasPrefix:@"/files/"]) {
8631 NSString *name = [path substringFromIndex:7];
8633 if (Package *package = [database_ packageWithName:name]) {
8634 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8635 [files setPackage:package];
8643 - (void) applicationOpenURL:(NSURL *)url {
8644 [super applicationOpenURL:url];
8646 if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
8647 [self setPage:page];
8649 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8653 - (void) applicationWillResignActive:(UIApplication *)application {
8654 // Stop refreshing if you get a phone call or lock the device.
8655 if ([container_ updating])
8656 [container_ cancelUpdate];
8658 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8659 [super applicationWillResignActive:application];
8662 - (void) addStashController {
8663 stash_ = [[CYStashController alloc] init];
8664 [window_ addSubview:[stash_ view]];
8667 - (void) removeStashController {
8668 [[stash_ view] removeFromSuperview];
8673 [self setIdleTimerDisabled:YES];
8675 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8676 [self setStatusBarShowsProgress:YES];
8677 UpdateExternalStatus(1);
8679 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8681 UpdateExternalStatus(0);
8682 [self setStatusBarShowsProgress:NO];
8684 [self removeStashController];
8686 if (ExecFork() == 0) {
8687 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8688 perror("launchctl stop");
8692 - (void) setupTabBarController {
8693 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8694 [tabbar_ setDelegate:self];
8696 NSMutableArray *items([NSMutableArray arrayWithObjects:
8697 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8698 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8699 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8700 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8704 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8705 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8707 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8710 NSMutableArray *controllers([NSMutableArray array]);
8712 for (UITabBarItem *item in items) {
8713 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8714 [controller setTabBarItem:item];
8715 [controllers addObject:controller];
8718 [tabbar_ setViewControllers:controllers];
8721 - (void) applicationDidFinishLaunching:(id)unused {
8722 [CYBrowserController _initialize];
8724 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8726 Font12_ = [[UIFont systemFontOfSize:12] retain];
8727 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8728 Font14_ = [[UIFont systemFontOfSize:14] retain];
8729 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8730 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8734 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8735 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8737 UIScreen *screen([UIScreen mainScreen]);
8739 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8740 [window_ orderFront:self];
8741 [window_ makeKey:self];
8742 [window_ setHidden:NO];
8745 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8746 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8747 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8748 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8749 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8750 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8751 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8752 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8753 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8756 [self addStashController];
8757 // XXX: this would be much cleaner as a yieldToSelector:
8758 // that way the removeStashController could happen right here inline
8759 // we also could no longer require the useless stash_ field anymore
8760 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8764 database_ = [Database sharedInstance];
8766 [self setupTabBarController];
8768 container_ = [[CYContainer alloc] initWithDatabase:database_];
8769 [container_ setUpdateDelegate:self];
8770 [container_ setTabBarController:tabbar_];
8771 [window_ addSubview:[container_ view]];
8773 // Show pinstripes while loading data.
8774 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8776 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8783 [self showSettings];
8787 [window_ setUserInteractionEnabled:NO];
8789 UIView *container = [[[UIView alloc] init] autorelease];
8790 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8792 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
8793 [spinner startAnimating];
8794 [container addSubview:spinner];
8796 UILabel *label = [[[UILabel alloc] init] autorelease];
8797 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8798 [label setBackgroundColor:[UIColor clearColor]];
8799 [label setTextColor:[UIColor blackColor]];
8800 [label setShadowColor:[UIColor whiteColor]];
8801 [label setShadowOffset:CGSizeMake(0, 1)];
8802 [label setText:UCLocalize("LOADING_DATA")];
8803 [container addSubview:label];
8805 CGSize viewsize = [[tabbar_ view] frame].size;
8806 CGSize spinnersize = [spinner bounds].size;
8807 CGSize textsize = [[label text] sizeWithFont:[label font]];
8808 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8810 CGRect containrect = {
8811 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8812 CGSizeMake(bothwidth, spinnersize.height)
8815 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8823 [container setFrame:containrect];
8824 [spinner setFrame:spinrect];
8825 [label setFrame:textrect];
8826 [[container_ view] addSubview:container];
8831 // Show the home page
8832 [tabbar_ setSelectedIndex:0];
8834 [window_ setUserInteractionEnabled:YES];
8836 // XXX: does this actually slow anything down?
8837 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8838 [container removeFromSuperview];
8841 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8842 if (item != nil && IsWildcat_) {
8843 [sheet showFromBarButtonItem:item animated:YES];
8845 [sheet showInView:window_];
8852 id Alloc_(id self, SEL selector) {
8853 id object = alloc_(self, selector);
8854 lprintf("[%s]A-%p\n", self->isa->name, object);
8859 id Dealloc_(id self, SEL selector) {
8860 id object = dealloc_(self, selector);
8861 lprintf("[%s]D-%p\n", self->isa->name, object);
8865 Class $WebDefaultUIKitDelegate;
8867 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8868 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8869 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8870 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8873 static NSNumber *shouldPlayKeyboardSounds;
8877 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8879 case 1104: // Keyboard Button Clicked
8880 case 1105: // Keyboard Delete Repeated
8881 if (shouldPlayKeyboardSounds == nil) {
8882 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8883 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8886 if (![shouldPlayKeyboardSounds boolValue])
8890 _UIHardware$_playSystemSound$(self, _cmd, sound);
8894 int main(int argc, char *argv[]) { _pooled
8897 if (Class $UIDevice = objc_getClass("UIDevice")) {
8898 UIDevice *device([$UIDevice currentDevice]);
8899 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8903 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8905 /* Library Hacks {{{ */
8906 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8908 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8909 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8910 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8911 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8912 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8915 $UIHardware = objc_getClass("UIHardware");
8916 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8917 if (UIHardware$_playSystemSound$ != NULL) {
8918 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8919 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8922 /* Set Locale {{{ */
8923 Locale_ = CFLocaleCopyCurrent();
8924 Languages_ = [NSLocale preferredLanguages];
8925 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8926 //NSLog(@"%@", [Languages_ description]);
8929 if (Languages_ == nil || [Languages_ count] == 0)
8930 // XXX: consider just setting to C and then falling through?
8933 lang = [[Languages_ objectAtIndex:0] UTF8String];
8934 setenv("LANG", lang, true);
8937 //std::setlocale(LC_ALL, lang);
8938 NSLog(@"Setting Language: %s", lang);
8941 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8943 /* Parse Arguments {{{ */
8944 bool substrate(false);
8950 for (int argi(1); argi != argc; ++argi)
8951 if (strcmp(argv[argi], "--") == 0) {
8953 argv[argi] = argv[0];
8959 for (int argi(1); argi != arge; ++argi)
8960 if (strcmp(args[argi], "--substrate") == 0)
8963 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8967 App_ = [[NSBundle mainBundle] bundlePath];
8968 Home_ = NSHomeDirectory();
8974 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8975 alloc_ = alloc->method_imp;
8976 alloc->method_imp = (IMP) &Alloc_;*/
8978 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8979 dealloc_ = dealloc->method_imp;
8980 dealloc->method_imp = (IMP) &Dealloc_;*/
8982 /* System Information {{{ */
8986 size = sizeof(maxproc);
8987 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8988 perror("sysctlbyname(\"kern.maxproc\", ?)");
8989 else if (maxproc < 64) {
8991 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8992 perror("sysctlbyname(\"kern.maxproc\", #)");
8995 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8996 char *osversion = new char[size];
8997 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8998 perror("sysctlbyname(\"kern.osversion\", ?)");
9000 System_ = [NSString stringWithUTF8String:osversion];
9002 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9003 char *machine = new char[size];
9004 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9005 perror("sysctlbyname(\"hw.machine\", ?)");
9009 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9010 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9011 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9012 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9016 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9017 NSData *data((NSData *) ecid);
9018 size_t length([data length]);
9019 uint8_t bytes[length];
9020 [data getBytes:bytes];
9021 char string[length * 2 + 1];
9022 for (size_t i(0); i != length; ++i)
9023 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9024 ChipID_ = [NSString stringWithUTF8String:string];
9028 IOObjectRelease(service);
9032 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9034 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9035 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9036 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9038 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9039 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9040 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9042 if (mcc != NULL && mnc != NULL)
9043 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9050 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9051 Build_ = [system objectForKey:@"ProductBuildVersion"];
9052 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9053 Product_ = [info objectForKey:@"SafariProductVersion"];
9054 Safari_ = [info objectForKey:@"CFBundleVersion"];
9057 /* Load Database {{{ */
9059 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9061 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9063 if (Metadata_ == NULL)
9064 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9066 Settings_ = [Metadata_ objectForKey:@"Settings"];
9068 Packages_ = [Metadata_ objectForKey:@"Packages"];
9069 Sections_ = [Metadata_ objectForKey:@"Sections"];
9070 Sources_ = [Metadata_ objectForKey:@"Sources"];
9072 Token_ = [Metadata_ objectForKey:@"Token"];
9075 if (Settings_ != nil)
9076 Role_ = [Settings_ objectForKey:@"Role"];
9078 if (Packages_ == nil) {
9079 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
9080 [Metadata_ setObject:Packages_ forKey:@"Packages"];
9083 if (Sections_ == nil) {
9084 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9085 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9088 if (Sources_ == nil) {
9089 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9090 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9094 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9096 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9097 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9098 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9099 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9100 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9101 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9103 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9105 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9106 unlink("/tmp/.cydia.fw");
9108 } else if (access("/User", F_OK) != 0 || version < 2) {
9111 system("/usr/libexec/cydia/firmware.sh");
9115 _assert([[NSFileManager defaultManager]
9116 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9117 withIntermediateDirectories:YES
9122 if (access("/tmp/cydia.chk", F_OK) == 0) {
9123 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9124 _assert(errno == ENOENT);
9125 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9126 _assert(errno == ENOENT);
9129 /* APT Initialization {{{ */
9130 _assert(pkgInitConfig(*_config));
9131 _assert(pkgInitSystem(*_config, _system));
9134 _config->Set("APT::Acquire::Translation", lang);
9136 // XXX: this timeout might be important :(
9137 //_config->Set("Acquire::http::Timeout", 15);
9139 _config->Set("Acquire::http::MaxParallel", 3);
9141 /* Color Choices {{{ */
9142 space_ = CGColorSpaceCreateDeviceRGB();
9144 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9145 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9146 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9147 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9148 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9149 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9150 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9151 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9152 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9154 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9155 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9157 /* UIKit Configuration {{{ */
9158 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9159 if ($GSFontSetUseLegacyFontMetrics != NULL)
9160 $GSFontSetUseLegacyFontMetrics(YES);
9162 // XXX: I have a feeling this was important
9163 //UIKeyboardDisableAutomaticAppearance();
9166 Colon_ = UCLocalize("COLON_DELIMITED");
9167 Error_ = UCLocalize("ERROR");
9168 Warning_ = UCLocalize("WARNING");
9171 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9173 CGColorSpaceRelease(space_);