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_;
1710 _transient NSString *section$_;
1717 CYString installed_;
1723 CYString depiction_;
1734 NSMutableArray *tags_;
1737 NSArray *relationships_;
1739 NSMutableDictionary *metadata_;
1740 _transient NSDate *firstSeen_;
1741 _transient NSDate *lastSeen_;
1745 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1746 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1748 - (pkgCache::PkgIterator) iterator;
1751 - (NSString *) section;
1752 - (NSString *) simpleSection;
1754 - (NSString *) longSection;
1755 - (NSString *) shortSection;
1759 - (Address *) maintainer;
1761 - (NSString *) longDescription;
1762 - (NSString *) shortDescription;
1765 - (NSMutableDictionary *) metadata;
1767 - (BOOL) subscribed;
1770 - (NSString *) latest;
1771 - (NSString *) installed;
1772 - (BOOL) uninstalled;
1775 - (BOOL) upgradableAndEssential:(BOOL)essential;
1778 - (BOOL) unfiltered;
1782 - (BOOL) halfConfigured;
1783 - (BOOL) halfInstalled;
1785 - (NSString *) mode;
1787 - (void) setVisible;
1790 - (NSString *) name;
1792 - (NSString *) homepage;
1793 - (NSString *) depiction;
1794 - (Address *) author;
1796 - (NSString *) support;
1798 - (NSArray *) files;
1799 - (NSArray *) relationships;
1800 - (NSArray *) warnings;
1801 - (NSArray *) applications;
1803 - (Source *) source;
1804 - (NSString *) role;
1806 - (BOOL) matches:(NSString *)text;
1808 - (bool) hasSupportingRole;
1809 - (BOOL) hasTag:(NSString *)tag;
1810 - (NSString *) primaryPurpose;
1811 - (NSArray *) purposes;
1812 - (bool) isCommercial;
1814 - (CYString &) cyname;
1816 - (uint32_t) compareBySection:(NSArray *)sections;
1818 - (uint32_t) compareForChanges;
1823 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1824 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1825 - (bool) isInstalledAndVisible:(NSNumber *)number;
1826 - (bool) isVisibleInSection:(NSString *)section;
1827 - (bool) isVisibleInSource:(Source *)source;
1831 uint32_t PackageChangesRadix(Package *self, void *) {
1836 uint32_t timestamp : 30;
1837 uint32_t ignored : 1;
1838 uint32_t upgradable : 1;
1842 bool upgradable([self upgradableAndEssential:YES]);
1843 value.bits.upgradable = upgradable ? 1 : 0;
1846 value.bits.timestamp = 0;
1847 value.bits.ignored = [self ignored] ? 0 : 1;
1848 value.bits.upgradable = 1;
1850 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1851 value.bits.ignored = 0;
1852 value.bits.upgradable = 0;
1855 return _not(uint32_t) - value.key;
1858 _finline static void Stifle(uint8_t &value) {
1861 uint32_t PackagePrefixRadix(Package *self, void *context) {
1862 size_t offset(reinterpret_cast<size_t>(context));
1863 CYString &name([self cyname]);
1865 size_t size(name.size());
1868 char *text(name.data());
1871 if (!isdigit(text[0]))
1875 while (size != digits && isdigit(text[digits]))
1885 if (offset == 0 && zeros != 0) {
1886 memset(data, '0', zeros);
1887 memcpy(data + zeros, text, 4 - zeros);
1889 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1890 if (size <= offset - zeros)
1893 text += offset - zeros;
1894 size -= offset - zeros;
1897 memcpy(data, text, 4);
1899 memcpy(data, text, size);
1900 memset(data + size, 0, 4 - size);
1903 for (size_t i(0); i != 4; ++i)
1904 if (isalpha(data[i]))
1912 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1914 /* XXX: ntohl may be more honest */
1915 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1918 CYString &(*PackageName)(Package *self, SEL sel);
1920 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1921 _profile(PackageNameCompare)
1922 CYString &lhi(PackageName(lhs, @selector(cyname)));
1923 CYString &rhi(PackageName(rhs, @selector(cyname)));
1924 CFStringRef lhn(lhi), rhn(rhi);
1927 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1928 else if (rhn == NULL)
1929 return NSOrderedDescending;
1931 _profile(PackageNameCompare$NumbersLast)
1932 if (!lhi.empty() && !rhi.empty()) {
1933 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1934 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1935 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1936 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1937 return lha ? NSOrderedAscending : NSOrderedDescending;
1941 CFIndex length = CFStringGetLength(lhn);
1943 _profile(PackageNameCompare$Compare)
1944 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1949 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1950 return PackageNameCompare(*lhs, *rhs, context);
1953 struct PackageNameOrdering :
1954 std::binary_function<Package *, Package *, bool>
1956 _finline bool operator ()(Package *lhs, Package *rhs) const {
1957 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1961 @implementation Package
1963 - (NSString *) description {
1964 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1974 if (sponsor$_ != nil)
1975 [sponsor$_ release];
1976 if (author$_ != nil)
1983 if (relationships_ != nil)
1984 [relationships_ release];
1985 if (metadata_ != nil)
1986 [metadata_ release];
1991 + (NSString *) webScriptNameForSelector:(SEL)selector {
1992 if (selector == @selector(hasTag:))
1998 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1999 return [self webScriptNameForSelector:selector] == nil;
2002 + (NSArray *) _attributeKeys {
2003 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];
2006 - (NSArray *) attributeKeys {
2007 return [[self class] _attributeKeys];
2010 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2011 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2021 _profile(Package$parse)
2022 pkgRecords::Parser *parser;
2024 _profile(Package$parse$Lookup)
2025 parser = &[database_ records]->Lookup(file_);
2030 _profile(Package$parse$Find)
2036 {"depiction", &depiction_},
2037 {"homepage", &homepage_},
2038 {"website", &website},
2040 {"support", &support_},
2041 {"sponsor", &sponsor_},
2042 {"author", &author_},
2045 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2046 const char *start, *end;
2048 if (parser->Find(names[i].name_, start, end)) {
2049 CYString &value(*names[i].value_);
2050 _profile(Package$parse$Value)
2051 value.set(pool_, start, end - start);
2057 _profile(Package$parse$Tagline)
2058 const char *start, *end;
2059 if (parser->ShortDesc(start, end)) {
2060 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2063 while (stop != start && stop[-1] == '\r')
2065 tagline_.set(pool_, start, stop - start);
2069 _profile(Package$parse$Retain)
2070 if (homepage_.empty())
2071 homepage_ = website;
2072 if (homepage_ == depiction_)
2078 - (void) setVisible {
2079 visible_ = required_ && [self unfiltered];
2082 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2083 if ((self = [super init]) != nil) {
2084 _profile(Package$initWithVersion)
2085 era_ = [database era];
2090 _profile(Package$initWithVersion$ParentPkg)
2091 iterator_ = version.ParentPkg();
2094 database_ = database;
2096 _profile(Package$initWithVersion$Latest)
2097 const char *latest(StripVersion_(version_.VerStr()));
2098 latest_ = (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(latest), strlen(latest), kCFStringEncodingASCII, NO);
2101 pkgCache::VerIterator current;
2102 _profile(Package$initWithVersion$Versions)
2103 current = iterator_.CurrentVer();
2105 installed_.set(pool_, StripVersion_(current.VerStr()));
2107 if (!version_.end())
2108 file_ = version_.FileList();
2110 pkgCache &cache([database_ cache]);
2111 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2115 _profile(Package$initWithVersion$Name)
2116 id_.set(pool_, iterator_.Name());
2117 name_.set(pool, iterator_.Display());
2120 _profile(Package$initWithVersion$lowercaseString)
2121 char *data(id_.data());
2122 for (size_t i(0), e(id_.size()); i != e; ++i)
2123 // XXX: do not use tolower() as this is not locale-specific? :(
2128 _profile(Package$initWithVersion$Source)
2129 source_ = [database_ getSource:file_.File()];
2138 _profile(Package$initWithVersion$Tags)
2139 pkgCache::TagIterator tag(iterator_.TagList());
2141 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2143 const char *name(tag.Name());
2144 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2145 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2146 role_ = (NSString *) CYStringCreate(name + 6);
2147 if (required_ && strncmp(name, "require::", 9) == 0 && (
2152 } while (!tag.end());
2156 bool changed(false);
2158 _profile(Package$initWithVersion$Metadata)
2159 metadata_ = [Packages_ objectForKey:id_];
2161 if (metadata_ == nil) {
2164 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2165 firstSeen_, @"FirstSeen",
2166 latest_, @"LastVersion",
2171 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2172 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2174 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2175 subscribed_ = [subscribed boolValue];
2177 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2179 if (firstSeen_ == nil) {
2180 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2181 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2185 if (version == nil) {
2186 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2188 } else if (![version isEqualToString:latest_]) {
2189 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2191 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2196 metadata_ = [metadata_ retain];
2199 [Packages_ setObject:metadata_ forKey:id_];
2204 _profile(Package$initWithVersion$Section)
2205 section_.set(pool_, iterator_.Section());
2208 _profile(Package$initWithVersion$hasTag)
2209 obsolete_ = [self hasTag:@"cydia::obsolete"];
2210 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2213 _profile(Package$initWithVersion$setVisible)
2219 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2220 pkgCache::VerIterator version;
2222 _profile(Package$packageWithIterator$GetCandidateVer)
2223 version = [database policy]->GetCandidateVer(iterator);
2229 return [[[Package alloc]
2230 initWithVersion:version
2237 - (pkgCache::PkgIterator) iterator {
2241 - (NSString *) section {
2242 if (section$_ == nil) {
2243 if (section_.empty())
2246 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2247 NSString *name(section_);
2250 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2251 if (NSString *rename = [value objectForKey:@"Rename"]) {
2260 - (NSString *) simpleSection {
2261 if (NSString *section = [self section])
2262 return Simplify(section);
2267 - (NSString *) longSection {
2268 return LocalizeSection([self section]);
2271 - (NSString *) shortSection {
2272 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2275 - (NSString *) uri {
2278 pkgIndexFile *index;
2279 pkgCache::PkgFileIterator file(file_.File());
2280 if (![database_ list].FindIndex(file, index))
2282 return [NSString stringWithUTF8String:iterator_->Path];
2283 //return [NSString stringWithUTF8String:file.Site()];
2284 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2288 - (Address *) maintainer {
2291 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2292 const std::string &maintainer(parser->Maintainer());
2293 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2297 return version_.end() ? 0 : version_->InstalledSize;
2300 - (NSString *) longDescription {
2301 @synchronized (database_) {
2302 if ([database_ era] != era_ || file_.end())
2305 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2306 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2308 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2309 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2310 if ([lines count] < 2)
2313 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2314 for (size_t i(1), e([lines count]); i != e; ++i) {
2315 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2316 [trimmed addObject:trim];
2319 return [trimmed componentsJoinedByString:@"\n"];
2322 - (NSString *) shortDescription {
2327 _profile(Package$index)
2328 CFStringRef name((CFStringRef) [self name]);
2329 if (CFStringGetLength(name) == 0)
2331 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2332 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2334 return toupper(character);
2338 - (NSMutableDictionary *) metadata {
2343 if (subscribed_ && lastSeen_ != nil)
2348 - (BOOL) subscribed {
2353 NSDictionary *metadata([self metadata]);
2354 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2355 return [ignored boolValue];
2360 - (NSString *) latest {
2364 - (NSString *) installed {
2368 - (BOOL) uninstalled {
2369 return installed_.empty();
2373 return !version_.end();
2376 - (BOOL) upgradableAndEssential:(BOOL)essential {
2377 _profile(Package$upgradableAndEssential)
2378 pkgCache::VerIterator current(iterator_.CurrentVer());
2380 return essential && essential_ && visible_;
2382 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2386 - (BOOL) essential {
2391 return [database_ cache][iterator_].InstBroken();
2394 - (BOOL) unfiltered {
2395 _profile(Package$unfiltered$obsolete)
2400 _profile(Package$unfiltered$hasSupportingRole)
2401 if (![self hasSupportingRole])
2407 _profile(Package$unfiltered$section)
2408 section = [self section];
2411 _profile(Package$unfiltered$isSectionVisible)
2412 if (section != nil && !isSectionVisible(section))
2424 unsigned char current(iterator_->CurrentState);
2425 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2428 - (BOOL) halfConfigured {
2429 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2432 - (BOOL) halfInstalled {
2433 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2437 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2438 return state.Mode != pkgDepCache::ModeKeep;
2441 - (NSString *) mode {
2442 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2444 switch (state.Mode) {
2445 case pkgDepCache::ModeDelete:
2446 if ((state.iFlags & pkgDepCache::Purge) != 0)
2450 case pkgDepCache::ModeKeep:
2451 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2452 return @"REINSTALL";
2453 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2457 case pkgDepCache::ModeInstall:
2458 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2459 return @"REINSTALL";
2460 else*/ switch (state.Status) {
2462 return @"DOWNGRADE";
2468 return @"NEW_INSTALL";
2479 - (NSString *) name {
2480 return name_.empty() ? id_ : name_;
2483 - (UIImage *) icon {
2484 NSString *section = [self simpleSection];
2488 if ([static_cast<id>(icon_) hasPrefix:@"file:///"])
2489 // XXX: correct escaping
2490 icon = [UIImage imageAtPath:[static_cast<id>(icon_) substringFromIndex:7]];
2491 if (icon == nil) if (section != nil)
2492 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2493 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2494 if ([dicon hasPrefix:@"file:///"])
2495 // XXX: correct escaping
2496 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2498 icon = [UIImage applicationImageNamed:@"unknown.png"];
2502 - (NSString *) homepage {
2506 - (NSString *) depiction {
2507 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2510 - (Address *) sponsor {
2511 if (sponsor$_ == nil) {
2512 if (sponsor_.empty())
2514 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2518 - (Address *) author {
2519 if (author$_ == nil) {
2520 if (author_.empty())
2522 author$_ = [[Address addressWithString:author_] retain];
2526 - (NSString *) support {
2527 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2530 - (NSArray *) files {
2531 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2532 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2535 fin.open([path UTF8String]);
2540 while (std::getline(fin, line))
2541 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2546 - (NSArray *) relationships {
2547 return relationships_;
2550 - (NSArray *) warnings {
2551 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2552 const char *name(iterator_.Name());
2554 size_t length(strlen(name));
2555 if (length < 2) invalid:
2556 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2557 else for (size_t i(0); i != length; ++i)
2559 /* XXX: technically this is not allowed */
2560 (name[i] < 'A' || name[i] > 'Z') &&
2561 (name[i] < 'a' || name[i] > 'z') &&
2562 (name[i] < '0' || name[i] > '9') &&
2563 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2566 if (strcmp(name, "cydia") != 0) {
2569 bool _private = false;
2572 bool repository = [[self section] isEqualToString:@"Repositories"];
2574 if (NSArray *files = [self files])
2575 for (NSString *file in files)
2576 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2578 else if (!user && [file isEqualToString:@"/User"])
2580 else if (!_private && [file isEqualToString:@"/private"])
2582 else if (!stash && [file isEqualToString:@"/var/stash"])
2585 /* XXX: this is not sensitive enough. only some folders are valid. */
2586 if (cydia && !repository)
2587 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2589 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2591 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2593 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2596 return [warnings count] == 0 ? nil : warnings;
2599 - (NSArray *) applications {
2600 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2602 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2604 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2605 if (NSArray *files = [self files])
2606 for (NSString *file in files)
2607 if (application_r(file)) {
2608 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2609 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2610 if ([id isEqualToString:me])
2613 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2615 display = application_r[1];
2617 NSString *bundle([file stringByDeletingLastPathComponent]);
2618 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2619 if (icon == nil || [icon length] == 0)
2621 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2623 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2624 [applications addObject:application];
2626 [application addObject:id];
2627 [application addObject:display];
2628 [application addObject:url];
2631 return [applications count] == 0 ? nil : applications;
2634 - (Source *) source {
2636 @synchronized (database_) {
2637 if ([database_ era] != era_ || file_.end())
2640 source_ = [database_ getSource:file_.File()];
2652 - (NSString *) role {
2656 - (BOOL) matches:(NSString *)text {
2662 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2663 if (range.location != NSNotFound)
2666 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2667 if (range.location != NSNotFound)
2670 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2671 if (range.location != NSNotFound)
2677 - (bool) hasSupportingRole {
2680 if ([role_ isEqualToString:@"enduser"])
2682 if ([Role_ isEqualToString:@"User"])
2684 if ([role_ isEqualToString:@"hacker"])
2686 if ([Role_ isEqualToString:@"Hacker"])
2688 if ([role_ isEqualToString:@"developer"])
2690 if ([Role_ isEqualToString:@"Developer"])
2695 - (BOOL) hasTag:(NSString *)tag {
2696 return tags_ == nil ? NO : [tags_ containsObject:tag];
2699 - (NSString *) primaryPurpose {
2700 for (NSString *tag in tags_)
2701 if ([tag hasPrefix:@"purpose::"])
2702 return [tag substringFromIndex:9];
2706 - (NSArray *) purposes {
2707 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2708 for (NSString *tag in tags_)
2709 if ([tag hasPrefix:@"purpose::"])
2710 [purposes addObject:[tag substringFromIndex:9]];
2711 return [purposes count] == 0 ? nil : purposes;
2714 - (bool) isCommercial {
2715 return [self hasTag:@"cydia::commercial"];
2718 - (CYString &) cyname {
2719 return name_.empty() ? id_ : name_;
2722 - (uint32_t) compareBySection:(NSArray *)sections {
2723 NSString *section([self section]);
2724 for (size_t i(0), e([sections count]); i != e; ++i) {
2725 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2729 return _not(uint32_t);
2732 - (uint32_t) compareForChanges {
2737 uint32_t timestamp : 30;
2738 uint32_t ignored : 1;
2739 uint32_t upgradable : 1;
2743 bool upgradable([self upgradableAndEssential:YES]);
2744 value.bits.upgradable = upgradable ? 1 : 0;
2747 value.bits.timestamp = 0;
2748 value.bits.ignored = [self ignored] ? 0 : 1;
2749 value.bits.upgradable = 1;
2751 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2752 value.bits.ignored = 0;
2753 value.bits.upgradable = 0;
2756 return _not(uint32_t) - value.key;
2760 pkgProblemResolver *resolver = [database_ resolver];
2761 resolver->Clear(iterator_);
2762 resolver->Protect(iterator_);
2766 pkgProblemResolver *resolver = [database_ resolver];
2767 resolver->Clear(iterator_);
2768 resolver->Protect(iterator_);
2769 pkgCacheFile &cache([database_ cache]);
2770 cache->MarkInstall(iterator_, false);
2771 pkgDepCache::StateCache &state((*cache)[iterator_]);
2772 if (!state.Install())
2773 cache->SetReInstall(iterator_, true);
2777 pkgProblemResolver *resolver = [database_ resolver];
2778 resolver->Clear(iterator_);
2779 resolver->Protect(iterator_);
2780 resolver->Remove(iterator_);
2781 [database_ cache]->MarkDelete(iterator_, true);
2784 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2785 _profile(Package$isUnfilteredAndSearchedForBy)
2788 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2789 value &= [self unfiltered];
2792 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2793 value &= [self matches:search];
2800 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2801 if ([search length] == 0)
2804 _profile(Package$isUnfilteredAndSelectedForBy)
2807 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2808 value &= [self unfiltered];
2811 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2812 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2819 - (bool) isInstalledAndVisible:(NSNumber *)number {
2820 return ((![number boolValue] && ![role_ isEqualToString:@"cydia"]) || [self visible]) && ![self uninstalled];
2823 - (bool) isVisibleInSection:(NSString *)name {
2824 NSString *section = [self section];
2829 section == nil && [name length] == 0 ||
2830 [name isEqualToString:section]
2834 - (bool) isVisibleInSource:(Source *)source {
2835 return [self source] == source && [self visible];
2840 /* Section Class {{{ */
2841 @interface Section : NSObject {
2846 NSString *localized_;
2849 - (NSComparisonResult) compareByLocalized:(Section *)section;
2850 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2851 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2852 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2853 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2854 - (NSString *) name;
2861 - (void) addToCount;
2863 - (void) setCount:(size_t)count;
2864 - (NSString *) localized;
2868 @implementation Section
2872 if (localized_ != nil)
2873 [localized_ release];
2877 - (NSComparisonResult) compareByLocalized:(Section *)section {
2878 NSString *lhs(localized_);
2879 NSString *rhs([section localized]);
2881 /*if ([lhs length] != 0 && [rhs length] != 0) {
2882 unichar lhc = [lhs characterAtIndex:0];
2883 unichar rhc = [rhs characterAtIndex:0];
2885 if (isalpha(lhc) && !isalpha(rhc))
2886 return NSOrderedAscending;
2887 else if (!isalpha(lhc) && isalpha(rhc))
2888 return NSOrderedDescending;
2891 return [lhs compare:rhs options:LaxCompareOptions_];
2894 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2895 if ((self = [self initWithName:name localize:NO]) != nil) {
2896 if (localized != nil)
2897 localized_ = [localized retain];
2901 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2902 return [self initWithName:name row:0 localize:localize];
2905 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2906 if ((self = [super init]) != nil) {
2907 name_ = [name retain];
2911 localized_ = [LocalizeSection(name_) retain];
2915 /* XXX: localize the index thingees */
2916 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2917 if ((self = [super init]) != nil) {
2918 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2924 - (NSString *) name {
2944 - (void) addToCount {
2948 - (void) setCount:(size_t)count {
2952 - (NSString *) localized {
2959 static NSString *Colon_;
2960 static NSString *Error_;
2961 static NSString *Warning_;
2963 /* Database Implementation {{{ */
2964 @implementation Database
2966 + (Database *) sharedInstance {
2967 static Database *instance;
2968 if (instance == nil)
2969 instance = [[Database alloc] init];
2978 // XXX: actually implement this thing
2980 NSRecycleZone(zone_);
2981 // XXX: malloc_destroy_zone(zone_);
2982 apr_pool_destroy(pool_);
2986 - (void) _readCydia:(NSNumber *)fd { _pooled
2987 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2988 std::istream is(&ib);
2991 static Pcre finish_r("^finish:([^:]*)$");
2993 while (std::getline(is, line)) {
2994 const char *data(line.c_str());
2995 size_t size = line.size();
2996 lprintf("C:%s\n", data);
2998 if (finish_r(data, size)) {
2999 NSString *finish = finish_r[1];
3000 int index = [Finishes_ indexOfObject:finish];
3001 if (index != INT_MAX && index > Finish_)
3009 - (void) _readStatus:(NSNumber *)fd { _pooled
3010 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3011 std::istream is(&ib);
3014 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3015 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3017 while (std::getline(is, line)) {
3018 const char *data(line.c_str());
3019 size_t size(line.size());
3020 lprintf("S:%s\n", data);
3022 if (conffile_r(data, size)) {
3023 [delegate_ setConfigurationData:conffile_r[1]];
3024 } else if (strncmp(data, "status: ", 8) == 0) {
3025 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3026 [delegate_ setProgressTitle:string];
3027 } else if (pmstatus_r(data, size)) {
3028 std::string type([pmstatus_r[1] UTF8String]);
3029 NSString *id = pmstatus_r[2];
3031 float percent([pmstatus_r[3] floatValue]);
3032 [delegate_ setProgressPercent:(percent / 100)];
3034 NSString *string = pmstatus_r[4];
3036 if (type == "pmerror")
3037 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3038 withObject:[NSArray arrayWithObjects:string, id, nil]
3041 else if (type == "pmstatus") {
3042 [delegate_ setProgressTitle:string];
3043 } else if (type == "pmconffile")
3044 [delegate_ setConfigurationData:string];
3046 lprintf("E:unknown pmstatus\n");
3048 lprintf("E:unknown status\n");
3054 - (void) _readOutput:(NSNumber *)fd { _pooled
3055 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3056 std::istream is(&ib);
3059 while (std::getline(is, line)) {
3060 lprintf("O:%s\n", line.c_str());
3061 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3071 - (Package *) packageWithName:(NSString *)name {
3072 @synchronized (self) {
3073 if (static_cast<pkgDepCache *>(cache_) == NULL)
3075 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3076 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3080 if ((self = [super init]) != nil) {
3087 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3088 apr_pool_create(&pool_, NULL);
3090 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
3094 _assert(pipe(fds) != -1);
3097 _config->Set("APT::Keep-Fds::", cydiafd_);
3098 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3101 detachNewThreadSelector:@selector(_readCydia:)
3103 withObject:[NSNumber numberWithInt:fds[0]]
3106 _assert(pipe(fds) != -1);
3110 detachNewThreadSelector:@selector(_readStatus:)
3112 withObject:[NSNumber numberWithInt:fds[0]]
3115 _assert(pipe(fds) != -1);
3116 _assert(dup2(fds[0], 0) != -1);
3117 _assert(close(fds[0]) != -1);
3119 input_ = fdopen(fds[1], "a");
3121 _assert(pipe(fds) != -1);
3122 _assert(dup2(fds[1], 1) != -1);
3123 _assert(close(fds[1]) != -1);
3126 detachNewThreadSelector:@selector(_readOutput:)
3128 withObject:[NSNumber numberWithInt:fds[0]]
3133 - (pkgCacheFile &) cache {
3137 - (pkgDepCache::Policy *) policy {
3141 - (pkgRecords *) records {
3145 - (pkgProblemResolver *) resolver {
3149 - (pkgAcquire &) fetcher {
3153 - (pkgSourceList &) list {
3157 - (NSArray *) packages {
3158 return (NSArray *) packages_;
3161 - (NSArray *) sources {
3162 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3163 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3164 [sources addObject:i->second];
3168 - (NSArray *) issues {
3169 if (cache_->BrokenCount() == 0)
3172 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3174 for (Package *package in [self packages]) {
3175 if (![package broken])
3177 pkgCache::PkgIterator pkg([package iterator]);
3179 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3180 [entry addObject:[package name]];
3181 [issues addObject:entry];
3183 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3187 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3188 pkgCache::DepIterator start;
3189 pkgCache::DepIterator end;
3190 dep.GlobOr(start, end); // ++dep
3192 if (!cache_->IsImportantDep(end))
3194 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3197 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3198 [entry addObject:failure];
3199 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3201 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3202 if (Package *package = [self packageWithName:name])
3203 name = [package name];
3204 [failure addObject:name];
3206 pkgCache::PkgIterator target(start.TargetPkg());
3207 if (target->ProvidesList != 0)
3208 [failure addObject:@"?"];
3210 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3212 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3213 else if (!cache_[target].CandidateVerIter(cache_).end())
3214 [failure addObject:@"-"];
3215 else if (target->ProvidesList == 0)
3216 [failure addObject:@"!"];
3218 [failure addObject:@"%"];
3222 if (start.TargetVer() != 0)
3223 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3234 - (bool) popErrorWithTitle:(NSString *)title {
3236 std::string message;
3238 while (!_error->empty()) {
3240 bool warning(!_error->PopMessage(error));
3244 size_t size(error.size());
3245 if (size == 0 || error[size - 1] != '\n')
3247 error.resize(size - 1);
3249 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3251 if (!message.empty())
3256 if (fatal && !message.empty())
3257 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3262 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3263 return [self popErrorWithTitle:title] || !success;
3266 - (void) reloadData { CYPoolStart() {
3267 @synchronized (self) {
3270 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3271 CFArrayRemoveAllValues(packages_);
3298 apr_pool_clear(pool_);
3299 NSRecycleZone(zone_);
3301 int chk(creat("/tmp/cydia.chk", 0644));
3305 NSString *title(UCLocalize("DATABASE"));
3308 if (!cache_.Open(progress_, true)) { pop:
3310 bool warning(!_error->PopMessage(error));
3311 lprintf("cache_.Open():[%s]\n", error.c_str());
3313 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3314 [delegate_ repairWithSelector:@selector(configure)];
3315 else if (error == "The package lists or status file could not be parsed or opened.")
3316 [delegate_ repairWithSelector:@selector(update)];
3317 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3318 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3319 // else if (error == "The list of sources could not be read.")
3321 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3330 unlink("/tmp/cydia.chk");
3332 now_ = [[NSDate date] retain];
3334 policy_ = new pkgDepCache::Policy();
3335 records_ = new pkgRecords(cache_);
3336 resolver_ = new pkgProblemResolver(cache_);
3337 fetcher_ = new pkgAcquire(&status_);
3340 list_ = new pkgSourceList();
3341 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3344 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3345 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3349 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3352 if (cache_->BrokenCount() != 0) {
3353 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3356 if (cache_->BrokenCount() != 0) {
3357 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3361 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3365 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3366 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3367 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3368 // XXX: this could be more intelligent
3369 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3370 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3372 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3377 /*std::vector<Package *> packages;
3378 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3379 [packages_ release];
3384 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3385 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3386 //packages.push_back(package);
3387 CFArrayAppendValue(packages_, [package retain]);
3391 /*if (packages.empty())
3392 packages_ = [[NSArray alloc] init];
3394 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3397 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3398 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3399 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3407 /*if (!packages.empty())
3408 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3409 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3411 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3413 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3415 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3419 } } CYPoolEnd() _trace(); }
3421 - (void) configure {
3422 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3423 system([dpkg UTF8String]);
3427 // XXX: I don't remember this condition
3432 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3434 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3436 if ([self popErrorWithTitle:title])
3440 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3443 public pkgArchiveCleaner
3446 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3451 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3458 fetcher_->Shutdown();
3460 pkgRecords records(cache_);
3462 lock_ = new FileFd();
3463 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3465 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3467 if ([self popErrorWithTitle:title])
3471 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3474 manager_ = (_system->CreatePM(cache_));
3475 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3482 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3484 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3486 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3488 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3489 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3492 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3497 bool failed = false;
3498 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3499 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3501 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3504 std::string uri = (*item)->DescURI();
3505 std::string error = (*item)->ErrorText;
3507 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3510 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3511 withObject:[NSArray arrayWithObjects:
3512 [NSString stringWithUTF8String:error.c_str()],
3524 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3526 if (_error->PendingError()) {
3531 if (result == pkgPackageManager::Failed) {
3536 if (result != pkgPackageManager::Completed) {
3541 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3543 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3545 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3546 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3549 if (![before isEqualToArray:after])
3554 NSString *title(UCLocalize("UPGRADE"));
3555 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3561 [self updateWithStatus:status_];
3564 - (void) setVisible {
3565 for (Package *package in [self packages])
3566 [package setVisible];
3569 - (void) updateWithStatus:(Status &)status {
3570 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3571 NSString *title(UCLocalize("REFRESHING_DATA"));
3574 if (!list.ReadMainList())
3575 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3578 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3579 if ([self popErrorWithTitle:title])
3582 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3583 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3584 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3586 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3590 - (void) setDelegate:(id)delegate {
3591 delegate_ = delegate;
3592 status_.setDelegate(delegate);
3593 progress_.setDelegate(delegate);
3596 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3597 SourceMap::const_iterator i(sources_.find(file->ID));
3598 return i == sources_.end() ? nil : i->second;
3604 /* Confirmation Controller {{{ */
3605 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3606 if (!iterator.end())
3607 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3608 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3610 pkgCache::PkgIterator package(dep.TargetPkg());
3613 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3621 /* Web Scripting {{{ */
3622 @interface CydiaObject : NSObject {
3624 _transient id delegate_;
3627 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3630 @implementation CydiaObject
3633 [indirect_ release];
3637 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3638 if ((self = [super init]) != nil) {
3639 indirect_ = [indirect retain];
3643 - (void) setDelegate:(id)delegate {
3644 delegate_ = delegate;
3647 + (NSArray *) _attributeKeys {
3648 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3651 - (NSArray *) attributeKeys {
3652 return [[self class] _attributeKeys];
3655 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3656 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3659 - (NSString *) device {
3660 return [[UIDevice currentDevice] uniqueIdentifier];
3663 #if 0 // XXX: implement!
3664 - (NSString *) mac {
3665 if (![indirect_ promptForSensitive:@"Mac Address"])
3669 - (NSString *) serial {
3670 if (![indirect_ promptForSensitive:@"Serial #"])
3674 - (NSString *) firewire {
3675 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3679 - (NSString *) imei {
3680 if (![indirect_ promptForSensitive:@"IMEI"])
3685 + (NSString *) webScriptNameForSelector:(SEL)selector {
3686 if (selector == @selector(close))
3688 else if (selector == @selector(getInstalledPackages))
3689 return @"getInstalledPackages";
3690 else if (selector == @selector(getPackageById:))
3691 return @"getPackageById";
3692 else if (selector == @selector(installPackages:))
3693 return @"installPackages";
3694 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3695 return @"setButtonImage";
3696 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3697 return @"setButtonTitle";
3698 else if (selector == @selector(setPopupHook:))
3699 return @"setPopupHook";
3700 else if (selector == @selector(setSpecial:))
3701 return @"setSpecial";
3702 else if (selector == @selector(setToken:))
3704 else if (selector == @selector(setViewportWidth:))
3705 return @"setViewportWidth";
3706 else if (selector == @selector(supports:))
3708 else if (selector == @selector(stringWithFormat:arguments:))
3710 else if (selector == @selector(localizedStringForKey:value:table:))
3712 else if (selector == @selector(du:))
3714 else if (selector == @selector(statfs:))
3720 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3721 return [self webScriptNameForSelector:selector] == nil;
3724 - (BOOL) supports:(NSString *)feature {
3725 return [feature isEqualToString:@"window.open"];
3728 - (NSArray *) getInstalledPackages {
3729 NSArray *packages([[Database sharedInstance] packages]);
3730 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3731 for (Package *package in packages)
3732 if ([package installed] != nil)
3733 [installed addObject:package];
3737 - (Package *) getPackageById:(NSString *)id {
3738 Package *package([[Database sharedInstance] packageWithName:id]);
3743 - (NSArray *) statfs:(NSString *)path {
3746 if (path == nil || statfs([path UTF8String], &stat) == -1)
3749 return [NSArray arrayWithObjects:
3750 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3751 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3752 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3756 - (NSNumber *) du:(NSString *)path {
3757 NSNumber *value(nil);
3760 _assert(pipe(fds) != -1);
3762 pid_t pid(ExecFork());
3764 _assert(dup2(fds[1], 1) != -1);
3765 _assert(close(fds[0]) != -1);
3766 _assert(close(fds[1]) != -1);
3767 /* XXX: this should probably not use du */
3768 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3773 _assert(close(fds[1]) != -1);
3775 if (FILE *du = fdopen(fds[0], "r")) {
3777 while (fgets(line, sizeof(line), du) != NULL) {
3778 size_t length(strlen(line));
3779 while (length != 0 && line[length - 1] == '\n')
3780 line[--length] = '\0';
3781 if (char *tab = strchr(line, '\t')) {
3783 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3788 } else _assert(close(fds[0]));
3792 if (waitpid(pid, &status, 0) == -1)
3795 else _assert(false);
3804 - (void) installPackages:(NSArray *)packages {
3805 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3808 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3809 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3812 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3813 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3816 - (void) setSpecial:(id)function {
3817 [indirect_ setSpecial:function];
3820 - (void) setToken:(NSString *)token {
3823 Token_ = [token retain];
3825 [Metadata_ setObject:Token_ forKey:@"Token"];
3829 - (void) setPopupHook:(id)function {
3830 [indirect_ setPopupHook:function];
3833 - (void) setViewportWidth:(float)width {
3834 [indirect_ setViewportWidth:width];
3837 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3838 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3839 unsigned count([arguments count]);
3841 for (unsigned i(0); i != count; ++i)
3842 values[i] = [arguments objectAtIndex:i];
3843 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3846 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3847 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3849 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3851 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3857 /* Cydia Browser Controller {{{ */
3858 @interface CYBrowserController : BrowserController {
3859 CydiaObject *cydia_;
3864 @implementation CYBrowserController
3871 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3874 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3875 [super webView:view didClearWindowObject:window forFrame:frame];
3877 WebDataSource *source([frame dataSource]);
3878 NSURLResponse *response([source response]);
3879 NSURL *url([response URL]);
3880 NSString *scheme([url scheme]);
3882 NSHTTPURLResponse *http;
3883 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3884 http = (NSHTTPURLResponse *) response;
3888 NSDictionary *headers([http allHeaderFields]);
3889 NSString *host([url host]);
3890 [self setHeaders:headers forHost:host];
3893 [host isEqualToString:@"cydia.saurik.com"] ||
3894 [host hasSuffix:@".cydia.saurik.com"] ||
3895 [scheme isEqualToString:@"file"]
3897 [window setValue:cydia_ forKey:@"cydia"];
3900 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3901 if (System_ != NULL)
3902 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3903 if (Machine_ != NULL)
3904 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3906 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3908 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3911 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3912 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3913 [self _setMoreHeaders:copy];
3917 - (void) setDelegate:(id)delegate {
3918 [super setDelegate:delegate];
3919 [cydia_ setDelegate:delegate];
3923 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3924 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3926 WebView *webview([[webview_ _documentView] webView]);
3928 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3930 NSString *application = package == nil ? @"Cydia" : [NSString
3931 stringWithFormat:@"Cydia/%@",
3936 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3938 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3939 if (Product_ != nil)
3940 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3942 [webview setApplicationNameForUserAgent:application];
3949 /* Confirmation {{{ */
3950 @protocol ConfirmationControllerDelegate
3951 - (void) cancelAndClear:(bool)clear;
3952 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3956 @interface ConfirmationController : CYBrowserController {
3957 _transient Database *database_;
3958 UIAlertView *essential_;
3965 - (id) initWithDatabase:(Database *)database;
3969 @implementation ConfirmationController
3976 if (essential_ != nil)
3977 [essential_ release];
3981 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3982 NSString *context([alert context]);
3984 if ([context isEqualToString:@"remove"]) {
3985 if (button == [alert cancelButtonIndex]) {
3986 [self dismissModalViewControllerAnimated:YES];
3987 } else if (button == [alert firstOtherButtonIndex]) {
3990 [delegate_ confirmWithNavigationController:[self navigationController]];
3993 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3994 } else if ([context isEqualToString:@"unable"]) {
3995 [self dismissModalViewControllerAnimated:YES];
3996 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3998 [super alertView:alert clickedButtonAtIndex:button];
4002 - (void) _doContinue {
4003 [self dismissModalViewControllerAnimated:YES];
4004 [delegate_ cancelAndClear:NO];
4007 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4008 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4012 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4013 [super webView:view didClearWindowObject:window forFrame:frame];
4014 [window setValue:changes_ forKey:@"changes"];
4015 [window setValue:issues_ forKey:@"issues"];
4016 [window setValue:sizes_ forKey:@"sizes"];
4017 [window setValue:self forKey:@"queue"];
4020 - (id) initWithDatabase:(Database *)database {
4021 if ((self = [super init]) != nil) {
4022 database_ = database;
4024 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4026 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4027 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4028 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4029 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4030 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4034 pkgDepCache::Policy *policy([database_ policy]);
4036 pkgCacheFile &cache([database_ cache]);
4037 NSArray *packages = [database_ packages];
4038 for (Package *package in packages) {
4039 pkgCache::PkgIterator iterator = [package iterator];
4040 pkgDepCache::StateCache &state(cache[iterator]);
4042 NSString *name([package name]);
4044 if (state.NewInstall())
4045 [installing addObject:name];
4046 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4047 [reinstalling addObject:name];
4048 else if (state.Upgrade())
4049 [upgrading addObject:name];
4050 else if (state.Downgrade())
4051 [downgrading addObject:name];
4052 else if (state.Delete()) {
4053 if ([package essential])
4055 [removing addObject:name];
4058 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4059 substrate_ |= DepSubstrate(iterator.CurrentVer());
4064 else if (Advanced_) {
4065 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4067 essential_ = [[UIAlertView alloc]
4068 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4069 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4071 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4072 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4075 [essential_ setContext:@"remove"];
4077 essential_ = [[UIAlertView alloc]
4078 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4079 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4081 cancelButtonTitle:UCLocalize("OKAY")
4082 otherButtonTitles:nil
4085 [essential_ setContext:@"unable"];
4088 changes_ = [[NSArray alloc] initWithObjects:
4096 issues_ = [database_ issues];
4098 issues_ = [issues_ retain];
4100 sizes_ = [[NSArray alloc] initWithObjects:
4101 SizeString([database_ fetcher].FetchNeeded()),
4102 SizeString([database_ fetcher].PartialPresent()),
4105 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4107 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4108 initWithTitle:UCLocalize("CANCEL")
4109 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4110 style:UIBarButtonItemStylePlain
4112 action:@selector(cancelButtonClicked)
4117 - (void) applyRightButton {
4118 #if !AlwaysReload && !IgnoreInstall
4119 if (issues_ == nil && ![self isLoading])
4120 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4121 initWithTitle:UCLocalize("CONFIRM")
4122 style:UIBarButtonItemStylePlain
4124 action:@selector(confirmButtonClicked)
4127 [super applyRightButton];
4129 [[self navigationItem] setRightBarButtonItem:nil];
4133 - (void) cancelButtonClicked {
4134 [self dismissModalViewControllerAnimated:YES];
4135 [delegate_ cancelAndClear:YES];
4139 - (void) confirmButtonClicked {
4143 if (essential_ != nil)
4148 [delegate_ confirmWithNavigationController:[self navigationController]];
4156 /* Progress Data {{{ */
4157 @interface ProgressData : NSObject {
4159 // XXX: should these really both be _transient?
4160 _transient id target_;
4161 _transient id object_;
4164 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4171 @implementation ProgressData
4173 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4174 if ((self = [super init]) != nil) {
4175 selector_ = selector;
4195 /* Progress Controller {{{ */
4196 @interface ProgressController : CYViewController <
4197 ConfigurationDelegate,
4200 _transient Database *database_;
4201 UIProgressBar *progress_;
4202 UITextView *output_;
4203 UITextLabel *status_;
4204 UIPushButton *close_;
4206 SHA1SumValue springlist_;
4207 SHA1SumValue notifyconf_;
4211 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4213 - (void) _retachThread;
4214 - (void) _detachNewThreadData:(ProgressData *)data;
4215 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4221 @protocol ProgressControllerDelegate
4222 - (void) progressControllerIsComplete:(ProgressController *)sender;
4225 @implementation ProgressController
4228 [database_ setDelegate:nil];
4229 [progress_ release];
4238 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4239 if ((self = [super init]) != nil) {
4240 database_ = database;
4241 [database_ setDelegate:self];
4242 delegate_ = delegate;
4244 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4246 progress_ = [[UIProgressBar alloc] init];
4247 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4248 [progress_ setStyle:0];
4250 status_ = [[UITextLabel alloc] init];
4251 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4252 [status_ setColor:[UIColor whiteColor]];
4253 [status_ setBackgroundColor:[UIColor clearColor]];
4254 [status_ setCentersHorizontally:YES];
4255 //[status_ setFont:font];
4257 output_ = [[UITextView alloc] init];
4259 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4260 //[output_ setTextFont:@"Courier New"];
4261 [output_ setFont:[[output_ font] fontWithSize:12]];
4262 [output_ setTextColor:[UIColor whiteColor]];
4263 [output_ setBackgroundColor:[UIColor clearColor]];
4264 [output_ setMarginTop:0];
4265 [output_ setAllowsRubberBanding:YES];
4266 [output_ setEditable:NO];
4267 [[self view] addSubview:output_];
4269 close_ = [[UIPushButton alloc] init];
4270 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4271 [close_ setAutosizesToFit:NO];
4272 [close_ setDrawsShadow:YES];
4273 [close_ setStretchBackground:YES];
4274 [close_ setEnabled:YES];
4275 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4276 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4277 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4278 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4282 - (void) positionViews {
4283 CGRect bounds = [[self view] bounds];
4284 CGSize prgsize = [UIProgressBar defaultSize];
4287 (bounds.size.width - prgsize.width) / 2,
4288 bounds.size.height - prgsize.height - 20
4291 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4293 [progress_ setFrame:prgrect];
4294 [status_ setFrame:CGRectMake(
4296 bounds.size.height - prgsize.height - 50,
4297 bounds.size.width - 20,
4300 [output_ setFrame:CGRectMake(
4303 bounds.size.width - 20,
4304 bounds.size.height - 62
4306 [close_ setFrame:CGRectMake(
4307 (bounds.size.width - closewidth) / 2,
4308 bounds.size.height - prgsize.height - 50,
4314 - (void) viewWillAppear:(BOOL)animated {
4315 [super viewDidAppear:animated];
4316 [[self navigationItem] setHidesBackButton:YES];
4317 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4319 [self positionViews];
4322 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4323 [self positionViews];
4326 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4327 NSString *context([alert context]);
4329 if ([context isEqualToString:@"conffile"]) {
4330 FILE *input = [database_ input];
4331 if (button == [alert cancelButtonIndex])
4332 fprintf(input, "N\n");
4333 else if (button == [alert firstOtherButtonIndex])
4334 fprintf(input, "Y\n");
4339 - (void) closeButtonPushed {
4342 UpdateExternalStatus(0);
4346 [self dismissModalViewControllerAnimated:YES];
4350 [delegate_ terminateWithSuccess];
4351 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4352 [delegate_ suspendWithAnimation:YES];
4354 [delegate_ suspend];*/
4358 system("launchctl stop com.apple.SpringBoard");
4362 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4371 - (void) _retachThread {
4372 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4374 [[self view] addSubview:close_];
4375 [progress_ removeFromSuperview];
4376 [status_ removeFromSuperview];
4378 [database_ popErrorWithTitle:title_];
4379 [delegate_ progressControllerIsComplete:self];
4383 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4386 MMap mmap(file, MMap::ReadOnly);
4388 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4389 if (!(notifyconf_ == sha1.Result()))
4396 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4399 MMap mmap(file, MMap::ReadOnly);
4401 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4402 if (!(springlist_ == sha1.Result()))
4408 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4409 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4410 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4411 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4412 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4415 system("su -c /usr/bin/uicache mobile");
4417 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4419 [delegate_ setStatusBarShowsProgress:NO];
4422 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4423 [[data target] performSelector:[data selector] withObject:[data object]];
4424 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4427 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4428 UpdateExternalStatus(1);
4435 title_ = [title retain];
4437 [[self navigationItem] setTitle:title_];
4439 [status_ setText:nil];
4440 [output_ setText:@""];
4441 [progress_ setProgress:0];
4443 [close_ removeFromSuperview];
4444 [[self view] addSubview:progress_];
4445 [[self view] addSubview:status_];
4447 [delegate_ setStatusBarShowsProgress:YES];
4452 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4455 MMap mmap(file, MMap::ReadOnly);
4457 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4458 notifyconf_ = sha1.Result();
4464 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4467 MMap mmap(file, MMap::ReadOnly);
4469 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4470 springlist_ = sha1.Result();
4475 detachNewThreadSelector:@selector(_detachNewThreadData:)
4477 withObject:[[[ProgressData alloc]
4478 initWithSelector:selector
4485 - (void) repairWithSelector:(SEL)selector {
4487 detachNewThreadSelector:selector
4490 title:UCLocalize("REPAIRING")
4494 - (void) setConfigurationData:(NSString *)data {
4496 performSelectorOnMainThread:@selector(_setConfigurationData:)
4502 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4503 CYActionSheet *sheet([[[CYActionSheet alloc]
4505 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4506 defaultButtonIndex:0
4509 [sheet setMessage:error];
4510 [sheet yieldToPopupAlertAnimated:YES];
4514 - (void) setProgressTitle:(NSString *)title {
4516 performSelectorOnMainThread:@selector(_setProgressTitle:)
4522 - (void) setProgressPercent:(float)percent {
4524 performSelectorOnMainThread:@selector(_setProgressPercent:)
4525 withObject:[NSNumber numberWithFloat:percent]
4530 - (void) startProgress {
4533 - (void) addProgressOutput:(NSString *)output {
4535 performSelectorOnMainThread:@selector(_addProgressOutput:)
4541 - (bool) isCancelling:(size_t)received {
4545 - (void) _setConfigurationData:(NSString *)data {
4546 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4548 if (!conffile_r(data)) {
4549 lprintf("E:invalid conffile\n");
4553 NSString *ofile = conffile_r[1];
4554 //NSString *nfile = conffile_r[2];
4556 UIAlertView *alert = [[[UIAlertView alloc]
4557 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4558 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4560 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4561 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4562 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4566 [alert setContext:@"conffile"];
4570 - (void) _setProgressTitle:(NSString *)title {
4571 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4572 for (size_t i(0), e([words count]); i != e; ++i) {
4573 NSString *word([words objectAtIndex:i]);
4574 if (Package *package = [database_ packageWithName:word])
4575 [words replaceObjectAtIndex:i withObject:[package name]];
4578 [status_ setText:[words componentsJoinedByString:@" "]];
4581 - (void) _setProgressPercent:(NSNumber *)percent {
4582 [progress_ setProgress:[percent floatValue]];
4585 - (void) _addProgressOutput:(NSString *)output {
4586 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4587 CGSize size = [output_ contentSize];
4588 CGRect rect = {{0, size.height}, {size.width, 0}};
4589 [output_ scrollRectToVisible:rect animated:YES];
4592 - (BOOL) isRunning {
4599 /* Cell Content View {{{ */
4600 @protocol ContentDelegate
4601 - (void) drawContentRect:(CGRect)rect;
4604 @interface ContentView : UIView {
4605 _transient id<ContentDelegate> delegate_;
4610 @implementation ContentView
4611 - (id) initWithFrame:(CGRect)frame {
4612 if ((self = [super initWithFrame:frame]) != nil) {
4613 /* Fix landscape stretching. */
4614 [self setNeedsDisplayOnBoundsChange:YES];
4618 - (void) setDelegate:(id<ContentDelegate>)delegate {
4619 delegate_ = delegate;
4622 - (void) drawRect:(CGRect)rect {
4623 [super drawRect:rect];
4624 [delegate_ drawContentRect:rect];
4628 /* Package Cell {{{ */
4629 @interface PackageCell : UITableViewCell <
4634 NSString *description_;
4640 ContentView *content_;
4646 - (PackageCell *) init;
4647 - (void) setPackage:(Package *)package;
4649 + (int) heightForPackage:(Package *)package;
4650 - (void) drawContentRect:(CGRect)rect;
4654 @implementation PackageCell
4656 - (void) clearPackage {
4667 if (description_ != nil) {
4668 [description_ release];
4672 if (source_ != nil) {
4677 if (badge_ != nil) {
4682 if (placard_ != nil) {
4692 [self clearPackage];
4699 return faded_ ? [self selectionPercent] : fade_;
4702 - (PackageCell *) init {
4703 CGRect frame(CGRectMake(0, 0, 320, 74));
4704 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4705 UIView *content([self contentView]);
4706 CGRect bounds([content bounds]);
4708 content_ = [[ContentView alloc] initWithFrame:bounds];
4709 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4710 [content addSubview:content_];
4712 [content_ setDelegate:self];
4713 [content_ setOpaque:YES];
4714 if ([self respondsToSelector:@selector(selectionPercent)])
4719 - (void) _setBackgroundColor {
4721 if (NSString *mode = [package_ mode]) {
4722 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4723 color = remove ? RemovingColor_ : InstallingColor_;
4725 color = [UIColor whiteColor];
4727 [content_ setBackgroundColor:color];
4728 [self setNeedsDisplay];
4731 - (void) setPackage:(Package *)package {
4732 [self clearPackage];
4735 Source *source = [package source];
4737 icon_ = [[package icon] retain];
4738 name_ = [[package name] retain];
4741 description_ = [package longDescription];
4742 if (description_ == nil)
4743 description_ = [package shortDescription];
4744 if (description_ != nil)
4745 description_ = [description_ retain];
4747 commercial_ = [package isCommercial];
4749 package_ = [package retain];
4751 NSString *label = nil;
4752 bool trusted = false;
4754 if (source != nil) {
4755 label = [source label];
4756 trusted = [source trusted];
4757 } else if ([[package id] isEqualToString:@"firmware"])
4758 label = UCLocalize("APPLE");
4760 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4762 NSString *from(label);
4764 NSString *section = [package simpleSection];
4765 if (section != nil && ![section isEqualToString:label]) {
4766 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4767 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4770 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4771 source_ = [from retain];
4773 if (NSString *purpose = [package primaryPurpose])
4774 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4775 badge_ = [badge_ retain];
4777 if ([package installed] != nil)
4778 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4779 placard_ = [placard_ retain];
4781 [self _setBackgroundColor];
4782 [content_ setNeedsDisplay];
4785 - (void) drawContentRect:(CGRect)rect {
4786 bool selected([self isSelected]);
4787 float width([self bounds].size.width);
4790 CGContextRef context(UIGraphicsGetCurrentContext());
4791 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4792 CGContextFillRect(context, rect);
4797 rect.size = [icon_ size];
4799 rect.size.width /= 2;
4800 rect.size.height /= 2;
4802 rect.origin.x = 25 - rect.size.width / 2;
4803 rect.origin.y = 25 - rect.size.height / 2;
4805 [icon_ drawInRect:rect];
4808 if (badge_ != nil) {
4809 CGSize size = [badge_ size];
4811 [badge_ drawAtPoint:CGPointMake(
4812 36 - size.width / 2,
4813 36 - size.height / 2
4821 UISetColor(commercial_ ? Purple_ : Black_);
4822 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4823 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4826 UISetColor(commercial_ ? Purplish_ : Gray_);
4827 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4829 if (placard_ != nil)
4830 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4833 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4834 //[self _setBackgroundColor];
4835 [super setSelected:selected animated:fade];
4836 [content_ setNeedsDisplay];
4839 + (int) heightForPackage:(Package *)package {
4845 /* Section Cell {{{ */
4846 @interface SectionCell : UITableViewCell <
4854 ContentView *content_;
4859 - (void) setSection:(Section *)section editing:(BOOL)editing;
4863 @implementation SectionCell
4865 - (void) clearSection {
4866 if (basic_ != nil) {
4871 if (section_ != nil) {
4881 if (count_ != nil) {
4888 [self clearSection];
4896 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4897 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4898 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4899 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4900 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4902 UIView *content([self contentView]);
4903 CGRect bounds([content bounds]);
4905 content_ = [[ContentView alloc] initWithFrame:bounds];
4906 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4907 [content addSubview:content_];
4908 [content_ setBackgroundColor:[UIColor whiteColor]];
4910 [content_ setDelegate:self];
4914 - (void) onSwitch:(id)sender {
4915 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4916 if (metadata == nil) {
4917 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4918 [Sections_ setObject:metadata forKey:basic_];
4922 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4925 - (void) setSection:(Section *)section editing:(BOOL)editing {
4926 if (editing != editing_) {
4928 [switch_ removeFromSuperview];
4930 [self addSubview:switch_];
4934 [self clearSection];
4936 if (section == nil) {
4937 name_ = [UCLocalize("ALL_PACKAGES") retain];
4940 basic_ = [section name];
4942 basic_ = [basic_ retain];
4944 section_ = [section localized];
4945 if (section_ != nil)
4946 section_ = [section_ retain];
4948 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4949 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4952 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4955 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4956 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
4958 [content_ setNeedsDisplay];
4961 - (void) setFrame:(CGRect)frame {
4962 [super setFrame:frame];
4964 CGRect rect([switch_ frame]);
4965 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4968 - (void) drawContentRect:(CGRect)rect {
4969 BOOL selected = [self isSelected];
4971 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4979 float width(rect.size.width);
4983 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4985 CGSize size = [count_ sizeWithFont:Font14_];
4989 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4995 /* File Table {{{ */
4996 @interface FileTable : CYViewController <
4997 UITableViewDataSource,
5000 _transient Database *database_;
5003 NSMutableArray *files_;
5007 - (id) initWithDatabase:(Database *)database;
5008 - (void) setPackage:(Package *)package;
5012 @implementation FileTable
5015 if (package_ != nil)
5024 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5025 return files_ == nil ? 0 : [files_ count];
5028 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5032 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5033 static NSString *reuseIdentifier = @"Cell";
5035 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5037 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5038 [cell setFont:[UIFont systemFontOfSize:16]];
5040 [cell setText:[files_ objectAtIndex:indexPath.row]];
5041 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5046 - (id) initWithDatabase:(Database *)database {
5047 if ((self = [super init]) != nil) {
5048 database_ = database;
5050 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5052 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5054 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5055 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5056 [list_ setRowHeight:24.0f];
5057 [[self view] addSubview:list_];
5059 [list_ setDataSource:self];
5060 [list_ setDelegate:self];
5064 - (void) setPackage:(Package *)package {
5065 if (package_ != nil) {
5066 [package_ autorelease];
5075 [files_ removeAllObjects];
5077 if (package != nil) {
5078 package_ = [package retain];
5079 name_ = [[package id] retain];
5081 if (NSArray *files = [package files])
5082 [files_ addObjectsFromArray:files];
5084 if ([files_ count] != 0) {
5085 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5086 [files_ removeObjectAtIndex:0];
5087 [files_ sortUsingSelector:@selector(compareByPath:)];
5089 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5090 [stack addObject:@"/"];
5092 for (int i(0), e([files_ count]); i != e; ++i) {
5093 NSString *file = [files_ objectAtIndex:i];
5094 while (![file hasPrefix:[stack lastObject]])
5095 [stack removeLastObject];
5096 NSString *directory = [stack lastObject];
5097 [stack addObject:[file stringByAppendingString:@"/"]];
5098 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5099 ([stack count] - 2) * 3, "",
5100 [file substringFromIndex:[directory length]]
5109 - (void) reloadData {
5110 [self setPackage:[database_ packageWithName:name_]];
5115 /* Package Controller {{{ */
5116 @interface PackageController : CYBrowserController <
5117 UIActionSheetDelegate
5119 _transient Database *database_;
5123 NSMutableArray *buttons_;
5124 UIBarButtonItem *button_;
5127 - (id) initWithDatabase:(Database *)database;
5128 - (void) setPackage:(Package *)package;
5132 @implementation PackageController
5135 if (package_ != nil)
5149 if ([self retainCount] == 1)
5150 [delegate_ setPackageController:self];
5154 /* XXX: this is not safe at all... localization of /fail/ */
5155 - (void) _clickButtonWithName:(NSString *)name {
5156 if ([name isEqualToString:UCLocalize("CLEAR")])
5157 [delegate_ clearPackage:package_];
5158 else if ([name isEqualToString:UCLocalize("INSTALL")])
5159 [delegate_ installPackage:package_];
5160 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5161 [delegate_ installPackage:package_];
5162 else if ([name isEqualToString:UCLocalize("REMOVE")])
5163 [delegate_ removePackage:package_];
5164 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5165 [delegate_ installPackage:package_];
5166 else _assert(false);
5169 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5170 NSString *context([sheet context]);
5172 if ([context isEqualToString:@"modify"]) {
5173 if (button != [sheet cancelButtonIndex]) {
5174 NSString *buttonName = [buttons_ objectAtIndex:button];
5175 [self _clickButtonWithName:buttonName];
5178 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5182 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5183 [super webView:view didClearWindowObject:window forFrame:frame];
5184 [window setValue:package_ forKey:@"package"];
5187 - (bool) _allowJavaScriptPanel {
5192 - (void) _customButtonClicked {
5193 int count([buttons_ count]);
5198 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5200 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5201 [buttons addObjectsFromArray:buttons_];
5203 UIActionSheet *sheet = [[[UIActionSheet alloc]
5206 cancelButtonTitle:nil
5207 destructiveButtonTitle:nil
5208 otherButtonTitles:nil
5211 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5213 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5214 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5216 [sheet setContext:@"modify"];
5218 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5222 // We don't want to allow non-commercial packages to do custom things to the install button,
5223 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5224 - (void) customButtonClicked {
5226 [super customButtonClicked];
5228 [self _customButtonClicked];
5231 - (void) reloadButtonClicked {
5232 // Don't reload a package view by clicking the button.
5235 - (void) applyLoadingTitle {
5236 // Don't show "Loading" as the title. Ever.
5239 - (UIBarButtonItem *) rightButton {
5244 - (id) initWithDatabase:(Database *)database {
5245 if ((self = [super init]) != nil) {
5246 database_ = database;
5247 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5248 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5252 - (void) setPackage:(Package *)package {
5253 if (package_ != nil) {
5254 [package_ autorelease];
5263 [buttons_ removeAllObjects];
5265 if (package != nil) {
5268 package_ = [package retain];
5269 name_ = [[package id] retain];
5270 commercial_ = [package isCommercial];
5272 if ([package_ mode] != nil)
5273 [buttons_ addObject:UCLocalize("CLEAR")];
5274 if ([package_ source] == nil);
5275 else if ([package_ upgradableAndEssential:NO])
5276 [buttons_ addObject:UCLocalize("UPGRADE")];
5277 else if ([package_ uninstalled])
5278 [buttons_ addObject:UCLocalize("INSTALL")];
5280 [buttons_ addObject:UCLocalize("REINSTALL")];
5281 if (![package_ uninstalled])
5282 [buttons_ addObject:UCLocalize("REMOVE")];
5289 switch ([buttons_ count]) {
5290 case 0: title = nil; break;
5291 case 1: title = [buttons_ objectAtIndex:0]; break;
5292 default: title = UCLocalize("MODIFY"); break;
5295 button_ = [[UIBarButtonItem alloc]
5297 style:UIBarButtonItemStylePlain
5299 action:@selector(customButtonClicked)
5303 - (bool) isLoading {
5304 return commercial_ ? [super isLoading] : false;
5307 - (void) reloadData {
5308 [self setPackage:[database_ packageWithName:name_]];
5313 /* Package Table {{{ */
5314 @interface PackageTable : UIView <
5315 UITableViewDataSource,
5318 _transient Database *database_;
5319 NSMutableArray *packages_;
5320 NSMutableArray *sections_;
5322 NSMutableArray *index_;
5323 NSMutableDictionary *indices_;
5324 // XXX: this target_ seems to be delegate_. :(
5325 _transient id target_;
5327 // XXX: why do we even have this delegate_?
5328 _transient id delegate_;
5331 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5333 - (void) setDelegate:(id)delegate;
5335 - (void) reloadData;
5336 - (void) resetCursor;
5338 - (UITableView *) list;
5340 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5342 - (void) deselectWithAnimation:(BOOL)animated;
5346 @implementation PackageTable
5349 [packages_ release];
5350 [sections_ release];
5358 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5359 NSInteger count([sections_ count]);
5360 return count == 0 ? 1 : count;
5363 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5364 if ([sections_ count] == 0)
5366 return [[sections_ objectAtIndex:section] name];
5369 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5370 if ([sections_ count] == 0)
5372 return [[sections_ objectAtIndex:section] count];
5375 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5376 Section *section([sections_ objectAtIndex:[path section]]);
5377 NSInteger row([path row]);
5378 Package *package([packages_ objectAtIndex:([section row] + row)]);
5382 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5383 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5385 cell = [[[PackageCell alloc] init] autorelease];
5386 [cell setPackage:[self packageAtIndexPath:path]];
5390 - (void) deselectWithAnimation:(BOOL)animated {
5391 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5394 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5395 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5398 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5399 Package *package([self packageAtIndexPath:path]);
5400 package = [database_ packageWithName:[package id]];
5401 [target_ performSelector:action_ withObject:package];
5405 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5406 return [packages_ count] > 20 ? index_ : nil;
5409 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5413 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5414 if ((self = [super initWithFrame:frame]) != nil) {
5415 database_ = database;
5420 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5421 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5423 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5424 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5426 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5427 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5428 [list_ setRowHeight:73.0f];
5429 [self addSubview:list_];
5431 [list_ setDataSource:self];
5432 [list_ setDelegate:self];
5436 - (void) setDelegate:(id)delegate {
5437 delegate_ = delegate;
5440 - (bool) hasPackage:(Package *)package {
5444 - (void) reloadData {
5445 NSArray *packages = [database_ packages];
5447 [packages_ removeAllObjects];
5448 [sections_ removeAllObjects];
5450 _profile(PackageTable$reloadData$Filter)
5451 for (Package *package in packages)
5452 if ([self hasPackage:package])
5453 [packages_ addObject:package];
5456 [index_ removeAllObjects];
5457 [indices_ removeAllObjects];
5459 Section *section = nil;
5461 _profile(PackageTable$reloadData$Section)
5462 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5466 _profile(PackageTable$reloadData$Section$Package)
5467 package = [packages_ objectAtIndex:offset];
5468 index = [package index];
5471 if (section == nil || [section index] != index) {
5472 _profile(PackageTable$reloadData$Section$Allocate)
5473 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5476 [index_ addObject:[section name]];
5477 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5479 _profile(PackageTable$reloadData$Section$Add)
5480 [sections_ addObject:section];
5484 [section addToCount];
5488 _profile(PackageTable$reloadData$List)
5493 - (void) resetCursor {
5494 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5497 - (UITableView *) list {
5501 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5502 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5507 /* Filtered Package Table {{{ */
5508 @interface FilteredPackageTable : PackageTable {
5514 - (void) setObject:(id)object;
5515 - (void) setObject:(id)object forFilter:(SEL)filter;
5517 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5521 @implementation FilteredPackageTable
5529 - (void) setFilter:(SEL)filter {
5532 /* XXX: this is an unsafe optimization of doomy hell */
5533 Method method(class_getInstanceMethod([Package class], filter));
5534 _assert(method != NULL);
5535 imp_ = method_getImplementation(method);
5536 _assert(imp_ != NULL);
5539 - (void) setObject:(id)object {
5545 object_ = [object retain];
5548 - (void) setObject:(id)object forFilter:(SEL)filter {
5549 [self setFilter:filter];
5550 [self setObject:object];
5553 - (bool) hasPackage:(Package *)package {
5554 _profile(FilteredPackageTable$hasPackage)
5555 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5559 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5560 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5561 [self setFilter:filter];
5562 object_ = [object retain];
5570 /* Filtered Package Controller {{{ */
5571 @interface FilteredPackageController : CYViewController {
5572 _transient Database *database_;
5573 FilteredPackageTable *packages_;
5577 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5581 @implementation FilteredPackageController
5584 [packages_ release];
5590 - (void) viewDidAppear:(BOOL)animated {
5591 [super viewDidAppear:animated];
5592 [packages_ deselectWithAnimation:animated];
5595 - (void) didSelectPackage:(Package *)package {
5596 PackageController *view([delegate_ packageController]);
5597 [view setPackage:package];
5598 [view setDelegate:delegate_];
5599 [[self navigationController] pushViewController:view animated:YES];
5602 - (NSString *) title { return title_; }
5604 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5605 if ((self = [super init]) != nil) {
5606 database_ = database;
5607 title_ = [title copy];
5608 [[self navigationItem] setTitle:title_];
5610 packages_ = [[FilteredPackageTable alloc]
5611 initWithFrame:[[self view] bounds]
5614 action:@selector(didSelectPackage:)
5619 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5620 [[self view] addSubview:packages_];
5624 - (void) reloadData {
5625 [packages_ reloadData];
5628 - (void) setDelegate:(id)delegate {
5629 [super setDelegate:delegate];
5630 [packages_ setDelegate:delegate];
5637 /* Add Source Controller {{{ */
5638 @interface AddSourceController : CYViewController {
5639 _transient Database *database_;
5642 - (id) initWithDatabase:(Database *)database;
5646 @implementation AddSourceController
5648 - (id) initWithDatabase:(Database *)database {
5649 if ((self = [super init]) != nil) {
5650 database_ = database;
5656 /* Source Cell {{{ */
5657 @interface SourceCell : UITableViewCell <
5662 NSString *description_;
5664 ContentView *content_;
5667 - (void) setSource:(Source *)source;
5671 @implementation SourceCell
5673 - (void) clearSource {
5676 [description_ release];
5685 - (void) setSource:(Source *)source {
5689 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5691 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5692 icon_ = [icon_ retain];
5694 origin_ = [[source name] retain];
5695 label_ = [[source uri] retain];
5696 description_ = [[source description] retain];
5698 [content_ setNeedsDisplay];
5707 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5708 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5709 UIView *content([self contentView]);
5710 CGRect bounds([content bounds]);
5712 content_ = [[ContentView alloc] initWithFrame:bounds];
5713 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5714 [content_ setBackgroundColor:[UIColor whiteColor]];
5715 [content addSubview:content_];
5717 [content_ setDelegate:self];
5718 [content_ setOpaque:YES];
5722 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5723 [super setSelected:selected animated:animated];
5724 [content_ setNeedsDisplay];
5727 - (void) drawContentRect:(CGRect)rect {
5728 bool selected([self isSelected]);
5729 float width(rect.size.width);
5732 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5739 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5743 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5747 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5752 /* Source Table {{{ */
5753 @interface SourceTable : CYViewController <
5754 UITableViewDataSource,
5757 _transient Database *database_;
5759 NSMutableArray *sources_;
5763 UIProgressHUD *hud_;
5766 //NSURLConnection *installer_;
5767 NSURLConnection *trivial_;
5768 NSURLConnection *trivial_bz2_;
5769 NSURLConnection *trivial_gz_;
5770 //NSURLConnection *automatic_;
5775 - (id) initWithDatabase:(Database *)database;
5777 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5781 @implementation SourceTable
5783 - (void) _releaseConnection:(NSURLConnection *)connection {
5784 if (connection != nil) {
5785 [connection cancel];
5786 //[connection setDelegate:nil];
5787 [connection release];
5799 //[self _releaseConnection:installer_];
5800 [self _releaseConnection:trivial_];
5801 [self _releaseConnection:trivial_gz_];
5802 [self _releaseConnection:trivial_bz2_];
5803 //[self _releaseConnection:automatic_];
5810 - (void) viewDidAppear:(BOOL)animated {
5811 [super viewDidAppear:animated];
5812 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5815 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5816 return offset_ == 0 ? 1 : 2;
5819 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5820 switch (section + (offset_ == 0 ? 1 : 0)) {
5821 case 0: return UCLocalize("ENTERED_BY_USER");
5822 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5828 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5829 int count = [sources_ count];
5831 case 0: return (offset_ == 0 ? count : offset_);
5832 case 1: return count - offset_;
5838 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5840 switch (indexPath.section) {
5841 case 0: idx = indexPath.row; break;
5842 case 1: idx = indexPath.row + offset_; break;
5846 return [sources_ objectAtIndex:idx];
5849 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5850 Source *source = [self sourceAtIndexPath:indexPath];
5851 return [source description] == nil ? 56 : 73;
5854 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5855 static NSString *cellIdentifier = @"SourceCell";
5857 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5858 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5859 [cell setSource:[self sourceAtIndexPath:indexPath]];
5864 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5865 return UITableViewCellAccessoryDisclosureIndicator;
5868 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5869 Source *source = [self sourceAtIndexPath:indexPath];
5871 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5872 initWithDatabase:database_
5873 title:[source label]
5874 filter:@selector(isVisibleInSource:)
5878 [packages setDelegate:delegate_];
5880 [[self navigationController] pushViewController:packages animated:YES];
5883 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5884 Source *source = [self sourceAtIndexPath:indexPath];
5885 return [source record] != nil;
5888 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5889 Source *source = [self sourceAtIndexPath:indexPath];
5890 [Sources_ removeObjectForKey:[source key]];
5891 [delegate_ syncData];
5895 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5898 @"./", @"Distribution",
5899 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5901 [delegate_ syncData];
5904 - (NSString *) getWarning {
5905 NSString *href(href_);
5906 NSRange colon([href rangeOfString:@"://"]);
5907 if (colon.location != NSNotFound)
5908 href = [href substringFromIndex:(colon.location + 3)];
5909 href = [href stringByAddingPercentEscapes];
5910 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5911 href = [href stringByCachingURLWithCurrentCDN];
5913 NSURL *url([NSURL URLWithString:href]);
5915 NSStringEncoding encoding;
5916 NSError *error(nil);
5918 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5919 return [warning length] == 0 ? nil : warning;
5923 - (void) _endConnection:(NSURLConnection *)connection {
5924 // XXX: the memory management in this method is horribly awkward
5926 NSURLConnection **field = NULL;
5927 if (connection == trivial_)
5929 else if (connection == trivial_bz2_)
5930 field = &trivial_bz2_;
5931 else if (connection == trivial_gz_)
5932 field = &trivial_gz_;
5933 _assert(field != NULL);
5934 [connection release];
5939 trivial_bz2_ == nil &&
5945 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5948 UIAlertView *alert = [[[UIAlertView alloc]
5949 initWithTitle:UCLocalize("SOURCE_WARNING")
5952 cancelButtonTitle:UCLocalize("CANCEL")
5953 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5956 [alert setContext:@"warning"];
5957 [alert setNumberOfRows:1];
5961 } else if (error_ != nil) {
5962 UIAlertView *alert = [[[UIAlertView alloc]
5963 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5964 message:[error_ localizedDescription]
5966 cancelButtonTitle:UCLocalize("OK")
5967 otherButtonTitles:nil
5970 [alert setContext:@"urlerror"];
5973 UIAlertView *alert = [[[UIAlertView alloc]
5974 initWithTitle:UCLocalize("NOT_REPOSITORY")
5975 message:UCLocalize("NOT_REPOSITORY_EX")
5977 cancelButtonTitle:UCLocalize("OK")
5978 otherButtonTitles:nil
5981 [alert setContext:@"trivial"];
5985 [delegate_ setStatusBarShowsProgress:NO];
5986 [delegate_ removeProgressHUD:hud_];
5996 if (error_ != nil) {
6003 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6004 switch ([response statusCode]) {
6010 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6011 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6013 error_ = [error retain];
6014 [self _endConnection:connection];
6017 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6018 [self _endConnection:connection];
6021 - (NSString *) title { return UCLocalize("SOURCES"); }
6023 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6024 NSMutableURLRequest *request = [NSMutableURLRequest
6025 requestWithURL:[NSURL URLWithString:href]
6026 cachePolicy:NSURLRequestUseProtocolCachePolicy
6027 timeoutInterval:120.0
6030 [request setHTTPMethod:method];
6032 if (Machine_ != NULL)
6033 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6034 if (UniqueID_ != nil)
6035 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6037 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6039 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6042 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6043 NSString *context([alert context]);
6045 if ([context isEqualToString:@"source"]) {
6048 NSString *href = [[alert textField] text];
6050 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6052 if (![href hasSuffix:@"/"])
6053 href_ = [href stringByAppendingString:@"/"];
6056 href_ = [href_ retain];
6058 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6059 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6060 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6061 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6065 // XXX: this is stupid
6066 hud_ = [[delegate_ addProgressHUD] retain];
6067 [hud_ setText:UCLocalize("VERIFYING_URL")];
6076 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6077 } else if ([context isEqualToString:@"trivial"])
6078 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6079 else if ([context isEqualToString:@"urlerror"])
6080 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6081 else if ([context isEqualToString:@"warning"]) {
6096 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6100 - (id) initWithDatabase:(Database *)database {
6101 if ((self = [super init]) != nil) {
6102 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6103 [self updateButtonsForEditingStatus:NO animated:NO];
6105 database_ = database;
6106 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6108 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6109 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6110 [[self view] addSubview:list_];
6112 [list_ setDataSource:self];
6113 [list_ setDelegate:self];
6119 - (void) reloadData {
6121 if (!list.ReadMainList())
6124 [sources_ removeAllObjects];
6125 [sources_ addObjectsFromArray:[database_ sources]];
6127 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6130 int count([sources_ count]);
6132 for (int i = 0; i != count; i++) {
6133 if ([[sources_ objectAtIndex:i] record] == nil)
6138 [list_ setEditing:NO];
6139 [self updateButtonsForEditingStatus:NO animated:NO];
6143 - (void) addButtonClicked {
6144 /*[book_ pushPage:[[[AddSourceController alloc]
6149 UIAlertView *alert = [[[UIAlertView alloc]
6150 initWithTitle:UCLocalize("ENTER_APT_URL")
6153 cancelButtonTitle:UCLocalize("CANCEL")
6154 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6157 [alert setContext:@"source"];
6158 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6160 [alert setNumberOfRows:1];
6161 [alert addTextFieldWithValue:@"http://" label:@""];
6163 UITextInputTraits *traits = [[alert textField] textInputTraits];
6164 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6165 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6166 [traits setKeyboardType:UIKeyboardTypeURL];
6167 // XXX: UIReturnKeyDone
6168 [traits setReturnKeyType:UIReturnKeyNext];
6173 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6174 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6175 initWithTitle:UCLocalize("ADD")
6176 style:UIBarButtonItemStylePlain
6178 action:@selector(addButtonClicked)
6179 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6181 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6182 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6183 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6185 action:@selector(editButtonClicked)
6186 ] autorelease] animated:animated];
6188 if (IsWildcat_ && !editing)
6189 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6190 initWithTitle:UCLocalize("SETTINGS")
6191 style:UIBarButtonItemStylePlain
6193 action:@selector(settingsButtonClicked)
6197 - (void) settingsButtonClicked {
6198 [delegate_ showSettings];
6201 - (void) editButtonClicked {
6202 [list_ setEditing:![list_ isEditing] animated:YES];
6204 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6210 /* Installed Controller {{{ */
6211 @interface InstalledController : FilteredPackageController {
6215 - (id) initWithDatabase:(Database *)database;
6217 - (void) updateRoleButton;
6218 - (void) queueStatusDidChange;
6222 @implementation InstalledController
6228 - (NSString *) title { return UCLocalize("INSTALLED"); }
6230 - (id) initWithDatabase:(Database *)database {
6231 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6232 [self updateRoleButton];
6233 [self queueStatusDidChange];
6238 - (void) queueButtonClicked {
6243 - (void) queueStatusDidChange {
6247 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6248 initWithTitle:UCLocalize("QUEUE")
6249 style:UIBarButtonItemStyleDone
6251 action:@selector(queueButtonClicked)
6254 [[self navigationItem] setLeftBarButtonItem:nil];
6260 - (void) reloadData {
6261 [packages_ reloadData];
6264 - (void) updateRoleButton {
6265 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6266 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6267 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6268 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6270 action:@selector(roleButtonClicked)
6274 - (void) roleButtonClicked {
6275 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6276 [packages_ reloadData];
6279 [self updateRoleButton];
6282 - (void) setDelegate:(id)delegate {
6283 [super setDelegate:delegate];
6284 [packages_ setDelegate:delegate];
6290 /* Home Controller {{{ */
6291 @interface HomeController : CYBrowserController {
6296 @implementation HomeController
6298 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6299 [super _setMoreHeaders:request];
6302 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6303 if (UniqueID_ != nil)
6304 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6306 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6309 - (void) aboutButtonClicked {
6310 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6312 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6313 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6314 [alert setCancelButtonIndex:0];
6317 @"Copyright (C) 2008-2010\n"
6318 "Jay Freeman (saurik)\n"
6319 "saurik@saurik.com\n"
6320 "http://www.saurik.com/"
6326 - (void) viewWillAppear:(BOOL)animated {
6327 [super viewWillAppear:animated];
6328 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6331 - (void) viewWillDisappear:(BOOL)animated {
6332 [super viewWillDisappear:animated];
6333 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6337 if ((self = [super init]) != nil) {
6338 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6339 initWithTitle:UCLocalize("ABOUT")
6340 style:UIBarButtonItemStylePlain
6342 action:@selector(aboutButtonClicked)
6349 /* Manage Controller {{{ */
6350 @interface ManageController : CYBrowserController {
6353 - (void) queueStatusDidChange;
6356 @implementation ManageController
6359 if ((self = [super init]) != nil) {
6360 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6362 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6363 initWithTitle:UCLocalize("SETTINGS")
6364 style:UIBarButtonItemStylePlain
6366 action:@selector(settingsButtonClicked)
6369 [self queueStatusDidChange];
6373 - (void) settingsButtonClicked {
6374 [delegate_ showSettings];
6378 - (void) queueButtonClicked {
6382 - (void) applyLoadingTitle {
6383 // No "Loading" title.
6386 - (void) applyRightButton {
6391 - (void) queueStatusDidChange {
6393 if (!IsWildcat_ && Queuing_) {
6394 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6395 initWithTitle:UCLocalize("QUEUE")
6396 style:UIBarButtonItemStyleDone
6398 action:@selector(queueButtonClicked)
6401 [[self navigationItem] setRightBarButtonItem:nil];
6406 - (bool) isLoading {
6413 /* Refresh Bar {{{ */
6414 @interface RefreshBar : UINavigationBar {
6415 UIProgressIndicator *indicator_;
6416 UITextLabel *prompt_;
6417 UIProgressBar *progress_;
6418 UINavigationButton *cancel_;
6423 @implementation RefreshBar
6426 [indicator_ release];
6428 [progress_ release];
6433 - (void) positionViews {
6434 CGRect frame = [cancel_ frame];
6435 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6436 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6437 [cancel_ setFrame:frame];
6439 CGSize prgsize = {75, 100};
6441 [self frame].size.width - prgsize.width - 10,
6442 ([self frame].size.height - prgsize.height) / 2
6444 [progress_ setFrame:prgrect];
6446 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6447 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6448 CGRect indrect = {{indoffset, indoffset}, indsize};
6449 [indicator_ setFrame:indrect];
6451 CGSize prmsize = {215, indsize.height + 4};
6453 indoffset * 2 + indsize.width,
6454 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6456 [prompt_ setFrame:prmrect];
6459 - (void)setFrame:(CGRect)frame {
6460 [super setFrame:frame];
6462 [self positionViews];
6465 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6466 if ((self = [super initWithFrame:frame])) {
6467 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6469 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6470 [self setBarStyle:UIBarStyleBlack];
6472 UIBarStyle barstyle([self _barStyle:NO]);
6473 bool ugly(barstyle == UIBarStyleDefault);
6475 UIProgressIndicatorStyle style = ugly ?
6476 UIProgressIndicatorStyleMediumBrown :
6477 UIProgressIndicatorStyleMediumWhite;
6479 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6480 [indicator_ setStyle:style];
6481 [indicator_ startAnimation];
6482 [self addSubview:indicator_];
6484 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6485 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6486 [prompt_ setBackgroundColor:[UIColor clearColor]];
6487 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6488 [self addSubview:prompt_];
6490 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6491 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6492 [progress_ setStyle:0];
6493 [self addSubview:progress_];
6495 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6496 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6497 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6498 [cancel_ setBarStyle:barstyle];
6500 [self positionViews];
6505 [cancel_ removeFromSuperview];
6509 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6510 [progress_ setProgress:0];
6511 [self addSubview:cancel_];
6515 [cancel_ removeFromSuperview];
6518 - (void) setPrompt:(NSString *)prompt {
6519 [prompt_ setText:prompt];
6522 - (void) setProgress:(float)progress {
6523 [progress_ setProgress:progress];
6529 @class CYNavigationController;
6531 /* Cydia Tab Bar Controller {{{ */
6532 @interface CYTabBarController : UITabBarController {
6533 _transient Database *database_;
6538 @implementation CYTabBarController
6540 /* XXX: some logic should probably go here related to
6541 freeing the view controllers on tab change */
6543 - (void) reloadData {
6544 size_t count([[self viewControllers] count]);
6545 for (size_t i(0); i != count; ++i) {
6546 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6551 - (id) initWithDatabase:(Database *)database {
6552 if ((self = [super init]) != nil) {
6553 database_ = database;
6560 /* Cydia Navigation Controller {{{ */
6561 @interface CYNavigationController : UINavigationController {
6562 _transient Database *database_;
6563 _transient id<UINavigationControllerDelegate> delegate_;
6566 - (id) initWithDatabase:(Database *)database;
6567 - (void) reloadData;
6572 @implementation CYNavigationController
6574 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6575 // Inherit autorotation settings for modal parents.
6576 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6577 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6579 return [super shouldAutorotateToInterfaceOrientation:orientation];
6587 - (void) reloadData {
6588 size_t count([[self viewControllers] count]);
6589 for (size_t i(0); i != count; ++i) {
6590 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6595 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6596 delegate_ = delegate;
6599 - (id) initWithDatabase:(Database *)database {
6600 if ((self = [super init]) != nil) {
6601 database_ = database;
6607 /* Cydia:// Protocol {{{ */
6608 @interface CydiaURLProtocol : NSURLProtocol {
6613 @implementation CydiaURLProtocol
6615 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6616 NSURL *url([request URL]);
6619 NSString *scheme([[url scheme] lowercaseString]);
6620 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6625 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6629 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6630 id<NSURLProtocolClient> client([self client]);
6632 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6634 NSData *data(UIImagePNGRepresentation(icon));
6636 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6637 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6638 [client URLProtocol:self didLoadData:data];
6639 [client URLProtocolDidFinishLoading:self];
6643 - (void) startLoading {
6644 id<NSURLProtocolClient> client([self client]);
6645 NSURLRequest *request([self request]);
6647 NSURL *url([request URL]);
6648 NSString *href([url absoluteString]);
6650 NSString *path([href substringFromIndex:8]);
6651 NSRange slash([path rangeOfString:@"/"]);
6654 if (slash.location == NSNotFound) {
6658 command = [path substringToIndex:slash.location];
6659 path = [path substringFromIndex:(slash.location + 1)];
6662 Database *database([Database sharedInstance]);
6664 if ([command isEqualToString:@"package-icon"]) {
6667 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6668 Package *package([database packageWithName:path]);
6671 UIImage *icon([package icon]);
6672 [self _returnPNGWithImage:icon forRequest:request];
6673 } else if ([command isEqualToString:@"source-icon"]) {
6676 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6677 NSString *source(Simplify(path));
6678 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6680 icon = [UIImage applicationImageNamed:@"unknown.png"];
6681 [self _returnPNGWithImage:icon forRequest:request];
6682 } else if ([command isEqualToString:@"uikit-image"]) {
6685 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6686 UIImage *icon(_UIImageWithName(path));
6687 [self _returnPNGWithImage:icon forRequest:request];
6688 } else if ([command isEqualToString:@"section-icon"]) {
6691 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6692 NSString *section(Simplify(path));
6693 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6695 icon = [UIImage applicationImageNamed:@"unknown.png"];
6696 [self _returnPNGWithImage:icon forRequest:request];
6698 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6702 - (void) stopLoading {
6708 /* Sections Controller {{{ */
6709 @interface SectionsController : CYViewController <
6710 UITableViewDataSource,
6713 _transient Database *database_;
6714 NSMutableArray *sections_;
6715 NSMutableArray *filtered_;
6721 - (id) initWithDatabase:(Database *)database;
6722 - (void) reloadData;
6725 - (void) editButtonClicked;
6729 @implementation SectionsController
6732 [list_ setDataSource:nil];
6733 [list_ setDelegate:nil];
6735 [sections_ release];
6736 [filtered_ release];
6738 [accessory_ release];
6742 - (void) viewDidAppear:(BOOL)animated {
6743 [super viewDidAppear:animated];
6744 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6747 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6748 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6752 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6753 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6756 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6760 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6761 static NSString *reuseIdentifier = @"SectionCell";
6763 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6765 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6767 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6772 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6776 Section *section = [self sectionAtIndexPath:indexPath];
6777 NSString *name = [section name];
6780 if ([indexPath row] == 0) {
6783 title = UCLocalize("ALL_PACKAGES");
6786 name = [NSString stringWithString:name];
6787 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6790 title = UCLocalize("NO_SECTION");
6794 FilteredPackageController *table = [[[FilteredPackageController alloc]
6795 initWithDatabase:database_
6797 filter:@selector(isVisibleInSection:)
6801 [table setDelegate:delegate_];
6803 [[self navigationController] pushViewController:table animated:YES];
6806 - (NSString *) title { return UCLocalize("SECTIONS"); }
6808 - (id) initWithDatabase:(Database *)database {
6809 if ((self = [super init]) != nil) {
6810 database_ = database;
6812 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6814 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6815 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6817 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6818 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6819 [list_ setRowHeight:45.0f];
6820 [[self view] addSubview:list_];
6822 [list_ setDataSource:self];
6823 [list_ setDelegate:self];
6829 - (void) reloadData {
6830 NSArray *packages = [database_ packages];
6832 [sections_ removeAllObjects];
6833 [filtered_ removeAllObjects];
6836 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6837 SectionMap sections;
6838 sections.resize(64);
6840 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6844 for (Package *package in packages) {
6845 NSString *name([package section]);
6846 NSString *key(name == nil ? @"" : name);
6851 _profile(SectionsView$reloadData$Section)
6852 section = §ions[key];
6853 if (*section == nil) {
6854 _profile(SectionsView$reloadData$Section$Allocate)
6855 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6860 [*section addToCount];
6862 _profile(SectionsView$reloadData$Filter)
6863 if (![package valid] || ![package visible])
6867 [*section addToRow];
6871 _profile(SectionsView$reloadData$Section)
6872 section = [sections objectForKey:key];
6873 if (section == nil) {
6874 _profile(SectionsView$reloadData$Section$Allocate)
6875 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6876 [sections setObject:section forKey:key];
6881 [section addToCount];
6883 _profile(SectionsView$reloadData$Filter)
6884 if (![package valid] || ![package visible])
6894 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6895 [sections_ addObject:i->second];
6897 [sections_ addObjectsFromArray:[sections allValues]];
6900 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6902 for (Section *section in sections_) {
6903 size_t count([section row]);
6907 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6908 [section setCount:count];
6909 [filtered_ addObject:section];
6912 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6913 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
6914 style:UIBarButtonItemStylePlain
6916 action:@selector(editButtonClicked)
6917 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6923 - (void) resetView {
6925 [self editButtonClicked];
6928 - (void) editButtonClicked {
6929 if ((editing_ = !editing_))
6932 [delegate_ updateData];
6934 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6935 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6936 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6939 - (UIView *) accessoryView {
6945 /* Changes Controller {{{ */
6946 @interface ChangesController : CYViewController <
6947 UITableViewDataSource,
6950 _transient Database *database_;
6951 CFMutableArrayRef packages_;
6952 NSMutableArray *sections_;
6955 BOOL hasSentFirstLoad_;
6958 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6959 - (void) reloadData;
6963 @implementation ChangesController
6966 [list_ setDelegate:nil];
6967 [list_ setDataSource:nil];
6969 CFRelease(packages_);
6971 [sections_ release];
6976 - (void) viewDidAppear:(BOOL)animated {
6977 [super viewDidAppear:animated];
6978 if (!hasSentFirstLoad_) {
6979 hasSentFirstLoad_ = YES;
6980 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6982 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6986 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6987 NSInteger count([sections_ count]);
6988 return count == 0 ? 1 : count;
6991 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6992 if ([sections_ count] == 0)
6994 return [[sections_ objectAtIndex:section] name];
6997 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6998 if ([sections_ count] == 0)
7000 return [[sections_ objectAtIndex:section] count];
7003 - (Package *) packageAtIndex:(NSUInteger)index {
7004 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7007 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7008 Section *section([sections_ objectAtIndex:[path section]]);
7009 NSInteger row([path row]);
7010 return [self packageAtIndex:([section row] + row)];
7013 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7014 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7016 cell = [[[PackageCell alloc] init] autorelease];
7017 [cell setPackage:[self packageAtIndexPath:path]];
7021 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7022 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7025 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7026 Package *package([self packageAtIndexPath:path]);
7027 PackageController *view([delegate_ packageController]);
7028 [view setDelegate:delegate_];
7029 [view setPackage:package];
7030 [[self navigationController] pushViewController:view animated:YES];
7034 - (void) refreshButtonClicked {
7035 [delegate_ beginUpdate];
7036 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7039 - (void) upgradeButtonClicked {
7040 [delegate_ distUpgrade];
7043 - (NSString *) title { return UCLocalize("CHANGES"); }
7045 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7046 if ((self = [super init]) != nil) {
7047 database_ = database;
7048 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7050 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7052 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7054 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7055 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7056 [list_ setRowHeight:73.0f];
7057 [[self view] addSubview:list_];
7059 [list_ setDataSource:self];
7060 [list_ setDelegate:self];
7062 delegate_ = delegate;
7066 - (void) _reloadPackages:(NSArray *)packages {
7068 for (Package *package in packages)
7070 [package uninstalled] && [package valid] && [package visible] ||
7071 [package upgradableAndEssential:YES]
7073 CFArrayAppendValue(packages_, package);
7076 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7080 - (void) reloadData {
7081 NSArray *packages = [database_ packages];
7083 CFArrayRemoveAllValues(packages_);
7085 [sections_ removeAllObjects];
7088 UIProgressHUD *hud([delegate_ addProgressHUD]);
7090 [hud setText:@"Loading Changes"];
7091 //NSLog(@"HUD:%@::%@", delegate_, hud);
7092 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7093 [delegate_ removeProgressHUD:hud];
7095 [self _reloadPackages:packages];
7098 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7099 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7100 Section *section = nil;
7104 bool unseens = false;
7106 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7108 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7109 Package *package = [self packageAtIndex:offset];
7111 BOOL uae = [package upgradableAndEssential:YES];
7117 _profile(ChangesController$reloadData$Remember)
7118 seen = [package seen];
7121 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7126 name = UCLocalize("UNKNOWN");
7128 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7132 _profile(ChangesController$reloadData$Allocate)
7133 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7134 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7135 [sections_ addObject:section];
7139 [section addToCount];
7140 } else if ([package ignored])
7141 [ignored addToCount];
7144 [upgradable addToCount];
7149 CFRelease(formatter);
7152 Section *last = [sections_ lastObject];
7153 size_t count = [last count];
7154 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7155 [sections_ removeLastObject];
7158 if ([ignored count] != 0)
7159 [sections_ insertObject:ignored atIndex:0];
7161 [sections_ insertObject:upgradable atIndex:0];
7166 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7167 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7168 style:UIBarButtonItemStylePlain
7170 action:@selector(upgradeButtonClicked)
7173 if (![delegate_ updating])
7174 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7175 initWithTitle:UCLocalize("REFRESH")
7176 style:UIBarButtonItemStylePlain
7178 action:@selector(refreshButtonClicked)
7184 /* Search Controller {{{ */
7185 @interface SearchController : FilteredPackageController <
7188 UISearchBar *search_;
7191 - (id) initWithDatabase:(Database *)database;
7192 - (void) reloadData;
7196 @implementation SearchController
7203 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7204 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7205 [search_ resignFirstResponder];
7209 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7210 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7214 - (NSString *) title { return nil; }
7216 - (id) initWithDatabase:(Database *)database {
7217 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7220 - (void)viewDidAppear:(BOOL)animated {
7221 [super viewDidAppear:animated];
7223 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7224 [search_ layoutSubviews];
7225 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7226 UITextField *textField = [search_ searchField];
7227 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7228 [search_ setDelegate:self];
7229 [textField setEnablesReturnKeyAutomatically:NO];
7230 [[self navigationItem] setTitleView:textField];
7234 - (void) _reloadData {
7237 - (void) reloadData {
7238 _profile(SearchController$reloadData)
7239 [packages_ reloadData];
7242 [packages_ resetCursor];
7245 - (void) didSelectPackage:(Package *)package {
7246 [search_ resignFirstResponder];
7247 [super didSelectPackage:package];
7252 /* Settings Controller {{{ */
7253 @interface SettingsController : CYViewController <
7254 UITableViewDataSource,
7257 _transient Database *database_;
7260 UITableView *table_;
7261 UISwitch *subscribedSwitch_;
7262 UISwitch *ignoredSwitch_;
7263 UITableViewCell *subscribedCell_;
7264 UITableViewCell *ignoredCell_;
7267 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7271 @implementation SettingsController
7275 if (package_ != nil)
7278 [subscribedSwitch_ release];
7279 [ignoredSwitch_ release];
7280 [subscribedCell_ release];
7281 [ignoredCell_ release];
7286 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7287 if (package_ == nil)
7293 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7294 if (package_ == nil)
7300 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7301 return UCLocalize("SHOW_ALL_CHANGES_EX");
7304 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7305 if (package_ == nil)
7308 NSMutableDictionary *metadata([package_ metadata]);
7311 if (NSNumber *number = [metadata objectForKey:key])
7312 before = [number boolValue];
7316 if (value != before) {
7317 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7319 [delegate_ updateData];
7323 - (void) onSubscribed:(id)control {
7324 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7327 - (void) onIgnored:(id)control {
7328 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
7331 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7332 if (package_ == nil)
7335 switch ([indexPath row]) {
7336 case 0: return subscribedCell_;
7337 case 1: return ignoredCell_;
7345 - (NSString *) title { return UCLocalize("SETTINGS"); }
7347 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7348 if ((self = [super init])) {
7349 database_ = database;
7350 name_ = [package retain];
7352 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7354 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7355 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7356 [[self view] addSubview:table_];
7358 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7359 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7360 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7362 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7363 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7364 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7366 subscribedCell_ = [[UITableViewCell alloc] init];
7367 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7368 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7369 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7371 ignoredCell_ = [[UITableViewCell alloc] init];
7372 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7373 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7374 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7376 [table_ setDataSource:self];
7377 [table_ setDelegate:self];
7382 - (void) reloadData {
7383 if (package_ != nil)
7384 [package_ autorelease];
7385 package_ = [database_ packageWithName:name_];
7386 if (package_ != nil) {
7388 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7389 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7392 [table_ reloadData];
7397 /* Signature Controller {{{ */
7398 @interface SignatureController : CYBrowserController {
7399 _transient Database *database_;
7403 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7407 @implementation SignatureController
7414 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7416 [super webView:view didClearWindowObject:window forFrame:frame];
7419 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7420 if ((self = [super init]) != nil) {
7421 database_ = database;
7422 package_ = [package retain];
7427 - (void) reloadData {
7428 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7434 /* Role Controller {{{ */
7435 @interface RoleController : CYViewController <
7436 UITableViewDataSource,
7439 _transient Database *database_;
7440 // XXX: ok, "roledelegate_"?...
7441 _transient id roledelegate_;
7442 UITableView *table_;
7443 UISegmentedControl *segment_;
7447 - (void) showDoneButton;
7448 - (void) resizeSegmentedControl;
7452 @implementation RoleController
7456 [container_ release];
7461 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7462 if ((self = [super init])) {
7463 database_ = database;
7464 roledelegate_ = delegate;
7466 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7468 NSArray *items = [NSArray arrayWithObjects:
7470 UCLocalize("HACKER"),
7471 UCLocalize("DEVELOPER"),
7473 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7474 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7475 [container_ addSubview:segment_];
7478 if ([Role_ isEqualToString:@"User"]) index = 0;
7479 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7480 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7482 [segment_ setSelectedSegmentIndex:index];
7483 [self showDoneButton];
7486 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7487 [self resizeSegmentedControl];
7489 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7490 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7491 [table_ setDelegate:self];
7492 [table_ setDataSource:self];
7493 [[self view] addSubview:table_];
7494 [table_ reloadData];
7498 - (void) resizeSegmentedControl {
7499 CGFloat width = [[self view] frame].size.width;
7500 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7503 - (void) viewWillAppear:(BOOL)animated {
7504 [super viewWillAppear:animated];
7506 [self resizeSegmentedControl];
7509 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7510 [self resizeSegmentedControl];
7513 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7514 [self resizeSegmentedControl];
7518 NSString *role(nil);
7520 switch ([segment_ selectedSegmentIndex]) {
7521 case 0: role = @"User"; break;
7522 case 1: role = @"Hacker"; break;
7523 case 2: role = @"Developer"; break;
7528 if (![role isEqualToString:Role_]) {
7529 bool rolling(Role_ == nil);
7532 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7536 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7541 [roledelegate_ loadData];
7543 [roledelegate_ updateData];
7547 - (void) segmentChanged:(UISegmentedControl *)control {
7548 [self showDoneButton];
7551 - (void) saveAndClose {
7554 [[self navigationItem] setRightBarButtonItem:nil];
7555 [[self navigationController] dismissModalViewControllerAnimated:YES];
7558 - (void) doneButtonClicked {
7559 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7560 [spinner startAnimating];
7561 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7562 [[self navigationItem] setRightBarButtonItem:spinItem];
7564 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7567 - (void) showDoneButton {
7568 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7569 initWithTitle:UCLocalize("DONE")
7570 style:UIBarButtonItemStyleDone
7572 action:@selector(doneButtonClicked)
7573 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
7576 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7577 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7581 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7585 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7586 return nil; // This method is required by the protocol.
7589 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7591 return UCLocalize("ROLE_EX");
7593 return [NSString stringWithFormat:
7594 @"%@: %@\n%@: %@\n%@: %@",
7595 UCLocalize("USER"), UCLocalize("USER_EX"),
7596 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7597 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7602 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7603 return section == 3 ? 44.0f : 0;
7606 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7607 return section == 3 ? container_ : nil;
7612 /* Stash Controller {{{ */
7613 @interface CYStashController : CYViewController {
7614 // XXX: just delete these things
7615 _transient UIActivityIndicatorView *spinner_;
7616 _transient UILabel *status_;
7617 _transient UILabel *caption_;
7621 @implementation CYStashController
7623 if ((self = [super init])) {
7624 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7626 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
7627 CGRect spinrect = [spinner_ frame];
7628 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7629 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7630 [spinner_ setFrame:spinrect];
7631 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7632 [[self view] addSubview:spinner_];
7633 [spinner_ startAnimating];
7636 captrect.size.width = [[self view] frame].size.width;
7637 captrect.size.height = 40.0f;
7638 captrect.origin.x = 0;
7639 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7640 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
7641 [caption_ setText:@"Initializing Filesystem"];
7642 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7643 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7644 [caption_ setTextColor:[UIColor whiteColor]];
7645 [caption_ setBackgroundColor:[UIColor clearColor]];
7646 [caption_ setShadowColor:[UIColor blackColor]];
7647 [caption_ setTextAlignment:UITextAlignmentCenter];
7648 [[self view] addSubview:caption_];
7651 statusrect.size.width = [[self view] frame].size.width;
7652 statusrect.size.height = 30.0f;
7653 statusrect.origin.x = 0;
7654 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7655 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
7656 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7657 [status_ setText:@"(Cydia will exit when complete.)"];
7658 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7659 [status_ setTextColor:[UIColor whiteColor]];
7660 [status_ setBackgroundColor:[UIColor clearColor]];
7661 [status_ setShadowColor:[UIColor blackColor]];
7662 [status_ setTextAlignment:UITextAlignmentCenter];
7663 [[self view] addSubview:status_];
7667 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7668 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7673 /* Cydia Container {{{ */
7674 @interface CYContainer : UIViewController <ProgressDelegate> {
7675 _transient Database *database_;
7676 RefreshBar *refreshbar_;
7680 // XXX: ok, "updatedelegate_"?...
7681 _transient NSObject<CydiaDelegate> *updatedelegate_;
7682 // XXX: can't we query for this variable when we need it?
7683 _transient UITabBarController *root_;
7686 - (void) setTabBarController:(UITabBarController *)controller;
7688 - (void) dropBar:(BOOL)animated;
7689 - (void) beginUpdate;
7690 - (void) raiseBar:(BOOL)animated;
7695 @implementation CYContainer
7697 - (BOOL) _reallyWantsFullScreenLayout {
7701 // NOTE: UIWindow only sends the top controller these messages,
7702 // So we have to forward them on.
7704 - (void) viewDidAppear:(BOOL)animated {
7705 [super viewDidAppear:animated];
7706 [root_ viewDidAppear:animated];
7709 - (void) viewWillAppear:(BOOL)animated {
7710 [super viewWillAppear:animated];
7711 [root_ viewWillAppear:animated];
7714 - (void) viewDidDisappear:(BOOL)animated {
7715 [super viewDidDisappear:animated];
7716 [root_ viewDidDisappear:animated];
7719 - (void) viewWillDisappear:(BOOL)animated {
7720 [super viewWillDisappear:animated];
7721 [root_ viewWillDisappear:animated];
7724 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7725 return ![updatedelegate_ hudIsShowing] && (IsWildcat_ || orientation == UIInterfaceOrientationPortrait);
7728 - (void) setTabBarController:(UITabBarController *)controller {
7730 [[self view] addSubview:[root_ view]];
7733 - (void) setUpdate:(NSDate *)date {
7737 - (void) beginUpdate {
7739 [refreshbar_ start];
7744 detachNewThreadSelector:@selector(performUpdate)
7750 - (void) performUpdate { _pooled
7752 status.setDelegate(self);
7753 [database_ updateWithStatus:status];
7756 performSelectorOnMainThread:@selector(completeUpdate)
7762 - (void) completeUpdate {
7767 [self raiseBar:YES];
7769 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7772 - (void) cancelUpdate {
7774 [self raiseBar:YES];
7776 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7779 - (void) cancelPressed {
7780 [self cancelUpdate];
7787 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7788 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7791 - (void) startProgress {
7794 - (void) setProgressTitle:(NSString *)title {
7796 performSelectorOnMainThread:@selector(_setProgressTitle:)
7802 - (bool) isCancelling:(size_t)received {
7806 - (void) setProgressPercent:(float)percent {
7808 performSelectorOnMainThread:@selector(_setProgressPercent:)
7809 withObject:[NSNumber numberWithFloat:percent]
7814 - (void) addProgressOutput:(NSString *)output {
7816 performSelectorOnMainThread:@selector(_addProgressOutput:)
7822 - (void) _setProgressTitle:(NSString *)title {
7823 [refreshbar_ setPrompt:title];
7826 - (void) _setProgressPercent:(NSNumber *)percent {
7827 [refreshbar_ setProgress:[percent floatValue]];
7830 - (void) _addProgressOutput:(NSString *)output {
7833 - (void) setUpdateDelegate:(id)delegate {
7834 updatedelegate_ = delegate;
7837 - (CGFloat) statusBarHeight {
7838 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7839 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7841 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7845 - (void) dropBar:(BOOL)animated {
7850 [[self view] addSubview:refreshbar_];
7852 CGFloat sboffset = [self statusBarHeight];
7854 CGRect barframe = [refreshbar_ frame];
7855 barframe.origin.y = sboffset;
7856 [refreshbar_ setFrame:barframe];
7859 [UIView beginAnimations:nil context:NULL];
7860 CGRect viewframe = [[root_ view] frame];
7861 viewframe.origin.y += barframe.size.height + sboffset;
7862 viewframe.size.height -= barframe.size.height + sboffset;
7863 [[root_ view] setFrame:viewframe];
7865 [UIView commitAnimations];
7867 // Ensure bar has the proper width for our view, it might have changed
7868 barframe.size.width = viewframe.size.width;
7869 [refreshbar_ setFrame:barframe];
7871 // XXX: fix Apple's layout bug
7872 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7875 - (void) raiseBar:(BOOL)animated {
7880 [refreshbar_ removeFromSuperview];
7882 CGFloat sboffset = [self statusBarHeight];
7885 [UIView beginAnimations:nil context:NULL];
7886 CGRect barframe = [refreshbar_ frame];
7887 CGRect viewframe = [[root_ view] frame];
7888 viewframe.origin.y -= barframe.size.height + sboffset;
7889 viewframe.size.height += barframe.size.height + sboffset;
7890 [[root_ view] setFrame:viewframe];
7892 [UIView commitAnimations];
7894 // XXX: fix Apple's layout bug
7895 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7898 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7899 // XXX: fix Apple's layout bug
7900 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7903 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7909 // XXX: fix Apple's layout bug
7910 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7913 - (void) statusBarFrameChanged:(NSNotification *)notification {
7921 [refreshbar_ release];
7922 [[NSNotificationCenter defaultCenter] removeObserver:self];
7926 - (id) initWithDatabase:(Database *)database {
7927 if ((self = [super init]) != nil) {
7928 database_ = database;
7930 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7931 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7933 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7950 @interface Cydia : UIApplication <
7951 ConfirmationControllerDelegate,
7952 ProgressControllerDelegate,
7954 UINavigationControllerDelegate,
7955 UITabBarControllerDelegate
7957 // XXX: evaluate all fields for _transient
7960 CYContainer *container_;
7961 CYTabBarController *tabbar_;
7963 NSMutableArray *essential_;
7964 NSMutableArray *broken_;
7966 Database *database_;
7970 UIKeyboard *keyboard_;
7973 SectionsController *sections_;
7974 ChangesController *changes_;
7975 ManageController *manage_;
7976 SearchController *search_;
7977 SourceTable *sources_;
7978 InstalledController *installed_;
7981 CYStashController *stash_;
7986 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7987 - (void) setPage:(CYViewController *)page;
7992 static _finline void _setHomePage(Cydia *self) {
7993 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7996 @implementation Cydia
7998 - (void) beginUpdate {
7999 [container_ beginUpdate];
8003 return [container_ updating];
8006 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
8011 if ([broken_ count] != 0) {
8012 int count = [broken_ count];
8014 UIAlertView *alert = [[[UIAlertView alloc]
8015 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8016 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8018 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8019 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8022 [alert setContext:@"fixhalf"];
8024 } else if (!Ignored_ && [essential_ count] != 0) {
8025 int count = [essential_ count];
8027 UIAlertView *alert = [[[UIAlertView alloc]
8028 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8029 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8031 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8032 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8035 [alert setContext:@"upgrade"];
8040 - (void) _saveConfig {
8043 NSString *error(nil);
8044 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8046 NSError *error(nil);
8047 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8048 NSLog(@"failure to save metadata data: %@", error);
8051 NSLog(@"failure to serialize metadata: %@", error);
8059 - (void) _updateData {
8062 /* XXX: this is just stupid */
8063 if (tag_ != 1 && sections_ != nil)
8064 [sections_ reloadData];
8065 if (tag_ != 2 && changes_ != nil)
8066 [changes_ reloadData];
8067 if (tag_ != 4 && search_ != nil)
8068 [search_ reloadData];
8070 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8073 - (int)indexOfTabWithTag:(int)tag {
8075 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8076 if ([[controller tabBarItem] tag] == tag)
8084 - (void) _refreshIfPossible {
8085 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8087 bool recently = false;
8088 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8089 if (update != nil) {
8090 NSTimeInterval interval([update timeIntervalSinceNow]);
8091 if (interval <= 0 && interval > -(15*60))
8095 // Don't automatic refresh if:
8096 // - We already refreshed recently.
8097 // - We already auto-refreshed this launch.
8098 // - Auto-refresh is disabled.
8099 if (recently || loaded_ || ManualRefresh) {
8100 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8102 // If we are cancelling due to ManualRefresh or a recent refresh
8103 // we need to make sure it knows it's already loaded.
8107 // We are going to load, so remember that.
8111 SCNetworkReachabilityFlags flags; {
8112 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8113 SCNetworkReachabilityGetFlags(reachability, &flags);
8114 CFRelease(reachability);
8117 // XXX: this elaborate mess is what Apple is using to determine this? :(
8118 // XXX: do we care if the user has to intervene? maybe that's ok?
8120 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8121 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8122 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8123 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8124 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8125 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8129 // If we can reach the server, auto-refresh!
8131 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8136 - (void) refreshIfPossible {
8137 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8140 - (void) _reloadData {
8141 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8142 [hud setText:UCLocalize("RELOADING_DATA")];
8144 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8147 [self removeProgressHUD:hud];
8151 [essential_ removeAllObjects];
8152 [broken_ removeAllObjects];
8154 NSArray *packages([database_ packages]);
8155 for (Package *package in packages) {
8157 [broken_ addObject:package];
8158 if ([package upgradableAndEssential:NO]) {
8159 if ([package essential])
8160 [essential_ addObject:package];
8165 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8167 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8168 [changesItem setBadgeValue:badge];
8169 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8171 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8172 [self setApplicationBadge:badge];
8174 [self setApplicationBadgeString:badge];
8176 [changesItem setBadgeValue:nil];
8177 [changesItem setAnimatedBadge:NO];
8179 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8180 [self removeApplicationBadge];
8181 else // XXX: maybe use setApplicationBadgeString also?
8182 [self setApplicationIconBadgeNumber:0];
8187 [self refreshIfPossible];
8190 - (void) updateData {
8191 [database_ setVisible];
8200 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8201 _assert(file != NULL);
8203 for (NSString *key in [Sources_ allKeys]) {
8204 NSDictionary *source([Sources_ objectForKey:key]);
8206 fprintf(file, "%s %s %s\n",
8207 [[source objectForKey:@"Type"] UTF8String],
8208 [[source objectForKey:@"URI"] UTF8String],
8209 [[source objectForKey:@"Distribution"] UTF8String]
8217 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8218 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8220 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8221 [container_ presentModalViewController:navigation animated:YES];
8224 detachNewThreadSelector:@selector(update_)
8227 title:UCLocalize("UPDATING_SOURCES")
8231 - (void) reloadData {
8232 @synchronized (self) {
8238 pkgProblemResolver *resolver = [database_ resolver];
8240 resolver->InstallProtect();
8241 if (!resolver->Resolve(true))
8245 - (CGRect) popUpBounds {
8246 return [[tabbar_ view] bounds];
8250 if (![database_ prepare])
8253 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8254 [page setDelegate:self];
8255 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8256 [confirm_ setDelegate:self];
8259 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8260 [container_ presentModalViewController:confirm_ animated:YES];
8266 @synchronized (self) {
8271 - (void) clearPackage:(Package *)package {
8272 @synchronized (self) {
8279 - (void) installPackages:(NSArray *)packages {
8280 @synchronized (self) {
8281 for (Package *package in packages)
8288 - (void) installPackage:(Package *)package {
8289 @synchronized (self) {
8296 - (void) removePackage:(Package *)package {
8297 @synchronized (self) {
8304 - (void) distUpgrade {
8305 @synchronized (self) {
8306 if (![database_ upgrade])
8313 @synchronized (self) {
8318 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8319 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8321 if (navigation != nil) {
8322 [navigation pushViewController:progress animated:YES];
8324 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8326 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8327 [container_ presentModalViewController:navigation animated:YES];
8331 detachNewThreadSelector:@selector(perform)
8334 title:UCLocalize("RUNNING")
8338 - (void) progressControllerIsComplete:(ProgressController *)progress {
8342 - (void) setPage:(CYViewController *)page {
8343 [page setDelegate:self];
8345 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8346 [navController setViewControllers:[NSArray arrayWithObject:page]];
8347 for (CYNavigationController *page in [tabbar_ viewControllers])
8348 if (page != navController)
8349 [page setViewControllers:nil];
8352 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8353 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8354 [browser loadURL:url];
8358 - (SectionsController *) sectionsController {
8359 if (sections_ == nil)
8360 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8364 - (ChangesController *) changesController {
8365 if (changes_ == nil)
8366 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8370 - (ManageController *) manageController {
8371 if (manage_ == nil) {
8372 manage_ = (ManageController *) [[self
8373 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8374 withClass:[ManageController class]
8377 queueDelegate_ = manage_;
8382 - (SearchController *) searchController {
8384 search_ = [[SearchController alloc] initWithDatabase:database_];
8388 - (SourceTable *) sourcesController {
8389 if (sources_ == nil)
8390 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8394 - (InstalledController *) installedController {
8395 if (installed_ == nil) {
8396 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8398 queueDelegate_ = installed_;
8403 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8404 int tag = [[viewController tabBarItem] tag];
8406 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8408 } else if (tag_ == 1) {
8409 [[self sectionsController] resetView];
8413 case kCydiaTag: _setHomePage(self); break;
8415 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8416 case kChangesTag: [self setPage:[self changesController]]; break;
8417 case kManageTag: [self setPage:[self manageController]]; break;
8418 case kInstalledTag: [self setPage:[self installedController]]; break;
8419 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8420 case kSearchTag: [self setPage:[self searchController]]; break;
8428 - (void) showSettings {
8429 RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease];
8430 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8432 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8433 [container_ presentModalViewController:nav animated:YES];
8436 - (void) setPackageController:(PackageController *)view {
8438 [view setPackage:nil];
8442 - (PackageController *) _packageController {
8443 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8446 - (PackageController *) packageController {
8447 return [self _packageController];
8450 // Returns the navigation controller for the queuing badge.
8451 - (id) queueBadgeController {
8452 int index = [self indexOfTabWithTag:kManageTag];
8454 index = [self indexOfTabWithTag:kInstalledTag];
8456 return [[tabbar_ viewControllers] objectAtIndex:index];
8459 - (void) cancelAndClear:(bool)clear {
8460 @synchronized (self) {
8463 pkgCacheFile &cache([database_ cache]);
8464 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
8465 // Unmark method taken from Synaptic Package Manager.
8466 // Thanks for being sane, unlike Aptitude.
8467 if (!cache[iterator].Keep()) {
8468 cache->MarkKeep(iterator, false);
8469 cache->SetReInstall(iterator, false);
8475 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
8479 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8482 // Show the changes in the current view.
8483 [(CYNavigationController *) [tabbar_ selectedViewController] reloadData];
8484 [queueDelegate_ queueStatusDidChange];
8488 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8489 NSString *context([alert context]);
8491 if ([context isEqualToString:@"fixhalf"]) {
8492 if (button == [alert firstOtherButtonIndex]) {
8493 @synchronized (self) {
8494 for (Package *broken in broken_) {
8497 NSString *id = [broken id];
8498 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8499 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8500 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8501 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8507 } else if (button == [alert cancelButtonIndex]) {
8508 [broken_ removeAllObjects];
8512 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8513 } else if ([context isEqualToString:@"upgrade"]) {
8514 if (button == [alert firstOtherButtonIndex]) {
8515 @synchronized (self) {
8516 for (Package *essential in essential_)
8517 [essential install];
8522 } else if (button == [alert firstOtherButtonIndex] + 1) {
8524 } else if (button == [alert cancelButtonIndex]) {
8528 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8532 - (void) system:(NSString *)command { _pooled
8533 system([command UTF8String]);
8536 - (void) applicationWillSuspend {
8538 [super applicationWillSuspend];
8541 - (BOOL) hudIsShowing {
8545 - (void) applicationSuspend:(__GSEvent *)event {
8546 // Use external process status API internally.
8547 // This is probably a really bad idea.
8548 uint64_t status = 0;
8550 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8551 notify_get_state(notify_token, &status);
8552 notify_cancel(notify_token);
8555 if (![self hudIsShowing] && status == 0)
8556 [super applicationSuspend:event];
8559 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8560 if (![self hudIsShowing])
8561 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8564 - (void) _setSuspended:(BOOL)value {
8565 if (![self hudIsShowing])
8566 [super _setSuspended:value];
8569 - (UIProgressHUD *) addProgressHUD {
8570 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8571 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8573 [window_ setUserInteractionEnabled:NO];
8576 UIViewController *target = container_;
8577 while ([target modalViewController] != nil) target = [target modalViewController];
8578 [[target view] addSubview:hud];
8584 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8586 [hud removeFromSuperview];
8587 [window_ setUserInteractionEnabled:YES];
8591 - (CYViewController *) pageForPackage:(NSString *)name {
8592 if (Package *package = [database_ packageWithName:name]) {
8593 PackageController *view([self packageController]);
8594 [view setPackage:package];
8597 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8598 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8599 return [self _pageForURL:url withClass:[CYBrowserController class]];
8603 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8607 NSString *href([url absoluteString]);
8608 if ([href hasPrefix:@"apptapp://package/"])
8609 return [self pageForPackage:[href substringFromIndex:18]];
8611 NSString *scheme([[url scheme] lowercaseString]);
8612 if (![scheme isEqualToString:@"cydia"])
8614 NSString *path([url absoluteString]);
8615 if ([path length] < 8)
8617 path = [path substringFromIndex:8];
8618 if (![path hasPrefix:@"/"])
8619 path = [@"/" stringByAppendingString:path];
8621 if ([path isEqualToString:@"/add-source"])
8622 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8623 else if ([path isEqualToString:@"/storage"])
8624 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8625 else if ([path isEqualToString:@"/sources"])
8626 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8627 else if ([path isEqualToString:@"/packages"])
8628 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8629 else if ([path hasPrefix:@"/url/"])
8630 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8631 else if ([path hasPrefix:@"/launch/"])
8632 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8633 else if ([path hasPrefix:@"/package-settings/"])
8634 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8635 else if ([path hasPrefix:@"/package-signature/"])
8636 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8637 else if ([path hasPrefix:@"/package/"])
8638 return [self pageForPackage:[path substringFromIndex:9]];
8639 else if ([path hasPrefix:@"/files/"]) {
8640 NSString *name = [path substringFromIndex:7];
8642 if (Package *package = [database_ packageWithName:name]) {
8643 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8644 [files setPackage:package];
8652 - (void) applicationOpenURL:(NSURL *)url {
8653 [super applicationOpenURL:url];
8655 if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
8656 [self setPage:page];
8658 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8662 - (void) applicationWillResignActive:(UIApplication *)application {
8663 // Stop refreshing if you get a phone call or lock the device.
8664 if ([container_ updating])
8665 [container_ cancelUpdate];
8667 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8668 [super applicationWillResignActive:application];
8671 - (void) addStashController {
8672 stash_ = [[CYStashController alloc] init];
8673 [window_ addSubview:[stash_ view]];
8676 - (void) removeStashController {
8677 [[stash_ view] removeFromSuperview];
8682 [self setIdleTimerDisabled:YES];
8684 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8685 [self setStatusBarShowsProgress:YES];
8686 UpdateExternalStatus(1);
8688 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8690 UpdateExternalStatus(0);
8691 [self setStatusBarShowsProgress:NO];
8693 [self removeStashController];
8695 if (ExecFork() == 0) {
8696 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8697 perror("launchctl stop");
8701 - (void) setupTabBarController {
8702 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8703 [tabbar_ setDelegate:self];
8705 NSMutableArray *items([NSMutableArray arrayWithObjects:
8706 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8707 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8708 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8709 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8713 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8714 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8716 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8719 NSMutableArray *controllers([NSMutableArray array]);
8721 for (UITabBarItem *item in items) {
8722 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8723 [controller setTabBarItem:item];
8724 [controllers addObject:controller];
8727 [tabbar_ setViewControllers:controllers];
8730 - (void) applicationDidFinishLaunching:(id)unused {
8731 [CYBrowserController _initialize];
8733 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8735 Font12_ = [[UIFont systemFontOfSize:12] retain];
8736 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8737 Font14_ = [[UIFont systemFontOfSize:14] retain];
8738 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8739 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8743 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8744 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8746 UIScreen *screen([UIScreen mainScreen]);
8748 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8749 [window_ orderFront:self];
8750 [window_ makeKey:self];
8751 [window_ setHidden:NO];
8754 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8755 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8756 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8757 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8758 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8759 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8760 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8761 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8762 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8765 [self addStashController];
8766 // XXX: this would be much cleaner as a yieldToSelector:
8767 // that way the removeStashController could happen right here inline
8768 // we also could no longer require the useless stash_ field anymore
8769 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8773 database_ = [Database sharedInstance];
8775 [self setupTabBarController];
8777 container_ = [[CYContainer alloc] initWithDatabase:database_];
8778 [container_ setUpdateDelegate:self];
8779 [container_ setTabBarController:tabbar_];
8780 [window_ addSubview:[container_ view]];
8782 // Show pinstripes while loading data.
8783 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8785 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8792 [self showSettings];
8796 [window_ setUserInteractionEnabled:NO];
8798 UIView *container = [[[UIView alloc] init] autorelease];
8799 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8801 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
8802 [spinner startAnimating];
8803 [container addSubview:spinner];
8805 UILabel *label = [[[UILabel alloc] init] autorelease];
8806 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8807 [label setBackgroundColor:[UIColor clearColor]];
8808 [label setTextColor:[UIColor blackColor]];
8809 [label setShadowColor:[UIColor whiteColor]];
8810 [label setShadowOffset:CGSizeMake(0, 1)];
8811 [label setText:UCLocalize("LOADING_DATA")];
8812 [container addSubview:label];
8814 CGSize viewsize = [[tabbar_ view] frame].size;
8815 CGSize spinnersize = [spinner bounds].size;
8816 CGSize textsize = [[label text] sizeWithFont:[label font]];
8817 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8819 CGRect containrect = {
8820 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8821 CGSizeMake(bothwidth, spinnersize.height)
8824 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8832 [container setFrame:containrect];
8833 [spinner setFrame:spinrect];
8834 [label setFrame:textrect];
8835 [[container_ view] addSubview:container];
8840 // Show the home page
8841 [tabbar_ setSelectedIndex:0];
8843 [window_ setUserInteractionEnabled:YES];
8845 // XXX: does this actually slow anything down?
8846 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8847 [container removeFromSuperview];
8850 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8851 if (item != nil && IsWildcat_) {
8852 [sheet showFromBarButtonItem:item animated:YES];
8854 [sheet showInView:window_];
8861 id Alloc_(id self, SEL selector) {
8862 id object = alloc_(self, selector);
8863 lprintf("[%s]A-%p\n", self->isa->name, object);
8868 id Dealloc_(id self, SEL selector) {
8869 id object = dealloc_(self, selector);
8870 lprintf("[%s]D-%p\n", self->isa->name, object);
8874 Class $WebDefaultUIKitDelegate;
8876 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8877 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8878 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8879 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8882 static NSNumber *shouldPlayKeyboardSounds;
8886 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8888 case 1104: // Keyboard Button Clicked
8889 case 1105: // Keyboard Delete Repeated
8890 if (shouldPlayKeyboardSounds == nil) {
8891 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8892 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8895 if (![shouldPlayKeyboardSounds boolValue])
8899 _UIHardware$_playSystemSound$(self, _cmd, sound);
8903 int main(int argc, char *argv[]) { _pooled
8906 if (Class $UIDevice = objc_getClass("UIDevice")) {
8907 UIDevice *device([$UIDevice currentDevice]);
8908 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8912 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8914 /* Library Hacks {{{ */
8915 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8917 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8918 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8919 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8920 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8921 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8924 $UIHardware = objc_getClass("UIHardware");
8925 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8926 if (UIHardware$_playSystemSound$ != NULL) {
8927 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8928 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8931 /* Set Locale {{{ */
8932 Locale_ = CFLocaleCopyCurrent();
8933 Languages_ = [NSLocale preferredLanguages];
8934 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8935 //NSLog(@"%@", [Languages_ description]);
8938 if (Languages_ == nil || [Languages_ count] == 0)
8939 // XXX: consider just setting to C and then falling through?
8942 lang = [[Languages_ objectAtIndex:0] UTF8String];
8943 setenv("LANG", lang, true);
8946 //std::setlocale(LC_ALL, lang);
8947 NSLog(@"Setting Language: %s", lang);
8950 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8952 /* Parse Arguments {{{ */
8953 bool substrate(false);
8959 for (int argi(1); argi != argc; ++argi)
8960 if (strcmp(argv[argi], "--") == 0) {
8962 argv[argi] = argv[0];
8968 for (int argi(1); argi != arge; ++argi)
8969 if (strcmp(args[argi], "--substrate") == 0)
8972 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8976 App_ = [[NSBundle mainBundle] bundlePath];
8977 Home_ = NSHomeDirectory();
8983 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8984 alloc_ = alloc->method_imp;
8985 alloc->method_imp = (IMP) &Alloc_;*/
8987 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8988 dealloc_ = dealloc->method_imp;
8989 dealloc->method_imp = (IMP) &Dealloc_;*/
8991 /* System Information {{{ */
8995 size = sizeof(maxproc);
8996 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8997 perror("sysctlbyname(\"kern.maxproc\", ?)");
8998 else if (maxproc < 64) {
9000 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9001 perror("sysctlbyname(\"kern.maxproc\", #)");
9004 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9005 char *osversion = new char[size];
9006 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9007 perror("sysctlbyname(\"kern.osversion\", ?)");
9009 System_ = [NSString stringWithUTF8String:osversion];
9011 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9012 char *machine = new char[size];
9013 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9014 perror("sysctlbyname(\"hw.machine\", ?)");
9018 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9019 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9020 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9021 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9025 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9026 NSData *data((NSData *) ecid);
9027 size_t length([data length]);
9028 uint8_t bytes[length];
9029 [data getBytes:bytes];
9030 char string[length * 2 + 1];
9031 for (size_t i(0); i != length; ++i)
9032 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9033 ChipID_ = [NSString stringWithUTF8String:string];
9037 IOObjectRelease(service);
9041 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9043 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9044 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9045 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9047 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9048 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9049 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9051 if (mcc != NULL && mnc != NULL)
9052 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9059 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9060 Build_ = [system objectForKey:@"ProductBuildVersion"];
9061 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9062 Product_ = [info objectForKey:@"SafariProductVersion"];
9063 Safari_ = [info objectForKey:@"CFBundleVersion"];
9066 /* Load Database {{{ */
9068 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9070 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9072 if (Metadata_ == NULL)
9073 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9075 Settings_ = [Metadata_ objectForKey:@"Settings"];
9077 Packages_ = [Metadata_ objectForKey:@"Packages"];
9078 Sections_ = [Metadata_ objectForKey:@"Sections"];
9079 Sources_ = [Metadata_ objectForKey:@"Sources"];
9081 Token_ = [Metadata_ objectForKey:@"Token"];
9084 if (Settings_ != nil)
9085 Role_ = [Settings_ objectForKey:@"Role"];
9087 if (Packages_ == nil) {
9088 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
9089 [Metadata_ setObject:Packages_ forKey:@"Packages"];
9092 if (Sections_ == nil) {
9093 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9094 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9097 if (Sources_ == nil) {
9098 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9099 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9103 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9105 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9106 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9107 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9108 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9109 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9110 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9112 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9114 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9115 unlink("/tmp/.cydia.fw");
9117 } else if (access("/User", F_OK) != 0 || version < 2) {
9120 system("/usr/libexec/cydia/firmware.sh");
9124 _assert([[NSFileManager defaultManager]
9125 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9126 withIntermediateDirectories:YES
9131 if (access("/tmp/cydia.chk", F_OK) == 0) {
9132 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9133 _assert(errno == ENOENT);
9134 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9135 _assert(errno == ENOENT);
9138 /* APT Initialization {{{ */
9139 _assert(pkgInitConfig(*_config));
9140 _assert(pkgInitSystem(*_config, _system));
9143 _config->Set("APT::Acquire::Translation", lang);
9145 // XXX: this timeout might be important :(
9146 //_config->Set("Acquire::http::Timeout", 15);
9148 _config->Set("Acquire::http::MaxParallel", 3);
9150 /* Color Choices {{{ */
9151 space_ = CGColorSpaceCreateDeviceRGB();
9153 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9154 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9155 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9156 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9157 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9158 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9159 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9160 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9161 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9163 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9164 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9166 /* UIKit Configuration {{{ */
9167 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9168 if ($GSFontSetUseLegacyFontMetrics != NULL)
9169 $GSFontSetUseLegacyFontMetrics(YES);
9171 // XXX: I have a feeling this was important
9172 //UIKeyboardDisableAutomaticAppearance();
9175 Colon_ = UCLocalize("COLON_DELIMITED");
9176 Error_ = UCLocalize("ERROR");
9177 Warning_ = UCLocalize("WARNING");
9180 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9182 CGColorSpaceRelease(space_);