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 (0 && !ForRelease)
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) radixSortUsingSelector:(SEL)selector withObject:(id)object;
415 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
423 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
424 struct RadixItem_ *lhs(swap), *rhs(swap + count);
426 static const size_t width = 32;
427 static const size_t bits = 11;
428 static const size_t slots = 1 << bits;
429 static const size_t passes = (width + (bits - 1)) / bits;
431 size_t *hist(new size_t[slots]);
433 for (size_t pass(0); pass != passes; ++pass) {
434 memset(hist, 0, sizeof(size_t) * slots);
436 for (size_t i(0); i != count; ++i) {
437 uint32_t key(lhs[i].key);
439 key &= _not(uint32_t) >> width - bits;
444 for (size_t i(0); i != slots; ++i) {
445 size_t local(offset);
450 for (size_t i(0); i != count; ++i) {
451 uint32_t key(lhs[i].key);
453 key &= _not(uint32_t) >> width - bits;
454 rhs[hist[key]++] = lhs[i];
457 RadixItem_ *tmp(lhs);
464 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
465 for (size_t i(0); i != count; ++i)
466 [values addObject:[self objectAtIndex:lhs[i].index]];
467 [self setArray:values];
472 @implementation NSMutableArray (Radix)
474 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
475 size_t count([self count]);
480 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
481 [invocation setSelector:selector];
482 [invocation setArgument:&object atIndex:2];
484 /* XXX: this is an unsafe optimization of doomy hell */
485 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
486 _assert(method != NULL);
487 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
488 _assert(imp != NULL);
491 struct RadixItem_ *swap(new RadixItem_[count * 2]);
493 for (size_t i(0); i != count; ++i) {
494 RadixItem_ &item(swap[i]);
497 id object([self objectAtIndex:i]);
500 [invocation setTarget:object];
502 [invocation getReturnValue:&item.key];
504 item.key = imp(object, selector, object);
508 RadixSort_(self, count, swap);
511 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
512 size_t count([self count]);
513 struct RadixItem_ *swap(new RadixItem_[count * 2]);
515 for (size_t i(0); i != count; ++i) {
516 RadixItem_ &item(swap[i]);
519 id object([self objectAtIndex:i]);
520 item.key = function(object, argument);
523 RadixSort_(self, count, swap);
528 /* Insertion Sort {{{ */
530 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
531 const char *ptr = (const char *)list;
533 CFIndex half = count / 2;
534 const char *probe = ptr + elementSize * half;
535 CFComparisonResult cr = comparator(element, probe, context);
536 if (0 == cr) return (probe - (const char *)list) / elementSize;
537 ptr = (cr < 0) ? ptr : probe + elementSize;
538 count = (cr < 0) ? half : (half + (count & 1) - 1);
540 return (ptr - (const char *)list) / elementSize;
543 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
544 const char *ptr = (const char *)list;
546 CFIndex half = count / 2;
547 const char *probe = ptr + elementSize * half;
548 CFComparisonResult cr = comparator(element, probe, context);
549 if (0 == cr) return (probe - (const char *)list) / elementSize;
550 ptr = (cr < 0) ? ptr : probe + elementSize;
551 count = (cr < 0) ? half : (half + (count & 1) - 1);
553 return (ptr - (const char *)list) / elementSize;
556 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
557 if (range.length == 0)
559 const void **values(new const void *[range.length]);
560 CFArrayGetValues(array, range, values);
562 #if HistogramInsertionSort
563 uint32_t total(0), *offsets(new uint32_t[range.length]);
566 for (CFIndex index(1); index != range.length; ++index) {
567 const void *value(values[index]);
568 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
569 CFIndex correct(index);
570 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
573 if (correct != index) {
574 size_t offset(index - correct);
575 #if HistogramInsertionSort
579 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
581 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
582 values[correct] = value;
586 CFArrayReplaceValues(array, range, values, range.length);
589 #if HistogramInsertionSort
590 for (CFIndex index(0); index != range.length; ++index)
591 if (offsets[index] != 0)
592 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
593 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
600 /* Apple Bug Fixes {{{ */
601 @implementation UIWebDocumentView (Cydia)
603 - (void) _setScrollerOffset:(CGPoint)offset {
604 UIScroller *scroller([self _scroller]);
606 CGSize size([scroller contentSize]);
607 CGSize bounds([scroller bounds].size);
610 max.x = size.width - bounds.width;
611 max.y = size.height - bounds.height;
619 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
620 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
622 [scroller setOffset:offset];
628 @implementation WebScriptObject (NSFastEnumeration)
630 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
631 size_t length([self count] - state->state);
634 else if (length > count)
636 for (size_t i(0); i != length; ++i)
637 objects[i] = [self objectAtIndex:state->state++];
638 state->itemsPtr = objects;
639 state->mutationsPtr = (unsigned long *) self;
645 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
646 size_t length([self length] - state->state);
649 else if (length > count)
651 for (size_t i(0); i != length; ++i)
652 objects[i] = [self item:state->state++];
653 state->itemsPtr = objects;
654 state->mutationsPtr = (unsigned long *) self;
658 /* Cydia NSString Additions {{{ */
659 @interface NSString (Cydia)
660 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
661 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
662 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
663 - (NSComparisonResult) compareByPath:(NSString *)other;
664 - (NSString *) stringByCachingURLWithCurrentCDN;
665 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
668 @implementation NSString (Cydia)
670 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
671 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
674 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
675 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
676 memcpy(data, bytes, length);
677 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
680 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
681 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
684 - (NSComparisonResult) compareByPath:(NSString *)other {
685 NSString *prefix = [self commonPrefixWithString:other options:0];
686 size_t length = [prefix length];
688 NSRange lrange = NSMakeRange(length, [self length] - length);
689 NSRange rrange = NSMakeRange(length, [other length] - length);
691 lrange = [self rangeOfString:@"/" options:0 range:lrange];
692 rrange = [other rangeOfString:@"/" options:0 range:rrange];
694 NSComparisonResult value;
696 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
697 value = NSOrderedSame;
698 else if (lrange.location == NSNotFound)
699 value = NSOrderedAscending;
700 else if (rrange.location == NSNotFound)
701 value = NSOrderedDescending;
703 value = NSOrderedSame;
705 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
706 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
707 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
708 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
710 NSComparisonResult result = [lpath compare:rpath];
711 return result == NSOrderedSame ? value : result;
714 - (NSString *) stringByCachingURLWithCurrentCDN {
716 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
717 withString:@"://cache.cydia.saurik.com/"
721 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
722 return [(id)CFURLCreateStringByAddingPercentEscapes(
727 kCFStringEncodingUTF8
734 /* C++ NSString Wrapper Cache {{{ */
741 _finline void clear_() {
742 if (cache_ != NULL) {
749 _finline bool empty() const {
753 _finline size_t size() const {
757 _finline char *data() const {
761 _finline void clear() {
766 _finline CYString() :
773 _finline ~CYString() {
777 void operator =(const CYString &rhs) {
781 if (rhs.cache_ == nil)
784 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
787 void set(apr_pool_t *pool, const char *data, size_t size) {
793 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
794 memcpy(temp, data, size);
801 _finline void set(apr_pool_t *pool, const char *data) {
802 set(pool, data, data == NULL ? 0 : strlen(data));
805 _finline void set(apr_pool_t *pool, const std::string &rhs) {
806 set(pool, rhs.data(), rhs.size());
809 bool operator ==(const CYString &rhs) const {
810 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
813 operator CFStringRef() {
814 if (cache_ == NULL) {
817 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
819 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
823 _finline operator id() {
824 return (NSString *) static_cast<CFStringRef>(*this);
828 /* C++ NSString Algorithm Adapters {{{ */
830 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
833 struct NSStringMapHash :
834 std::unary_function<NSString *, size_t>
836 _finline size_t operator ()(NSString *value) const {
837 return CFStringHashNSString((CFStringRef) value);
841 struct NSStringMapLess :
842 std::binary_function<NSString *, NSString *, bool>
844 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
845 return [lhs compare:rhs] == NSOrderedAscending;
849 struct NSStringMapEqual :
850 std::binary_function<NSString *, NSString *, bool>
852 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
853 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
854 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
855 //[lhs isEqualToString:rhs];
860 /* Perl-Compatible RegEx {{{ */
870 Pcre(const char *regex) :
875 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
878 lprintf("%d:%s\n", offset, error);
882 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
883 matches_ = new int[(capture_ + 1) * 3];
891 NSString *operator [](size_t match) {
892 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
895 bool operator ()(NSString *data) {
896 // XXX: length is for characters, not for bytes
897 return operator ()([data UTF8String], [data length]);
900 bool operator ()(const char *data, size_t size) {
902 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
906 /* Mime Addresses {{{ */
907 @interface Address : NSObject {
913 - (NSString *) address;
915 - (void) setAddress:(NSString *)address;
917 + (Address *) addressWithString:(NSString *)string;
918 - (Address *) initWithString:(NSString *)string;
921 @implementation Address
930 - (NSString *) name {
934 - (NSString *) address {
938 - (void) setAddress:(NSString *)address {
940 [address_ autorelease];
944 address_ = [address retain];
947 + (Address *) addressWithString:(NSString *)string {
948 return [[[Address alloc] initWithString:string] autorelease];
951 + (NSArray *) _attributeKeys {
952 return [NSArray arrayWithObjects:@"address", @"name", nil];
955 - (NSArray *) attributeKeys {
956 return [[self class] _attributeKeys];
959 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
960 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
963 - (Address *) initWithString:(NSString *)string {
964 if ((self = [super init]) != nil) {
965 const char *data = [string UTF8String];
966 size_t size = [string length];
968 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
970 if (address_r(data, size)) {
971 name_ = [address_r[1] retain];
972 address_ = [address_r[2] retain];
974 name_ = [string retain];
982 /* CoreGraphics Primitives {{{ */
993 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
996 Set(space, red, green, blue, alpha);
1001 CGColorRelease(color_);
1008 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1010 float color[] = {red, green, blue, alpha};
1011 color_ = CGColorCreate(space, (CGFloat *) color);
1014 operator CGColorRef() {
1020 /* Random Global Variables {{{ */
1021 static const int PulseInterval_ = 50000;
1022 static const int ButtonBarWidth_ = 60;
1023 static const int ButtonBarHeight_ = 48;
1024 static const float KeyboardTime_ = 0.3f;
1027 static NSArray *Finishes_;
1029 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1030 #define NotifyConfig_ "/etc/notify.conf"
1032 static bool Queuing_;
1034 static CYColor Blue_;
1035 static CYColor Blueish_;
1036 static CYColor Black_;
1037 static CYColor Off_;
1038 static CYColor White_;
1039 static CYColor Gray_;
1040 static CYColor Green_;
1041 static CYColor Purple_;
1042 static CYColor Purplish_;
1044 static UIColor *InstallingColor_;
1045 static UIColor *RemovingColor_;
1047 static NSString *App_;
1048 static NSString *Home_;
1050 static BOOL Advanced_;
1051 static BOOL Ignored_;
1053 static UIFont *Font12_;
1054 static UIFont *Font12Bold_;
1055 static UIFont *Font14_;
1056 static UIFont *Font18Bold_;
1057 static UIFont *Font22Bold_;
1059 static const char *Machine_ = NULL;
1060 static NSString *System_ = nil;
1061 static NSString *SerialNumber_ = nil;
1062 static NSString *ChipID_ = nil;
1063 static NSString *Token_ = nil;
1064 static NSString *UniqueID_ = nil;
1065 static NSString *PLMN_ = nil;
1066 static NSString *Build_ = nil;
1067 static NSString *Product_ = nil;
1068 static NSString *Safari_ = nil;
1070 static CFLocaleRef Locale_;
1071 static NSArray *Languages_;
1072 static CGColorSpaceRef space_;
1074 static NSDictionary *SectionMap_;
1075 static NSMutableDictionary *Metadata_;
1076 static _transient NSMutableDictionary *Settings_;
1077 static _transient NSString *Role_;
1078 static _transient NSMutableDictionary *Packages_;
1079 static _transient NSMutableDictionary *Sections_;
1080 static _transient NSMutableDictionary *Sources_;
1081 static bool Changed_;
1082 static NSDate *now_;
1084 static bool IsWildcat_;
1087 /* Display Helpers {{{ */
1088 inline float Interpolate(float begin, float end, float fraction) {
1089 return (end - begin) * fraction + begin;
1092 /* XXX: localize this! */
1093 NSString *SizeString(double size) {
1094 bool negative = size < 0;
1099 while (size > 1024) {
1104 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1106 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1109 static _finline CFStringRef CFCString(const char *value) {
1110 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1113 const char *StripVersion_(const char *version) {
1114 const char *colon(strchr(version, ':'));
1116 version = colon + 1;
1120 CFStringRef StripVersion(const char *version) {
1121 const char *colon(strchr(version, ':'));
1123 version = colon + 1;
1124 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1126 return CFCString(version);
1129 NSString *LocalizeSection(NSString *section) {
1130 static Pcre title_r("^(.*?) \\((.*)\\)$");
1131 if (title_r(section)) {
1132 NSString *parent(title_r[1]);
1133 NSString *child(title_r[2]);
1135 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1136 LocalizeSection(parent),
1137 LocalizeSection(child)
1141 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1144 NSString *Simplify(NSString *title) {
1145 const char *data = [title UTF8String];
1146 size_t size = [title length];
1148 static Pcre square_r("^\\[(.*)\\]$");
1149 if (square_r(data, size))
1150 return Simplify(square_r[1]);
1152 static Pcre paren_r("^\\((.*)\\)$");
1153 if (paren_r(data, size))
1154 return Simplify(paren_r[1]);
1156 static Pcre title_r("^(.*?) \\((.*)\\)$");
1157 if (title_r(data, size))
1158 return Simplify(title_r[1]);
1164 NSString *GetLastUpdate() {
1165 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1168 return UCLocalize("NEVER_OR_UNKNOWN");
1170 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1171 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1173 CFRelease(formatter);
1175 return [(NSString *) formatted autorelease];
1178 bool isSectionVisible(NSString *section) {
1179 NSDictionary *metadata([Sections_ objectForKey:section]);
1180 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1181 return hidden == nil || ![hidden boolValue];
1186 /* Delegate Prototypes {{{ */
1190 @interface NSObject (ProgressDelegate)
1193 @protocol ProgressDelegate
1194 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1195 - (void) setProgressTitle:(NSString *)title;
1196 - (void) setProgressPercent:(float)percent;
1197 - (void) startProgress;
1198 - (void) addProgressOutput:(NSString *)output;
1199 - (bool) isCancelling:(size_t)received;
1202 @protocol ConfigurationDelegate
1203 - (void) repairWithSelector:(SEL)selector;
1204 - (void) setConfigurationData:(NSString *)data;
1207 @class PackageController;
1209 @protocol CydiaDelegate
1210 - (void) setPackageController:(PackageController *)view;
1211 - (void) clearPackage:(Package *)package;
1212 - (void) installPackage:(Package *)package;
1213 - (void) installPackages:(NSArray *)packages;
1214 - (void) removePackage:(Package *)package;
1215 - (void) beginUpdate;
1217 - (void) distUpgrade;
1219 - (void) updateData;
1221 - (void) showSettings;
1222 - (UIProgressHUD *) addProgressHUD;
1223 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1224 - (CYViewController *) pageForPackage:(NSString *)name;
1225 - (PackageController *) packageController;
1226 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1230 /* Status Delegation {{{ */
1232 public pkgAcquireStatus
1235 _transient NSObject<ProgressDelegate> *delegate_;
1243 void setDelegate(id delegate) {
1244 delegate_ = delegate;
1247 NSObject<ProgressDelegate> *getDelegate() const {
1251 virtual bool MediaChange(std::string media, std::string drive) {
1255 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1258 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1259 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1260 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1263 virtual void Done(pkgAcquire::ItemDesc &item) {
1266 virtual void Fail(pkgAcquire::ItemDesc &item) {
1268 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1269 item.Owner->Status == pkgAcquire::Item::StatDone
1273 std::string &error(item.Owner->ErrorText);
1277 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1278 NSArray *fields([description componentsSeparatedByString:@" "]);
1279 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1281 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1282 withObject:[NSArray arrayWithObjects:
1283 [NSString stringWithUTF8String:error.c_str()],
1290 virtual bool Pulse(pkgAcquire *Owner) {
1291 bool value = pkgAcquireStatus::Pulse(Owner);
1294 double(CurrentBytes + CurrentItems) /
1295 double(TotalBytes + TotalItems)
1298 [delegate_ setProgressPercent:percent];
1299 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1302 virtual void Start() {
1303 [delegate_ startProgress];
1306 virtual void Stop() {
1310 /* Progress Delegation {{{ */
1315 _transient id<ProgressDelegate> delegate_;
1319 virtual void Update() {
1320 /*if (abs(Percent - percent_) > 2)
1321 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1325 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1326 [delegate_ setProgressPercent:(Percent / 100)];*/
1336 void setDelegate(id delegate) {
1337 delegate_ = delegate;
1340 id getDelegate() const {
1344 virtual void Done() {
1346 //[delegate_ setProgressPercent:1];
1351 /* Database Interface {{{ */
1352 typedef std::map< unsigned long, _H<Source> > SourceMap;
1354 @interface Database : NSObject {
1360 pkgCacheFile cache_;
1361 pkgDepCache::Policy *policy_;
1362 pkgRecords *records_;
1363 pkgProblemResolver *resolver_;
1364 pkgAcquire *fetcher_;
1366 SPtr<pkgPackageManager> manager_;
1367 pkgSourceList *list_;
1370 NSMutableArray *packages_;
1372 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1381 + (Database *) sharedInstance;
1384 - (void) _readCydia:(NSNumber *)fd;
1385 - (void) _readStatus:(NSNumber *)fd;
1386 - (void) _readOutput:(NSNumber *)fd;
1390 - (Package *) packageWithName:(NSString *)name;
1392 - (pkgCacheFile &) cache;
1393 - (pkgDepCache::Policy *) policy;
1394 - (pkgRecords *) records;
1395 - (pkgProblemResolver *) resolver;
1396 - (pkgAcquire &) fetcher;
1397 - (pkgSourceList &) list;
1398 - (NSArray *) packages;
1399 - (NSArray *) sources;
1400 - (void) reloadData;
1408 - (void) setVisible;
1410 - (void) updateWithStatus:(Status &)status;
1412 - (void) setDelegate:(id)delegate;
1413 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1416 /* Delegate Helpers {{{ */
1417 @implementation NSObject (ProgressDelegate)
1419 - (void) _setProgressErrorPackage:(NSArray *)args {
1420 [self performSelector:@selector(setProgressError:forPackage:)
1421 withObject:[args objectAtIndex:0]
1422 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1426 - (void) _setProgressErrorTitle:(NSArray *)args {
1427 [self performSelector:@selector(setProgressError:withTitle:)
1428 withObject:[args objectAtIndex:0]
1429 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1433 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1434 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1435 withObject:[NSArray arrayWithObjects:error, title, nil]
1440 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1441 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1443 [self performSelector:@selector(setProgressError:withTitle:)
1445 withObject:(package == nil ? id : [package name])
1452 /* Source Class {{{ */
1453 @interface Source : NSObject {
1454 CYString depiction_;
1455 CYString description_;
1461 CYString distribution_;
1466 NSString *authority_;
1468 CYString defaultIcon_;
1470 NSDictionary *record_;
1474 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1476 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1478 - (NSString *) depictionForPackage:(NSString *)package;
1479 - (NSString *) supportForPackage:(NSString *)package;
1481 - (NSDictionary *) record;
1485 - (NSString *) distribution;
1486 - (NSString *) type;
1488 - (NSString *) host;
1490 - (NSString *) name;
1491 - (NSString *) description;
1492 - (NSString *) label;
1493 - (NSString *) origin;
1494 - (NSString *) version;
1496 - (NSString *) defaultIcon;
1500 @implementation Source
1504 distribution_.clear();
1507 description_.clear();
1513 defaultIcon_.clear();
1515 if (record_ != nil) {
1525 if (authority_ != nil) {
1526 [authority_ release];
1536 + (NSArray *) _attributeKeys {
1537 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1540 - (NSArray *) attributeKeys {
1541 return [[self class] _attributeKeys];
1544 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1545 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1548 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1551 trusted_ = index->IsTrusted();
1553 uri_.set(pool, index->GetURI());
1554 distribution_.set(pool, index->GetDist());
1555 type_.set(pool, index->GetType());
1557 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1558 if (dindex != NULL) {
1560 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1563 pkgTagFile tags(&fd);
1565 pkgTagSection section;
1572 {"default-icon", &defaultIcon_},
1573 {"depiction", &depiction_},
1574 {"description", &description_},
1576 {"origin", &origin_},
1577 {"support", &support_},
1578 {"version", &version_},
1581 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1582 const char *start, *end;
1584 if (section.Find(names[i].name_, start, end)) {
1585 CYString &value(*names[i].value_);
1586 value.set(pool, start, end - start);
1592 record_ = [Sources_ objectForKey:[self key]];
1594 record_ = [record_ retain];
1596 NSURL *url([NSURL URLWithString:uri_]);
1600 host_ = [[host_ lowercaseString] retain];
1605 authority_ = [url path];
1607 if (authority_ != nil)
1608 authority_ = [authority_ retain];
1611 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1612 if ((self = [super init]) != nil) {
1613 [self setMetaIndex:index inPool:pool];
1617 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1618 NSDictionary *lhr = [self record];
1619 NSDictionary *rhr = [source record];
1622 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1624 NSString *lhs = [self name];
1625 NSString *rhs = [source name];
1627 if ([lhs length] != 0 && [rhs length] != 0) {
1628 unichar lhc = [lhs characterAtIndex:0];
1629 unichar rhc = [rhs characterAtIndex:0];
1631 if (isalpha(lhc) && !isalpha(rhc))
1632 return NSOrderedAscending;
1633 else if (!isalpha(lhc) && isalpha(rhc))
1634 return NSOrderedDescending;
1637 return [lhs compare:rhs options:LaxCompareOptions_];
1640 - (NSString *) depictionForPackage:(NSString *)package {
1641 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1644 - (NSString *) supportForPackage:(NSString *)package {
1645 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1648 - (NSDictionary *) record {
1656 - (NSString *) uri {
1660 - (NSString *) distribution {
1661 return distribution_;
1664 - (NSString *) type {
1668 - (NSString *) key {
1669 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1672 - (NSString *) host {
1676 - (NSString *) name {
1677 return origin_.empty() ? authority_ : origin_;
1680 - (NSString *) description {
1681 return description_;
1684 - (NSString *) label {
1685 return label_.empty() ? authority_ : label_;
1688 - (NSString *) origin {
1692 - (NSString *) version {
1696 - (NSString *) defaultIcon {
1697 return defaultIcon_;
1702 /* Relationship Class {{{ */
1703 @interface Relationship : NSObject {
1708 - (NSString *) type;
1710 - (NSString *) name;
1714 @implementation Relationship
1722 - (NSString *) type {
1730 - (NSString *) name {
1737 /* Package Class {{{ */
1738 @interface Package : NSObject {
1742 pkgCache::VerIterator version_;
1743 pkgCache::PkgIterator iterator_;
1744 _transient Database *database_;
1745 pkgCache::VerFileIterator file_;
1752 NSString *section$_;
1759 CYString installed_;
1765 CYString depiction_;
1776 NSMutableArray *tags_;
1779 NSArray *relationships_;
1781 NSMutableDictionary *metadata_;
1782 _transient NSDate *firstSeen_;
1783 _transient NSDate *lastSeen_;
1787 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1788 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1790 - (pkgCache::PkgIterator) iterator;
1793 - (NSString *) section;
1794 - (NSString *) simpleSection;
1796 - (NSString *) longSection;
1797 - (NSString *) shortSection;
1801 - (Address *) maintainer;
1803 - (NSString *) longDescription;
1804 - (NSString *) shortDescription;
1807 - (NSMutableDictionary *) metadata;
1809 - (BOOL) subscribed;
1812 - (NSString *) latest;
1813 - (NSString *) installed;
1814 - (BOOL) uninstalled;
1817 - (BOOL) upgradableAndEssential:(BOOL)essential;
1820 - (BOOL) unfiltered;
1824 - (BOOL) halfConfigured;
1825 - (BOOL) halfInstalled;
1827 - (NSString *) mode;
1829 - (void) setVisible;
1832 - (NSString *) name;
1834 - (NSString *) homepage;
1835 - (NSString *) depiction;
1836 - (Address *) author;
1838 - (NSString *) support;
1840 - (NSArray *) files;
1841 - (NSArray *) relationships;
1842 - (NSArray *) warnings;
1843 - (NSArray *) applications;
1845 - (Source *) source;
1846 - (NSString *) role;
1848 - (BOOL) matches:(NSString *)text;
1850 - (bool) hasSupportingRole;
1851 - (BOOL) hasTag:(NSString *)tag;
1852 - (NSString *) primaryPurpose;
1853 - (NSArray *) purposes;
1854 - (bool) isCommercial;
1856 - (CYString &) cyname;
1858 - (uint32_t) compareBySection:(NSArray *)sections;
1860 - (uint32_t) compareForChanges;
1865 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1866 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1867 - (bool) isInstalledAndVisible:(NSNumber *)number;
1868 - (bool) isVisibleInSection:(NSString *)section;
1869 - (bool) isVisibleInSource:(Source *)source;
1873 uint32_t PackageChangesRadix(Package *self, void *) {
1878 uint32_t timestamp : 30;
1879 uint32_t ignored : 1;
1880 uint32_t upgradable : 1;
1884 bool upgradable([self upgradableAndEssential:YES]);
1885 value.bits.upgradable = upgradable ? 1 : 0;
1888 value.bits.timestamp = 0;
1889 value.bits.ignored = [self ignored] ? 0 : 1;
1890 value.bits.upgradable = 1;
1892 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1893 value.bits.ignored = 0;
1894 value.bits.upgradable = 0;
1897 return _not(uint32_t) - value.key;
1900 _finline static void Stifle(uint8_t &value) {
1903 uint32_t PackagePrefixRadix(Package *self, void *context) {
1904 size_t offset(reinterpret_cast<size_t>(context));
1905 CYString &name([self cyname]);
1907 size_t size(name.size());
1910 char *text(name.data());
1913 if (!isdigit(text[0]))
1917 while (size != digits && isdigit(text[digits]))
1927 if (offset == 0 && zeros != 0) {
1928 memset(data, '0', zeros);
1929 memcpy(data + zeros, text, 4 - zeros);
1931 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1932 if (size <= offset - zeros)
1935 text += offset - zeros;
1936 size -= offset - zeros;
1939 memcpy(data, text, 4);
1941 memcpy(data, text, size);
1942 memset(data + size, 0, 4 - size);
1945 for (size_t i(0); i != 4; ++i)
1946 if (isalpha(data[i]))
1951 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1953 /* XXX: ntohl may be more honest */
1954 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1957 CYString &(*PackageName)(Package *self, SEL sel);
1959 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1960 _profile(PackageNameCompare)
1961 CYString &lhi(PackageName(lhs, @selector(cyname)));
1962 CYString &rhi(PackageName(rhs, @selector(cyname)));
1963 CFStringRef lhn(lhi), rhn(rhi);
1966 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1967 else if (rhn == NULL)
1968 return NSOrderedDescending;
1970 _profile(PackageNameCompare$NumbersLast)
1971 if (!lhi.empty() && !rhi.empty()) {
1972 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1973 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1974 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1975 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1976 return lha ? NSOrderedAscending : NSOrderedDescending;
1980 CFIndex length = CFStringGetLength(lhn);
1982 _profile(PackageNameCompare$Compare)
1983 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1988 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1989 return PackageNameCompare(*lhs, *rhs, context);
1992 struct PackageNameOrdering :
1993 std::binary_function<Package *, Package *, bool>
1995 _finline bool operator ()(Package *lhs, Package *rhs) const {
1996 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2000 @implementation Package
2002 - (NSString *) description {
2003 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2009 if (section$_ != nil)
2010 [section$_ release];
2015 if (sponsor$_ != nil)
2016 [sponsor$_ release];
2017 if (author$_ != nil)
2024 if (relationships_ != nil)
2025 [relationships_ release];
2026 if (metadata_ != nil)
2027 [metadata_ release];
2032 + (NSString *) webScriptNameForSelector:(SEL)selector {
2033 if (selector == @selector(hasTag:))
2039 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2040 return [self webScriptNameForSelector:selector] == nil;
2043 + (NSArray *) _attributeKeys {
2044 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];
2047 - (NSArray *) attributeKeys {
2048 return [[self class] _attributeKeys];
2051 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2052 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2062 _profile(Package$parse)
2063 pkgRecords::Parser *parser;
2065 _profile(Package$parse$Lookup)
2066 parser = &[database_ records]->Lookup(file_);
2071 _profile(Package$parse$Find)
2077 {"depiction", &depiction_},
2078 {"homepage", &homepage_},
2079 {"website", &website},
2081 {"support", &support_},
2082 {"sponsor", &sponsor_},
2083 {"author", &author_},
2086 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2087 const char *start, *end;
2089 if (parser->Find(names[i].name_, start, end)) {
2090 CYString &value(*names[i].value_);
2091 _profile(Package$parse$Value)
2092 value.set(pool_, start, end - start);
2098 _profile(Package$parse$Tagline)
2099 const char *start, *end;
2100 if (parser->ShortDesc(start, end)) {
2101 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2104 while (stop != start && stop[-1] == '\r')
2106 tagline_.set(pool_, start, stop - start);
2110 _profile(Package$parse$Retain)
2111 if (homepage_.empty())
2112 homepage_ = website;
2113 if (homepage_ == depiction_)
2119 - (void) setVisible {
2120 visible_ = required_ && [self unfiltered];
2123 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2124 if ((self = [super init]) != nil) {
2125 _profile(Package$initWithVersion)
2126 era_ = [database era];
2130 iterator_ = version.ParentPkg();
2131 database_ = database;
2133 _profile(Package$initWithVersion$Latest)
2134 latest_ = (NSString *) StripVersion(version_.VerStr());
2137 pkgCache::VerIterator current;
2138 _profile(Package$initWithVersion$Versions)
2139 current = iterator_.CurrentVer();
2141 installed_.set(pool_, StripVersion_(current.VerStr()));
2143 if (!version_.end())
2144 file_ = version_.FileList();
2146 pkgCache &cache([database_ cache]);
2147 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2151 _profile(Package$initWithVersion$Name)
2152 id_.set(pool_, iterator_.Name());
2153 name_.set(pool, iterator_.Display());
2157 _profile(Package$initWithVersion$Source)
2158 source_ = [database_ getSource:file_.File()];
2167 _profile(Package$initWithVersion$Tags)
2168 pkgCache::TagIterator tag(iterator_.TagList());
2170 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2172 const char *name(tag.Name());
2173 [tags_ addObject:(NSString *)CFCString(name)];
2174 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2175 role_ = (NSString *) CFCString(name + 6);
2176 if (required_ && strncmp(name, "require::", 9) == 0 && (
2181 } while (!tag.end());
2185 bool changed(false);
2186 NSString *key([static_cast<id>(id_) lowercaseString]);
2188 _profile(Package$initWithVersion$Metadata)
2189 metadata_ = [Packages_ objectForKey:key];
2191 if (metadata_ == nil) {
2194 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2195 firstSeen_, @"FirstSeen",
2196 latest_, @"LastVersion",
2201 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2202 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2204 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2205 subscribed_ = [subscribed boolValue];
2207 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2209 if (firstSeen_ == nil) {
2210 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2211 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2215 if (version == nil) {
2216 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2218 } else if (![version isEqualToString:latest_]) {
2219 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2221 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2226 metadata_ = [metadata_ retain];
2229 [Packages_ setObject:metadata_ forKey:key];
2234 _profile(Package$initWithVersion$Section)
2235 section_.set(pool_, iterator_.Section());
2238 obsolete_ = [self hasTag:@"cydia::obsolete"];
2239 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2244 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2245 pkgCache::VerIterator version;
2247 _profile(Package$packageWithIterator$GetCandidateVer)
2248 version = [database policy]->GetCandidateVer(iterator);
2254 return [[[Package alloc]
2255 initWithVersion:version
2262 - (pkgCache::PkgIterator) iterator {
2266 - (NSString *) section {
2267 if (section$_ == nil) {
2268 if (section_.empty())
2271 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2272 NSString *name(section_);
2275 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2276 if (NSString *rename = [value objectForKey:@"Rename"]) {
2281 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2285 - (NSString *) simpleSection {
2286 if (NSString *section = [self section])
2287 return Simplify(section);
2292 - (NSString *) longSection {
2293 return LocalizeSection([self section]);
2296 - (NSString *) shortSection {
2297 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2300 - (NSString *) uri {
2303 pkgIndexFile *index;
2304 pkgCache::PkgFileIterator file(file_.File());
2305 if (![database_ list].FindIndex(file, index))
2307 return [NSString stringWithUTF8String:iterator_->Path];
2308 //return [NSString stringWithUTF8String:file.Site()];
2309 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2313 - (Address *) maintainer {
2316 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2317 const std::string &maintainer(parser->Maintainer());
2318 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2322 return version_.end() ? 0 : version_->InstalledSize;
2325 - (NSString *) longDescription {
2326 @synchronized (database_) {
2327 if ([database_ era] != era_ || file_.end())
2330 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2331 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2333 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2334 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2335 if ([lines count] < 2)
2338 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2339 for (size_t i(1), e([lines count]); i != e; ++i) {
2340 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2341 [trimmed addObject:trim];
2344 return [trimmed componentsJoinedByString:@"\n"];
2347 - (NSString *) shortDescription {
2352 _profile(Package$index)
2353 CFStringRef name((CFStringRef) [self name]);
2354 if (CFStringGetLength(name) == 0)
2356 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2357 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2359 return toupper(character);
2363 - (NSMutableDictionary *) metadata {
2368 if (subscribed_ && lastSeen_ != nil)
2373 - (BOOL) subscribed {
2378 NSDictionary *metadata([self metadata]);
2379 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2380 return [ignored boolValue];
2385 - (NSString *) latest {
2389 - (NSString *) installed {
2393 - (BOOL) uninstalled {
2394 return installed_.empty();
2398 return !version_.end();
2401 - (BOOL) upgradableAndEssential:(BOOL)essential {
2402 _profile(Package$upgradableAndEssential)
2403 pkgCache::VerIterator current(iterator_.CurrentVer());
2405 return essential && essential_ && visible_;
2407 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2411 - (BOOL) essential {
2416 return [database_ cache][iterator_].InstBroken();
2419 - (BOOL) unfiltered {
2420 NSString *section([self section]);
2421 return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
2429 unsigned char current(iterator_->CurrentState);
2430 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2433 - (BOOL) halfConfigured {
2434 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2437 - (BOOL) halfInstalled {
2438 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2442 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2443 return state.Mode != pkgDepCache::ModeKeep;
2446 - (NSString *) mode {
2447 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2449 switch (state.Mode) {
2450 case pkgDepCache::ModeDelete:
2451 if ((state.iFlags & pkgDepCache::Purge) != 0)
2455 case pkgDepCache::ModeKeep:
2456 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2457 return @"REINSTALL";
2458 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2462 case pkgDepCache::ModeInstall:
2463 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2464 return @"REINSTALL";
2465 else*/ switch (state.Status) {
2467 return @"DOWNGRADE";
2473 return @"NEW_INSTALL";
2484 - (NSString *) name {
2485 return name_.empty() ? id_ : name_;
2488 - (UIImage *) icon {
2489 NSString *section = [self simpleSection];
2493 if ([static_cast<id>(icon_) hasPrefix:@"file:///"])
2494 // XXX: correct escaping
2495 icon = [UIImage imageAtPath:[static_cast<id>(icon_) substringFromIndex:7]];
2496 if (icon == nil) if (section != nil)
2497 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2498 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2499 if ([dicon hasPrefix:@"file:///"])
2500 // XXX: correct escaping
2501 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2503 icon = [UIImage applicationImageNamed:@"unknown.png"];
2507 - (NSString *) homepage {
2511 - (NSString *) depiction {
2512 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2515 - (Address *) sponsor {
2516 if (sponsor$_ == nil) {
2517 if (sponsor_.empty())
2519 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2523 - (Address *) author {
2524 if (author$_ == nil) {
2525 if (author_.empty())
2527 author$_ = [[Address addressWithString:author_] retain];
2531 - (NSString *) support {
2532 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2535 - (NSArray *) files {
2536 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2537 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2540 fin.open([path UTF8String]);
2545 while (std::getline(fin, line))
2546 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2551 - (NSArray *) relationships {
2552 return relationships_;
2555 - (NSArray *) warnings {
2556 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2557 const char *name(iterator_.Name());
2559 size_t length(strlen(name));
2560 if (length < 2) invalid:
2561 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2562 else for (size_t i(0); i != length; ++i)
2564 /* XXX: technically this is not allowed */
2565 (name[i] < 'A' || name[i] > 'Z') &&
2566 (name[i] < 'a' || name[i] > 'z') &&
2567 (name[i] < '0' || name[i] > '9') &&
2568 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2571 if (strcmp(name, "cydia") != 0) {
2574 bool _private = false;
2577 bool repository = [[self section] isEqualToString:@"Repositories"];
2579 if (NSArray *files = [self files])
2580 for (NSString *file in files)
2581 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2583 else if (!user && [file isEqualToString:@"/User"])
2585 else if (!_private && [file isEqualToString:@"/private"])
2587 else if (!stash && [file isEqualToString:@"/var/stash"])
2590 /* XXX: this is not sensitive enough. only some folders are valid. */
2591 if (cydia && !repository)
2592 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2594 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2596 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2598 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2601 return [warnings count] == 0 ? nil : warnings;
2604 - (NSArray *) applications {
2605 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2607 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2609 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2610 if (NSArray *files = [self files])
2611 for (NSString *file in files)
2612 if (application_r(file)) {
2613 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2614 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2615 if ([id isEqualToString:me])
2618 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2620 display = application_r[1];
2622 NSString *bundle([file stringByDeletingLastPathComponent]);
2623 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2624 if (icon == nil || [icon length] == 0)
2626 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2628 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2629 [applications addObject:application];
2631 [application addObject:id];
2632 [application addObject:display];
2633 [application addObject:url];
2636 return [applications count] == 0 ? nil : applications;
2639 - (Source *) source {
2641 @synchronized (database_) {
2642 if ([database_ era] != era_ || file_.end())
2645 source_ = [database_ getSource:file_.File()];
2657 - (NSString *) role {
2661 - (BOOL) matches:(NSString *)text {
2667 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2668 if (range.location != NSNotFound)
2671 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2672 if (range.location != NSNotFound)
2675 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2676 if (range.location != NSNotFound)
2682 - (bool) hasSupportingRole {
2685 if ([role_ isEqualToString:@"enduser"])
2687 if ([Role_ isEqualToString:@"User"])
2689 if ([role_ isEqualToString:@"hacker"])
2691 if ([Role_ isEqualToString:@"Hacker"])
2693 if ([role_ isEqualToString:@"developer"])
2695 if ([Role_ isEqualToString:@"Developer"])
2700 - (BOOL) hasTag:(NSString *)tag {
2701 return tags_ == nil ? NO : [tags_ containsObject:tag];
2704 - (NSString *) primaryPurpose {
2705 for (NSString *tag in tags_)
2706 if ([tag hasPrefix:@"purpose::"])
2707 return [tag substringFromIndex:9];
2711 - (NSArray *) purposes {
2712 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2713 for (NSString *tag in tags_)
2714 if ([tag hasPrefix:@"purpose::"])
2715 [purposes addObject:[tag substringFromIndex:9]];
2716 return [purposes count] == 0 ? nil : purposes;
2719 - (bool) isCommercial {
2720 return [self hasTag:@"cydia::commercial"];
2723 - (CYString &) cyname {
2724 return name_.empty() ? id_ : name_;
2727 - (uint32_t) compareBySection:(NSArray *)sections {
2728 NSString *section([self section]);
2729 for (size_t i(0), e([sections count]); i != e; ++i) {
2730 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2734 return _not(uint32_t);
2737 - (uint32_t) compareForChanges {
2742 uint32_t timestamp : 30;
2743 uint32_t ignored : 1;
2744 uint32_t upgradable : 1;
2748 bool upgradable([self upgradableAndEssential:YES]);
2749 value.bits.upgradable = upgradable ? 1 : 0;
2752 value.bits.timestamp = 0;
2753 value.bits.ignored = [self ignored] ? 0 : 1;
2754 value.bits.upgradable = 1;
2756 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2757 value.bits.ignored = 0;
2758 value.bits.upgradable = 0;
2761 return _not(uint32_t) - value.key;
2765 pkgProblemResolver *resolver = [database_ resolver];
2766 resolver->Clear(iterator_);
2767 resolver->Protect(iterator_);
2771 pkgProblemResolver *resolver = [database_ resolver];
2772 resolver->Clear(iterator_);
2773 resolver->Protect(iterator_);
2774 pkgCacheFile &cache([database_ cache]);
2775 cache->MarkInstall(iterator_, false);
2776 pkgDepCache::StateCache &state((*cache)[iterator_]);
2777 if (!state.Install())
2778 cache->SetReInstall(iterator_, true);
2782 pkgProblemResolver *resolver = [database_ resolver];
2783 resolver->Clear(iterator_);
2784 resolver->Protect(iterator_);
2785 resolver->Remove(iterator_);
2786 [database_ cache]->MarkDelete(iterator_, true);
2789 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2790 _profile(Package$isUnfilteredAndSearchedForBy)
2793 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2794 value &= [self unfiltered];
2797 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2798 value &= [self matches:search];
2805 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2806 if ([search length] == 0)
2809 _profile(Package$isUnfilteredAndSelectedForBy)
2812 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2813 value &= [self unfiltered];
2816 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2817 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2824 - (bool) isInstalledAndVisible:(NSNumber *)number {
2825 return (![number boolValue] || [self visible]) && ![self uninstalled];
2828 - (bool) isVisibleInSection:(NSString *)name {
2829 NSString *section = [self section];
2834 section == nil && [name length] == 0 ||
2835 [name isEqualToString:section]
2839 - (bool) isVisibleInSource:(Source *)source {
2840 return [self source] == source && [self visible];
2845 /* Section Class {{{ */
2846 @interface Section : NSObject {
2851 NSString *localized_;
2854 - (NSComparisonResult) compareByLocalized:(Section *)section;
2855 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2856 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2857 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2858 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2859 - (NSString *) name;
2866 - (void) addToCount;
2868 - (void) setCount:(size_t)count;
2869 - (NSString *) localized;
2873 @implementation Section
2877 if (localized_ != nil)
2878 [localized_ release];
2882 - (NSComparisonResult) compareByLocalized:(Section *)section {
2883 NSString *lhs(localized_);
2884 NSString *rhs([section localized]);
2886 /*if ([lhs length] != 0 && [rhs length] != 0) {
2887 unichar lhc = [lhs characterAtIndex:0];
2888 unichar rhc = [rhs characterAtIndex:0];
2890 if (isalpha(lhc) && !isalpha(rhc))
2891 return NSOrderedAscending;
2892 else if (!isalpha(lhc) && isalpha(rhc))
2893 return NSOrderedDescending;
2896 return [lhs compare:rhs options:LaxCompareOptions_];
2899 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2900 if ((self = [self initWithName:name localize:NO]) != nil) {
2901 if (localized != nil)
2902 localized_ = [localized retain];
2906 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2907 return [self initWithName:name row:0 localize:localize];
2910 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2911 if ((self = [super init]) != nil) {
2912 name_ = [name retain];
2916 localized_ = [LocalizeSection(name_) retain];
2920 /* XXX: localize the index thingees */
2921 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2922 if ((self = [super init]) != nil) {
2923 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2929 - (NSString *) name {
2949 - (void) addToCount {
2953 - (void) setCount:(size_t)count {
2957 - (NSString *) localized {
2964 static NSString *Colon_;
2965 static NSString *Error_;
2966 static NSString *Warning_;
2968 /* Database Implementation {{{ */
2969 @implementation Database
2971 + (Database *) sharedInstance {
2972 static Database *instance;
2973 if (instance == nil)
2974 instance = [[Database alloc] init];
2984 NSRecycleZone(zone_);
2985 // XXX: malloc_destroy_zone(zone_);
2986 apr_pool_destroy(pool_);
2990 - (void) _readCydia:(NSNumber *)fd { _pooled
2991 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2992 std::istream is(&ib);
2995 static Pcre finish_r("^finish:([^:]*)$");
2997 while (std::getline(is, line)) {
2998 const char *data(line.c_str());
2999 size_t size = line.size();
3000 lprintf("C:%s\n", data);
3002 if (finish_r(data, size)) {
3003 NSString *finish = finish_r[1];
3004 int index = [Finishes_ indexOfObject:finish];
3005 if (index != INT_MAX && index > Finish_)
3013 - (void) _readStatus:(NSNumber *)fd { _pooled
3014 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3015 std::istream is(&ib);
3018 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3019 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3021 while (std::getline(is, line)) {
3022 const char *data(line.c_str());
3023 size_t size(line.size());
3024 lprintf("S:%s\n", data);
3026 if (conffile_r(data, size)) {
3027 [delegate_ setConfigurationData:conffile_r[1]];
3028 } else if (strncmp(data, "status: ", 8) == 0) {
3029 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3030 [delegate_ setProgressTitle:string];
3031 } else if (pmstatus_r(data, size)) {
3032 std::string type([pmstatus_r[1] UTF8String]);
3033 NSString *id = pmstatus_r[2];
3035 float percent([pmstatus_r[3] floatValue]);
3036 [delegate_ setProgressPercent:(percent / 100)];
3038 NSString *string = pmstatus_r[4];
3040 if (type == "pmerror")
3041 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3042 withObject:[NSArray arrayWithObjects:string, id, nil]
3045 else if (type == "pmstatus") {
3046 [delegate_ setProgressTitle:string];
3047 } else if (type == "pmconffile")
3048 [delegate_ setConfigurationData:string];
3050 lprintf("E:unknown pmstatus\n");
3052 lprintf("E:unknown status\n");
3058 - (void) _readOutput:(NSNumber *)fd { _pooled
3059 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3060 std::istream is(&ib);
3063 while (std::getline(is, line)) {
3064 lprintf("O:%s\n", line.c_str());
3065 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3075 - (Package *) packageWithName:(NSString *)name {
3076 @synchronized (self) {
3077 if (static_cast<pkgDepCache *>(cache_) == NULL)
3079 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3080 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3084 if ((self = [super init]) != nil) {
3091 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3092 apr_pool_create(&pool_, NULL);
3094 packages_ = [[NSMutableArray alloc] init];
3098 _assert(pipe(fds) != -1);
3101 _config->Set("APT::Keep-Fds::", cydiafd_);
3102 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3105 detachNewThreadSelector:@selector(_readCydia:)
3107 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3110 _assert(pipe(fds) != -1);
3114 detachNewThreadSelector:@selector(_readStatus:)
3116 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3119 _assert(pipe(fds) != -1);
3120 _assert(dup2(fds[0], 0) != -1);
3121 _assert(close(fds[0]) != -1);
3123 input_ = fdopen(fds[1], "a");
3125 _assert(pipe(fds) != -1);
3126 _assert(dup2(fds[1], 1) != -1);
3127 _assert(close(fds[1]) != -1);
3130 detachNewThreadSelector:@selector(_readOutput:)
3132 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3137 - (pkgCacheFile &) cache {
3141 - (pkgDepCache::Policy *) policy {
3145 - (pkgRecords *) records {
3149 - (pkgProblemResolver *) resolver {
3153 - (pkgAcquire &) fetcher {
3157 - (pkgSourceList &) list {
3161 - (NSArray *) packages {
3165 - (NSArray *) sources {
3166 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3167 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3168 [sources addObject:i->second];
3172 - (NSArray *) issues {
3173 if (cache_->BrokenCount() == 0)
3176 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3178 for (Package *package in packages_) {
3179 if (![package broken])
3181 pkgCache::PkgIterator pkg([package iterator]);
3183 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3184 [entry addObject:[package name]];
3185 [issues addObject:entry];
3187 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3191 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3192 pkgCache::DepIterator start;
3193 pkgCache::DepIterator end;
3194 dep.GlobOr(start, end); // ++dep
3196 if (!cache_->IsImportantDep(end))
3198 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3201 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3202 [entry addObject:failure];
3203 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3205 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3206 if (Package *package = [self packageWithName:name])
3207 name = [package name];
3208 [failure addObject:name];
3210 pkgCache::PkgIterator target(start.TargetPkg());
3211 if (target->ProvidesList != 0)
3212 [failure addObject:@"?"];
3214 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3216 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3217 else if (!cache_[target].CandidateVerIter(cache_).end())
3218 [failure addObject:@"-"];
3219 else if (target->ProvidesList == 0)
3220 [failure addObject:@"!"];
3222 [failure addObject:@"%"];
3226 if (start.TargetVer() != 0)
3227 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3238 - (bool) popErrorWithTitle:(NSString *)title {
3240 std::string message;
3242 while (!_error->empty()) {
3244 bool warning(!_error->PopMessage(error));
3248 size_t size(error.size());
3249 if (size == 0 || error[size - 1] != '\n')
3251 error.resize(size - 1);
3253 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3255 if (!message.empty())
3260 if (fatal && !message.empty())
3261 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3266 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3267 return [self popErrorWithTitle:title] || !success;
3270 - (void) reloadData { CYPoolStart() {
3271 @synchronized (self) {
3274 [packages_ removeAllObjects];
3300 apr_pool_clear(pool_);
3301 NSRecycleZone(zone_);
3303 int chk(creat("/tmp/cydia.chk", 0644));
3307 NSString *title(UCLocalize("DATABASE"));
3310 if (!cache_.Open(progress_, true)) { pop:
3312 bool warning(!_error->PopMessage(error));
3313 lprintf("cache_.Open():[%s]\n", error.c_str());
3315 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3316 [delegate_ repairWithSelector:@selector(configure)];
3317 else if (error == "The package lists or status file could not be parsed or opened.")
3318 [delegate_ repairWithSelector:@selector(update)];
3319 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3320 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3321 // else if (error == "The list of sources could not be read.")
3323 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3332 unlink("/tmp/cydia.chk");
3334 now_ = [[NSDate date] retain];
3336 policy_ = new pkgDepCache::Policy();
3337 records_ = new pkgRecords(cache_);
3338 resolver_ = new pkgProblemResolver(cache_);
3339 fetcher_ = new pkgAcquire(&status_);
3342 list_ = new pkgSourceList();
3343 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3346 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3347 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3351 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3354 if (cache_->BrokenCount() != 0) {
3355 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3358 if (cache_->BrokenCount() != 0) {
3359 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3363 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3369 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3370 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3371 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3372 // XXX: this could be more intelligent
3373 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3374 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3376 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3383 /*std::vector<Package *> packages;
3384 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3385 [packages_ release];
3390 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3391 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3392 //packages.push_back(package);
3393 [packages_ addObject:package];
3397 /*if (packages.empty())
3398 packages_ = [[NSArray alloc] init];
3400 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3403 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3404 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3405 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3413 /*if (!packages.empty())
3414 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3415 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3417 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3419 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3421 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3428 - (void) configure {
3429 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3430 system([dpkg UTF8String]);
3434 // XXX: I don't remember this condition
3439 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3441 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3443 if ([self popErrorWithTitle:title])
3447 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3450 public pkgArchiveCleaner
3453 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3458 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3465 fetcher_->Shutdown();
3467 pkgRecords records(cache_);
3469 lock_ = new FileFd();
3470 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3472 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3474 if ([self popErrorWithTitle:title])
3478 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3481 manager_ = (_system->CreatePM(cache_));
3482 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3489 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3491 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3493 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3495 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3496 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3499 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3504 bool failed = false;
3505 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3506 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3508 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3511 std::string uri = (*item)->DescURI();
3512 std::string error = (*item)->ErrorText;
3514 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3517 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3518 withObject:[NSArray arrayWithObjects:
3519 [NSString stringWithUTF8String:error.c_str()],
3531 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3533 if (_error->PendingError()) {
3538 if (result == pkgPackageManager::Failed) {
3543 if (result != pkgPackageManager::Completed) {
3548 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3550 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3552 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3553 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3556 if (![before isEqualToArray:after])
3561 NSString *title(UCLocalize("UPGRADE"));
3562 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3568 [self updateWithStatus:status_];
3571 - (void) setVisible {
3572 for (Package *package in packages_)
3573 [package setVisible];
3576 - (void) updateWithStatus:(Status &)status {
3577 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3578 NSString *title(UCLocalize("REFRESHING_DATA"));
3581 if (!list.ReadMainList())
3582 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3585 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3586 if ([self popErrorWithTitle:title])
3589 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3590 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3591 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3593 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3597 - (void) setDelegate:(id)delegate {
3598 delegate_ = delegate;
3599 status_.setDelegate(delegate);
3600 progress_.setDelegate(delegate);
3603 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3604 SourceMap::const_iterator i(sources_.find(file->ID));
3605 return i == sources_.end() ? nil : i->second;
3611 /* Confirmation Controller {{{ */
3612 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3613 if (!iterator.end())
3614 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3615 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3617 pkgCache::PkgIterator package(dep.TargetPkg());
3620 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3628 /* Web Scripting {{{ */
3629 @interface CydiaObject : NSObject {
3634 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3637 @implementation CydiaObject
3640 [indirect_ release];
3644 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3645 if ((self = [super init]) != nil) {
3646 indirect_ = [indirect retain];
3650 - (void) setDelegate:(id)delegate {
3651 delegate_ = delegate;
3654 + (NSArray *) _attributeKeys {
3655 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3658 - (NSArray *) attributeKeys {
3659 return [[self class] _attributeKeys];
3662 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3663 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3666 - (NSString *) device {
3667 return [[UIDevice currentDevice] uniqueIdentifier];
3670 #if 0 // XXX: implement!
3671 - (NSString *) mac {
3672 if (![indirect_ promptForSensitive:@"Mac Address"])
3676 - (NSString *) serial {
3677 if (![indirect_ promptForSensitive:@"Serial #"])
3681 - (NSString *) firewire {
3682 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3686 - (NSString *) imei {
3687 if (![indirect_ promptForSensitive:@"IMEI"])
3692 + (NSString *) webScriptNameForSelector:(SEL)selector {
3693 if (selector == @selector(close))
3695 else if (selector == @selector(getInstalledPackages))
3696 return @"getInstalledPackages";
3697 else if (selector == @selector(getPackageById:))
3698 return @"getPackageById";
3699 else if (selector == @selector(installPackages:))
3700 return @"installPackages";
3701 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3702 return @"setButtonImage";
3703 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3704 return @"setButtonTitle";
3705 else if (selector == @selector(setPopupHook:))
3706 return @"setPopupHook";
3707 else if (selector == @selector(setSpecial:))
3708 return @"setSpecial";
3709 else if (selector == @selector(setToken:))
3711 else if (selector == @selector(setViewportWidth:))
3712 return @"setViewportWidth";
3713 else if (selector == @selector(supports:))
3715 else if (selector == @selector(stringWithFormat:arguments:))
3717 else if (selector == @selector(localizedStringForKey:value:table:))
3719 else if (selector == @selector(du:))
3721 else if (selector == @selector(statfs:))
3727 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3728 return [self webScriptNameForSelector:selector] == nil;
3731 - (BOOL) supports:(NSString *)feature {
3732 return [feature isEqualToString:@"window.open"];
3735 - (NSArray *) getInstalledPackages {
3736 NSArray *packages([[Database sharedInstance] packages]);
3737 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3738 for (Package *package in packages)
3739 if ([package installed] != nil)
3740 [installed addObject:package];
3744 - (Package *) getPackageById:(NSString *)id {
3745 Package *package([[Database sharedInstance] packageWithName:id]);
3750 - (NSArray *) statfs:(NSString *)path {
3753 if (path == nil || statfs([path UTF8String], &stat) == -1)
3756 return [NSArray arrayWithObjects:
3757 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3758 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3759 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3763 - (NSNumber *) du:(NSString *)path {
3764 NSNumber *value(nil);
3767 _assert(pipe(fds) != -1);
3769 pid_t pid(ExecFork());
3771 _assert(dup2(fds[1], 1) != -1);
3772 _assert(close(fds[0]) != -1);
3773 _assert(close(fds[1]) != -1);
3774 /* XXX: this should probably not use du */
3775 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3780 _assert(close(fds[1]) != -1);
3782 if (FILE *du = fdopen(fds[0], "r")) {
3784 while (fgets(line, sizeof(line), du) != NULL) {
3785 size_t length(strlen(line));
3786 while (length != 0 && line[length - 1] == '\n')
3787 line[--length] = '\0';
3788 if (char *tab = strchr(line, '\t')) {
3790 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3795 } else _assert(close(fds[0]));
3799 if (waitpid(pid, &status, 0) == -1)
3802 else _assert(false);
3811 - (void) installPackages:(NSArray *)packages {
3812 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3815 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3816 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3819 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3820 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3823 - (void) setSpecial:(id)function {
3824 [indirect_ setSpecial:function];
3827 - (void) setToken:(NSString *)token {
3830 Token_ = [token retain];
3832 [Metadata_ setObject:Token_ forKey:@"Token"];
3836 - (void) setPopupHook:(id)function {
3837 [indirect_ setPopupHook:function];
3840 - (void) setViewportWidth:(float)width {
3841 [indirect_ setViewportWidth:width];
3844 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3845 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3846 unsigned count([arguments count]);
3848 for (unsigned i(0); i != count; ++i)
3849 values[i] = [arguments objectAtIndex:i];
3850 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3853 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3854 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3856 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3858 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3864 /* Cydia Browser Controller {{{ */
3865 @interface CYBrowserController : BrowserController {
3866 CydiaObject *cydia_;
3871 @implementation CYBrowserController
3878 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3881 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3882 [super webView:view didClearWindowObject:window forFrame:frame];
3884 WebDataSource *source([frame dataSource]);
3885 NSURLResponse *response([source response]);
3886 NSURL *url([response URL]);
3887 NSString *scheme([url scheme]);
3889 NSHTTPURLResponse *http;
3890 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3891 http = (NSHTTPURLResponse *) response;
3895 NSDictionary *headers([http allHeaderFields]);
3896 NSString *host([url host]);
3897 [self setHeaders:headers forHost:host];
3900 [host isEqualToString:@"cydia.saurik.com"] ||
3901 [host hasSuffix:@".cydia.saurik.com"] ||
3902 [scheme isEqualToString:@"file"]
3904 [window setValue:cydia_ forKey:@"cydia"];
3907 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3908 if (System_ != NULL)
3909 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3910 if (Machine_ != NULL)
3911 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3913 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3915 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3918 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3919 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3920 [self _setMoreHeaders:copy];
3924 - (void) setDelegate:(id)delegate {
3925 [super setDelegate:delegate];
3926 [cydia_ setDelegate:delegate];
3930 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3931 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3933 WebView *webview([[webview_ _documentView] webView]);
3935 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3937 NSString *application = package == nil ? @"Cydia" : [NSString
3938 stringWithFormat:@"Cydia/%@",
3943 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3945 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3946 if (Product_ != nil)
3947 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3949 [webview setApplicationNameForUserAgent:application];
3956 /* Confirmation {{{ */
3957 @protocol ConfirmationControllerDelegate
3958 - (void) cancelAndClear:(bool)clear;
3959 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3963 @interface ConfirmationController : CYBrowserController {
3964 _transient Database *database_;
3965 UIAlertView *essential_;
3972 - (id) initWithDatabase:(Database *)database;
3976 @implementation ConfirmationController
3983 if (essential_ != nil)
3984 [essential_ release];
3988 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3989 NSString *context([alert context]);
3991 if ([context isEqualToString:@"remove"]) {
3992 if (button == [alert cancelButtonIndex]) {
3993 [self dismissModalViewControllerAnimated:YES];
3994 } else if (button == [alert firstOtherButtonIndex]) {
3997 [delegate_ confirmWithNavigationController:[self navigationController]];
4000 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4001 } else if ([context isEqualToString:@"unable"]) {
4002 [self dismissModalViewControllerAnimated:YES];
4003 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4005 [super alertView:alert clickedButtonAtIndex:button];
4009 - (void) _doContinue {
4010 [self dismissModalViewControllerAnimated:YES];
4011 [delegate_ cancelAndClear:NO];
4014 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4015 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4019 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4020 [super webView:view didClearWindowObject:window forFrame:frame];
4021 [window setValue:changes_ forKey:@"changes"];
4022 [window setValue:issues_ forKey:@"issues"];
4023 [window setValue:sizes_ forKey:@"sizes"];
4024 [window setValue:self forKey:@"queue"];
4027 - (id) initWithDatabase:(Database *)database {
4028 if ((self = [super init]) != nil) {
4029 database_ = database;
4031 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4033 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4034 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4035 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4036 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4037 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4041 pkgDepCache::Policy *policy([database_ policy]);
4043 pkgCacheFile &cache([database_ cache]);
4044 NSArray *packages = [database_ packages];
4045 for (Package *package in packages) {
4046 pkgCache::PkgIterator iterator = [package iterator];
4047 pkgDepCache::StateCache &state(cache[iterator]);
4049 NSString *name([package name]);
4051 if (state.NewInstall())
4052 [installing addObject:name];
4053 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4054 [reinstalling addObject:name];
4055 else if (state.Upgrade())
4056 [upgrading addObject:name];
4057 else if (state.Downgrade())
4058 [downgrading addObject:name];
4059 else if (state.Delete()) {
4060 if ([package essential])
4062 [removing addObject:name];
4065 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4066 substrate_ |= DepSubstrate(iterator.CurrentVer());
4071 else if (Advanced_) {
4072 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4074 essential_ = [[UIAlertView alloc]
4075 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4076 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4078 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4079 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4082 [essential_ setContext:@"remove"];
4084 essential_ = [[UIAlertView alloc]
4085 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4086 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4088 cancelButtonTitle:UCLocalize("OKAY")
4089 otherButtonTitles:nil
4092 [essential_ setContext:@"unable"];
4095 changes_ = [[NSArray alloc] initWithObjects:
4103 issues_ = [database_ issues];
4105 issues_ = [issues_ retain];
4107 sizes_ = [[NSArray alloc] initWithObjects:
4108 SizeString([database_ fetcher].FetchNeeded()),
4109 SizeString([database_ fetcher].PartialPresent()),
4112 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4114 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
4115 initWithTitle:UCLocalize("CANCEL")
4116 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4117 style:UIBarButtonItemStylePlain
4119 action:@selector(cancelButtonClicked)
4121 [[self navigationItem] setLeftBarButtonItem:leftItem];
4126 - (void) applyRightButton {
4127 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
4128 initWithTitle:UCLocalize("CONFIRM")
4129 style:UIBarButtonItemStylePlain
4131 action:@selector(confirmButtonClicked)
4133 #if !AlwaysReload && !IgnoreInstall
4134 if (issues_ == nil && ![self isLoading]) [[self navigationItem] setRightBarButtonItem:rightItem];
4135 else [super applyRightButton];
4137 [[self navigationItem] setRightBarButtonItem:nil];
4139 [rightItem release];
4142 - (void) cancelButtonClicked {
4143 [self dismissModalViewControllerAnimated:YES];
4144 [delegate_ cancelAndClear:YES];
4148 - (void) confirmButtonClicked {
4152 if (essential_ != nil)
4157 [delegate_ confirmWithNavigationController:[self navigationController]];
4165 /* Progress Data {{{ */
4166 @interface ProgressData : NSObject {
4172 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4179 @implementation ProgressData
4181 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4182 if ((self = [super init]) != nil) {
4183 selector_ = selector;
4203 /* Progress Controller {{{ */
4204 @interface ProgressController : CYViewController <
4205 ConfigurationDelegate,
4208 _transient Database *database_;
4209 UIProgressBar *progress_;
4210 UITextView *output_;
4211 UITextLabel *status_;
4212 UIPushButton *close_;
4214 SHA1SumValue springlist_;
4215 SHA1SumValue notifyconf_;
4219 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4221 - (void) _retachThread;
4222 - (void) _detachNewThreadData:(ProgressData *)data;
4223 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4229 @protocol ProgressControllerDelegate
4230 - (void) progressControllerIsComplete:(ProgressController *)sender;
4233 @implementation ProgressController
4236 [database_ setDelegate:nil];
4237 [progress_ release];
4246 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4247 if ((self = [super init]) != nil) {
4248 database_ = database;
4249 [database_ setDelegate:self];
4250 delegate_ = delegate;
4252 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4254 progress_ = [[UIProgressBar alloc] init];
4255 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4256 [progress_ setStyle:0];
4258 status_ = [[UITextLabel alloc] init];
4259 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4260 [status_ setColor:[UIColor whiteColor]];
4261 [status_ setBackgroundColor:[UIColor clearColor]];
4262 [status_ setCentersHorizontally:YES];
4263 //[status_ setFont:font];
4265 output_ = [[UITextView alloc] init];
4267 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4268 //[output_ setTextFont:@"Courier New"];
4269 [output_ setFont:[[output_ font] fontWithSize:12]];
4270 [output_ setTextColor:[UIColor whiteColor]];
4271 [output_ setBackgroundColor:[UIColor clearColor]];
4272 [output_ setMarginTop:0];
4273 [output_ setAllowsRubberBanding:YES];
4274 [output_ setEditable:NO];
4275 [[self view] addSubview:output_];
4277 close_ = [[UIPushButton alloc] init];
4278 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4279 [close_ setAutosizesToFit:NO];
4280 [close_ setDrawsShadow:YES];
4281 [close_ setStretchBackground:YES];
4282 [close_ setEnabled:YES];
4283 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4284 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4285 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4286 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4290 - (void) positionViews {
4291 CGRect bounds = [[self view] bounds];
4292 CGSize prgsize = [UIProgressBar defaultSize];
4295 (bounds.size.width - prgsize.width) / 2,
4296 bounds.size.height - prgsize.height - 20
4299 float closewidth = bounds.size.width - 20;
4300 if (closewidth > 300) closewidth = 300;
4302 [progress_ setFrame:prgrect];
4303 [status_ setFrame:CGRectMake(
4305 bounds.size.height - prgsize.height - 50,
4306 bounds.size.width - 20,
4309 [output_ setFrame:CGRectMake(
4312 bounds.size.width - 20,
4313 bounds.size.height - 62
4315 [close_ setFrame:CGRectMake(
4316 (bounds.size.width - closewidth) / 2,
4317 bounds.size.height - prgsize.height - 50,
4323 - (void) viewWillAppear:(BOOL)animated {
4324 [super viewDidAppear:animated];
4325 [[self navigationItem] setHidesBackButton:YES];
4326 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4328 [self positionViews];
4331 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4332 [self positionViews];
4335 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4336 NSString *context([alert context]);
4338 if ([context isEqualToString:@"conffile"]) {
4339 FILE *input = [database_ input];
4340 if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
4341 else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
4346 - (void) closeButtonPushed {
4349 UpdateExternalStatus(0);
4353 [self dismissModalViewControllerAnimated:YES];
4357 [delegate_ terminateWithSuccess];
4358 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4359 [delegate_ suspendWithAnimation:YES];
4361 [delegate_ suspend];*/
4365 system("launchctl stop com.apple.SpringBoard");
4369 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4378 - (void) _retachThread {
4379 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4381 [[self view] addSubview:close_];
4382 [progress_ removeFromSuperview];
4383 [status_ removeFromSuperview];
4385 [database_ popErrorWithTitle:title_];
4386 [delegate_ progressControllerIsComplete:self];
4390 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4393 MMap mmap(file, MMap::ReadOnly);
4395 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4396 if (!(notifyconf_ == sha1.Result()))
4403 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4406 MMap mmap(file, MMap::ReadOnly);
4408 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4409 if (!(springlist_ == sha1.Result()))
4415 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4416 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4417 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4418 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4419 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4422 system("su -c /usr/bin/uicache mobile");
4424 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4426 [delegate_ setStatusBarShowsProgress:NO];
4429 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4430 [[data target] performSelector:[data selector] withObject:[data object]];
4433 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4436 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4437 UpdateExternalStatus(1);
4444 title_ = [title retain];
4446 [[self navigationItem] setTitle:title_];
4448 [status_ setText:nil];
4449 [output_ setText:@""];
4450 [progress_ setProgress:0];
4452 [close_ removeFromSuperview];
4453 [[self view] addSubview:progress_];
4454 [[self view] addSubview:status_];
4456 [delegate_ setStatusBarShowsProgress:YES];
4461 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4464 MMap mmap(file, MMap::ReadOnly);
4466 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4467 notifyconf_ = sha1.Result();
4473 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4476 MMap mmap(file, MMap::ReadOnly);
4478 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4479 springlist_ = sha1.Result();
4484 detachNewThreadSelector:@selector(_detachNewThreadData:)
4486 withObject:[[ProgressData alloc]
4487 initWithSelector:selector
4494 - (void) repairWithSelector:(SEL)selector {
4496 detachNewThreadSelector:selector
4499 title:UCLocalize("REPAIRING")
4503 - (void) setConfigurationData:(NSString *)data {
4505 performSelectorOnMainThread:@selector(_setConfigurationData:)
4511 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4512 CYActionSheet *sheet([[[CYActionSheet alloc]
4514 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4515 defaultButtonIndex:0
4518 [sheet setMessage:error];
4519 [sheet yieldToPopupAlertAnimated:YES];
4523 - (void) setProgressTitle:(NSString *)title {
4525 performSelectorOnMainThread:@selector(_setProgressTitle:)
4531 - (void) setProgressPercent:(float)percent {
4533 performSelectorOnMainThread:@selector(_setProgressPercent:)
4534 withObject:[NSNumber numberWithFloat:percent]
4539 - (void) startProgress {
4542 - (void) addProgressOutput:(NSString *)output {
4544 performSelectorOnMainThread:@selector(_addProgressOutput:)
4550 - (bool) isCancelling:(size_t)received {
4554 - (void) _setConfigurationData:(NSString *)data {
4555 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4557 if (!conffile_r(data)) {
4558 lprintf("E:invalid conffile\n");
4562 NSString *ofile = conffile_r[1];
4563 //NSString *nfile = conffile_r[2];
4565 UIAlertView *alert = [[[UIAlertView alloc]
4566 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4567 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4569 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4570 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4571 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4575 [alert setContext:@"conffile"];
4579 - (void) _setProgressTitle:(NSString *)title {
4580 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4581 for (size_t i(0), e([words count]); i != e; ++i) {
4582 NSString *word([words objectAtIndex:i]);
4583 if (Package *package = [database_ packageWithName:word])
4584 [words replaceObjectAtIndex:i withObject:[package name]];
4587 [status_ setText:[words componentsJoinedByString:@" "]];
4590 - (void) _setProgressPercent:(NSNumber *)percent {
4591 [progress_ setProgress:[percent floatValue]];
4594 - (void) _addProgressOutput:(NSString *)output {
4595 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4596 CGSize size = [output_ contentSize];
4597 CGRect rect = {{0, size.height}, {size.width, 0}};
4598 [output_ scrollRectToVisible:rect animated:YES];
4601 - (BOOL) isRunning {
4608 /* Cell Content View {{{ */
4609 @protocol ContentDelegate
4610 - (void) drawContentRect:(CGRect)rect;
4613 @interface ContentView : UIView {
4614 _transient id<ContentDelegate> delegate_;
4619 @implementation ContentView
4620 - (id) initWithFrame:(CGRect)frame {
4621 if ((self = [super initWithFrame:frame]) != nil) {
4622 /* Fix landscape stretching. */
4623 [self setNeedsDisplayOnBoundsChange:YES];
4627 - (void) setDelegate:(id<ContentDelegate>)delegate {
4628 delegate_ = delegate;
4631 - (void) drawRect:(CGRect)rect {
4632 [super drawRect:rect];
4633 [delegate_ drawContentRect:rect];
4637 /* Package Cell {{{ */
4638 @interface PackageCell : UITableViewCell <
4643 NSString *description_;
4649 ContentView *content_;
4655 - (PackageCell *) init;
4656 - (void) setPackage:(Package *)package;
4658 + (int) heightForPackage:(Package *)package;
4659 - (void) drawContentRect:(CGRect)rect;
4663 @implementation PackageCell
4665 - (void) clearPackage {
4676 if (description_ != nil) {
4677 [description_ release];
4681 if (source_ != nil) {
4686 if (badge_ != nil) {
4691 if (placard_ != nil) {
4701 [self clearPackage];
4708 return faded_ ? [self selectionPercent] : fade_;
4711 - (PackageCell *) init {
4712 CGRect frame(CGRectMake(0, 0, 320, 74));
4713 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4714 UIView *content([self contentView]);
4715 CGRect bounds([content bounds]);
4717 content_ = [[ContentView alloc] initWithFrame:bounds];
4718 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4719 [content addSubview:content_];
4721 [content_ setDelegate:self];
4722 [content_ setOpaque:YES];
4723 if ([self respondsToSelector:@selector(selectionPercent)])
4728 - (void) _setBackgroundColor {
4730 if (NSString *mode = [package_ mode]) {
4731 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4732 color = remove ? RemovingColor_ : InstallingColor_;
4734 color = [UIColor whiteColor];
4736 [content_ setBackgroundColor:color];
4737 [self setNeedsDisplay];
4740 - (void) setPackage:(Package *)package {
4741 [self clearPackage];
4744 Source *source = [package source];
4746 icon_ = [[package icon] retain];
4747 name_ = [[package name] retain];
4750 description_ = [package longDescription];
4751 if (description_ == nil)
4752 description_ = [package shortDescription];
4753 if (description_ != nil)
4754 description_ = [description_ retain];
4756 commercial_ = [package isCommercial];
4758 package_ = [package retain];
4760 NSString *label = nil;
4761 bool trusted = false;
4763 if (source != nil) {
4764 label = [source label];
4765 trusted = [source trusted];
4766 } else if ([[package id] isEqualToString:@"firmware"])
4767 label = UCLocalize("APPLE");
4769 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4771 NSString *from(label);
4773 NSString *section = [package simpleSection];
4774 if (section != nil && ![section isEqualToString:label]) {
4775 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4776 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4779 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4780 source_ = [from retain];
4782 if (NSString *purpose = [package primaryPurpose])
4783 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4784 badge_ = [badge_ retain];
4786 if ([package installed] != nil)
4787 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4788 placard_ = [placard_ retain];
4790 [self _setBackgroundColor];
4791 [content_ setNeedsDisplay];
4794 - (void) drawContentRect:(CGRect)rect {
4795 bool selected([self isSelected]);
4796 float width([self bounds].size.width);
4799 CGContextRef context(UIGraphicsGetCurrentContext());
4800 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4801 CGContextFillRect(context, rect);
4806 rect.size = [icon_ size];
4808 rect.size.width /= 2;
4809 rect.size.height /= 2;
4811 rect.origin.x = 25 - rect.size.width / 2;
4812 rect.origin.y = 25 - rect.size.height / 2;
4814 [icon_ drawInRect:rect];
4817 if (badge_ != nil) {
4818 CGSize size = [badge_ size];
4820 [badge_ drawAtPoint:CGPointMake(
4821 36 - size.width / 2,
4822 36 - size.height / 2
4830 UISetColor(commercial_ ? Purple_ : Black_);
4831 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4832 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4835 UISetColor(commercial_ ? Purplish_ : Gray_);
4836 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4838 if (placard_ != nil)
4839 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4842 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4843 //[self _setBackgroundColor];
4844 [super setSelected:selected animated:fade];
4845 [content_ setNeedsDisplay];
4848 + (int) heightForPackage:(Package *)package {
4854 /* Section Cell {{{ */
4855 @interface SectionCell : UITableViewCell <
4863 ContentView *content_;
4868 - (void) setSection:(Section *)section editing:(BOOL)editing;
4872 @implementation SectionCell
4874 - (void) clearSection {
4875 if (basic_ != nil) {
4880 if (section_ != nil) {
4890 if (count_ != nil) {
4897 [self clearSection];
4905 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4906 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4907 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4908 switch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4909 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4911 UIView *content([self contentView]);
4912 CGRect bounds([content bounds]);
4914 content_ = [[ContentView alloc] initWithFrame:bounds];
4915 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4916 [content addSubview:content_];
4917 [content_ setBackgroundColor:[UIColor whiteColor]];
4919 [content_ setDelegate:self];
4923 - (void) onSwitch:(id)sender {
4924 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4925 if (metadata == nil) {
4926 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4927 [Sections_ setObject:metadata forKey:basic_];
4931 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4934 - (void) setSection:(Section *)section editing:(BOOL)editing {
4935 if (editing != editing_) {
4937 [switch_ removeFromSuperview];
4939 [self addSubview:switch_];
4943 [self clearSection];
4945 if (section == nil) {
4946 name_ = [UCLocalize("ALL_PACKAGES") retain];
4949 basic_ = [section name];
4951 basic_ = [basic_ retain];
4953 section_ = [section localized];
4954 if (section_ != nil)
4955 section_ = [section_ retain];
4957 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4958 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4961 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4964 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4965 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
4967 [content_ setNeedsDisplay];
4970 - (void) setFrame:(CGRect)frame {
4971 [super setFrame:frame];
4973 CGRect rect([switch_ frame]);
4974 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4977 - (void) drawContentRect:(CGRect)rect {
4978 BOOL selected = [self isSelected];
4980 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4988 float width(rect.size.width);
4992 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4994 CGSize size = [count_ sizeWithFont:Font14_];
4998 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5004 /* File Table {{{ */
5005 @interface FileTable : CYViewController <
5006 UITableViewDataSource,
5009 _transient Database *database_;
5012 NSMutableArray *files_;
5016 - (id) initWithDatabase:(Database *)database;
5017 - (void) setPackage:(Package *)package;
5021 @implementation FileTable
5024 if (package_ != nil)
5033 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5034 return files_ == nil ? 0 : [files_ count];
5037 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5041 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5042 static NSString *reuseIdentifier = @"Cell";
5044 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5046 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5047 [cell setFont:[UIFont systemFontOfSize:16]];
5049 [cell setText:[files_ objectAtIndex:indexPath.row]];
5050 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5055 - (id) initWithDatabase:(Database *)database {
5056 if ((self = [super init]) != nil) {
5057 database_ = database;
5059 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5061 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5063 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5064 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5065 [list_ setRowHeight:24.0f];
5066 [[self view] addSubview:list_];
5068 [list_ setDataSource:self];
5069 [list_ setDelegate:self];
5073 - (void) setPackage:(Package *)package {
5074 if (package_ != nil) {
5075 [package_ autorelease];
5084 [files_ removeAllObjects];
5086 if (package != nil) {
5087 package_ = [package retain];
5088 name_ = [[package id] retain];
5090 if (NSArray *files = [package files])
5091 [files_ addObjectsFromArray:files];
5093 if ([files_ count] != 0) {
5094 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5095 [files_ removeObjectAtIndex:0];
5096 [files_ sortUsingSelector:@selector(compareByPath:)];
5098 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5099 [stack addObject:@"/"];
5101 for (int i(0), e([files_ count]); i != e; ++i) {
5102 NSString *file = [files_ objectAtIndex:i];
5103 while (![file hasPrefix:[stack lastObject]])
5104 [stack removeLastObject];
5105 NSString *directory = [stack lastObject];
5106 [stack addObject:[file stringByAppendingString:@"/"]];
5107 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5108 ([stack count] - 2) * 3, "",
5109 [file substringFromIndex:[directory length]]
5118 - (void) reloadData {
5119 [self setPackage:[database_ packageWithName:name_]];
5124 /* Package Controller {{{ */
5125 @interface PackageController : CYBrowserController <
5126 UIActionSheetDelegate
5128 _transient Database *database_;
5132 NSMutableArray *buttons_;
5133 UIBarButtonItem *button_;
5136 - (id) initWithDatabase:(Database *)database;
5137 - (void) setPackage:(Package *)package;
5141 @implementation PackageController
5144 if (package_ != nil)
5158 if ([self retainCount] == 1)
5159 [delegate_ setPackageController:self];
5163 /* XXX: this is not safe at all... localization of /fail/ */
5164 - (void) _clickButtonWithName:(NSString *)name {
5165 if ([name isEqualToString:UCLocalize("CLEAR")])
5166 [delegate_ clearPackage:package_];
5167 else if ([name isEqualToString:UCLocalize("INSTALL")])
5168 [delegate_ installPackage:package_];
5169 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5170 [delegate_ installPackage:package_];
5171 else if ([name isEqualToString:UCLocalize("REMOVE")])
5172 [delegate_ removePackage:package_];
5173 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5174 [delegate_ installPackage:package_];
5175 else _assert(false);
5178 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5179 NSString *context([sheet context]);
5181 if ([context isEqualToString:@"modify"]) {
5182 if (button != [sheet cancelButtonIndex]) {
5183 NSString *buttonName = [buttons_ objectAtIndex:button];
5184 [self _clickButtonWithName:buttonName];
5187 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5191 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5192 [super webView:view didClearWindowObject:window forFrame:frame];
5193 [window setValue:package_ forKey:@"package"];
5196 - (bool) _allowJavaScriptPanel {
5201 - (void) _customButtonClicked {
5202 int count([buttons_ count]);
5207 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5209 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5210 [buttons addObjectsFromArray:buttons_];
5212 UIActionSheet *sheet = [[[UIActionSheet alloc]
5215 cancelButtonTitle:nil
5216 destructiveButtonTitle:nil
5217 otherButtonTitles:nil
5220 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5222 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5223 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5225 [sheet setContext:@"modify"];
5227 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5231 // We don't want to allow non-commercial packages to do custom things to the install button,
5232 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5233 - (void) customButtonClicked {
5235 [super customButtonClicked];
5237 [self _customButtonClicked];
5240 - (void) reloadButtonClicked {
5241 // Don't reload a package view by clicking the button.
5244 - (void) applyLoadingTitle {
5245 // Don't show "Loading" as the title. Ever.
5248 - (UIBarButtonItem *) rightButton {
5253 - (id) initWithDatabase:(Database *)database {
5254 if ((self = [super init]) != nil) {
5255 database_ = database;
5256 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5257 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5261 - (void) setPackage:(Package *)package {
5262 if (package_ != nil) {
5263 [package_ autorelease];
5272 [buttons_ removeAllObjects];
5274 if (package != nil) {
5277 package_ = [package retain];
5278 name_ = [[package id] retain];
5279 commercial_ = [package isCommercial];
5281 if ([package_ mode] != nil)
5282 [buttons_ addObject:UCLocalize("CLEAR")];
5283 if ([package_ source] == nil);
5284 else if ([package_ upgradableAndEssential:NO])
5285 [buttons_ addObject:UCLocalize("UPGRADE")];
5286 else if ([package_ uninstalled])
5287 [buttons_ addObject:UCLocalize("INSTALL")];
5289 [buttons_ addObject:UCLocalize("REINSTALL")];
5290 if (![package_ uninstalled])
5291 [buttons_ addObject:UCLocalize("REMOVE")];
5298 switch ([buttons_ count]) {
5299 case 0: title = nil; break;
5300 case 1: title = [buttons_ objectAtIndex:0]; break;
5301 default: title = UCLocalize("MODIFY"); break;
5304 button_ = [[UIBarButtonItem alloc]
5306 style:UIBarButtonItemStylePlain
5308 action:@selector(customButtonClicked)
5312 - (bool) isLoading {
5313 return commercial_ ? [super isLoading] : false;
5316 - (void) reloadData {
5317 [self setPackage:[database_ packageWithName:name_]];
5322 /* Package Table {{{ */
5323 @interface PackageTable : UIView <
5324 UITableViewDataSource,
5327 _transient Database *database_;
5328 NSMutableArray *packages_;
5329 NSMutableArray *sections_;
5331 NSMutableArray *index_;
5332 NSMutableDictionary *indices_;
5338 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5340 - (void) setDelegate:(id)delegate;
5342 - (void) reloadData;
5343 - (void) resetCursor;
5345 - (UITableView *) list;
5347 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5349 - (void) deselectWithAnimation:(BOOL)animated;
5353 @implementation PackageTable
5356 [packages_ release];
5357 [sections_ release];
5365 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5366 NSInteger count([sections_ count]);
5367 return count == 0 ? 1 : count;
5370 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5371 if ([sections_ count] == 0)
5373 return [[sections_ objectAtIndex:section] name];
5376 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5377 if ([sections_ count] == 0)
5379 return [[sections_ objectAtIndex:section] count];
5382 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5383 Section *section([sections_ objectAtIndex:[path section]]);
5384 NSInteger row([path row]);
5385 Package *package([packages_ objectAtIndex:([section row] + row)]);
5389 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5390 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5392 cell = [[[PackageCell alloc] init] autorelease];
5393 [cell setPackage:[self packageAtIndexPath:path]];
5397 - (void) deselectWithAnimation:(BOOL)animated {
5398 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5401 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5402 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5405 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5406 Package *package([self packageAtIndexPath:path]);
5407 package = [database_ packageWithName:[package id]];
5408 [target_ performSelector:action_ withObject:package];
5412 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5413 return [packages_ count] > 20 ? index_ : nil;
5416 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5420 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5421 if ((self = [super initWithFrame:frame]) != nil) {
5422 database_ = database;
5427 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5428 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5430 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5431 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5433 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5434 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5435 [list_ setRowHeight:73.0f];
5436 [self addSubview:list_];
5438 [list_ setDataSource:self];
5439 [list_ setDelegate:self];
5443 - (void) setDelegate:(id)delegate {
5444 delegate_ = delegate;
5447 - (bool) hasPackage:(Package *)package {
5451 - (void) reloadData {
5452 NSArray *packages = [database_ packages];
5454 [packages_ removeAllObjects];
5455 [sections_ removeAllObjects];
5457 _profile(PackageTable$reloadData$Filter)
5458 for (Package *package in packages)
5459 if ([self hasPackage:package])
5460 [packages_ addObject:package];
5463 [index_ removeAllObjects];
5464 [indices_ removeAllObjects];
5466 Section *section = nil;
5468 _profile(PackageTable$reloadData$Section)
5469 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5473 _profile(PackageTable$reloadData$Section$Package)
5474 package = [packages_ objectAtIndex:offset];
5475 index = [package index];
5478 if (section == nil || [section index] != index) {
5479 _profile(PackageTable$reloadData$Section$Allocate)
5480 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5483 [index_ addObject:[section name]];
5484 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5486 _profile(PackageTable$reloadData$Section$Add)
5487 [sections_ addObject:section];
5491 [section addToCount];
5495 _profile(PackageTable$reloadData$List)
5500 - (void) resetCursor {
5501 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5504 - (UITableView *) list {
5508 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5509 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5514 /* Filtered Package Table {{{ */
5515 @interface FilteredPackageTable : PackageTable {
5521 - (void) setObject:(id)object;
5522 - (void) setObject:(id)object forFilter:(SEL)filter;
5524 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5528 @implementation FilteredPackageTable
5536 - (void) setFilter:(SEL)filter {
5539 /* XXX: this is an unsafe optimization of doomy hell */
5540 Method method(class_getInstanceMethod([Package class], filter));
5541 _assert(method != NULL);
5542 imp_ = method_getImplementation(method);
5543 _assert(imp_ != NULL);
5546 - (void) setObject:(id)object {
5552 object_ = [object retain];
5555 - (void) setObject:(id)object forFilter:(SEL)filter {
5556 [self setFilter:filter];
5557 [self setObject:object];
5560 - (bool) hasPackage:(Package *)package {
5561 _profile(FilteredPackageTable$hasPackage)
5562 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5566 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5567 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5568 [self setFilter:filter];
5569 object_ = [object retain];
5577 /* Filtered Package Controller {{{ */
5578 @interface FilteredPackageController : CYViewController {
5579 _transient Database *database_;
5580 FilteredPackageTable *packages_;
5584 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5588 @implementation FilteredPackageController
5591 [packages_ release];
5597 - (void) viewDidAppear:(BOOL)animated {
5598 [super viewDidAppear:animated];
5599 [packages_ deselectWithAnimation:animated];
5602 - (void) didSelectPackage:(Package *)package {
5603 PackageController *view([delegate_ packageController]);
5604 [view setPackage:package];
5605 [view setDelegate:delegate_];
5606 [[self navigationController] pushViewController:view animated:YES];
5609 - (NSString *) title { return title_; }
5611 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5612 if ((self = [super init]) != nil) {
5613 database_ = database;
5614 title_ = [title copy];
5615 [[self navigationItem] setTitle:title_];
5617 packages_ = [[FilteredPackageTable alloc]
5618 initWithFrame:[[self view] bounds]
5621 action:@selector(didSelectPackage:)
5626 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5627 [[self view] addSubview:packages_];
5631 - (void) reloadData {
5632 [packages_ reloadData];
5635 - (void) setDelegate:(id)delegate {
5636 [super setDelegate:delegate];
5637 [packages_ setDelegate:delegate];
5644 /* Add Source Controller {{{ */
5645 @interface AddSourceController : CYViewController {
5646 _transient Database *database_;
5649 - (id) initWithDatabase:(Database *)database;
5653 @implementation AddSourceController
5655 - (id) initWithDatabase:(Database *)database {
5656 if ((self = [super init]) != nil) {
5657 database_ = database;
5663 /* Source Cell {{{ */
5664 @interface SourceCell : UITableViewCell <
5669 NSString *description_;
5671 ContentView *content_;
5674 - (void) setSource:(Source *)source;
5678 @implementation SourceCell
5680 - (void) clearSource {
5683 [description_ release];
5692 - (void) setSource:(Source *)source {
5696 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5698 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5699 icon_ = [icon_ retain];
5701 origin_ = [[source name] retain];
5702 label_ = [[source uri] retain];
5703 description_ = [[source description] retain];
5705 [content_ setNeedsDisplay];
5714 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5715 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5716 UIView *content([self contentView]);
5717 CGRect bounds([content bounds]);
5719 content_ = [[ContentView alloc] initWithFrame:bounds];
5720 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5721 [content_ setBackgroundColor:[UIColor whiteColor]];
5722 [content addSubview:content_];
5724 [content_ setDelegate:self];
5725 [content_ setOpaque:YES];
5729 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5730 [super setSelected:selected animated:animated];
5731 [content_ setNeedsDisplay];
5734 - (void) drawContentRect:(CGRect)rect {
5735 bool selected([self isSelected]);
5736 float width(rect.size.width);
5739 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5746 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5750 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5754 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5759 /* Source Table {{{ */
5760 @interface SourceTable : CYViewController <
5761 UITableViewDataSource,
5764 _transient Database *database_;
5766 NSMutableArray *sources_;
5770 UIProgressHUD *hud_;
5773 //NSURLConnection *installer_;
5774 NSURLConnection *trivial_;
5775 NSURLConnection *trivial_bz2_;
5776 NSURLConnection *trivial_gz_;
5777 //NSURLConnection *automatic_;
5782 - (id) initWithDatabase:(Database *)database;
5784 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5788 @implementation SourceTable
5790 - (void) _deallocConnection:(NSURLConnection *)connection {
5791 if (connection != nil) {
5792 [connection cancel];
5793 //[connection setDelegate:nil];
5794 [connection release];
5806 //[self _deallocConnection:installer_];
5807 [self _deallocConnection:trivial_];
5808 [self _deallocConnection:trivial_gz_];
5809 [self _deallocConnection:trivial_bz2_];
5810 //[self _deallocConnection:automatic_];
5817 - (void) viewDidAppear:(BOOL)animated {
5818 [super viewDidAppear:animated];
5819 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5822 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5823 return offset_ == 0 ? 1 : 2;
5826 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5827 switch (section + (offset_ == 0 ? 1 : 0)) {
5828 case 0: return UCLocalize("ENTERED_BY_USER");
5829 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5835 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5836 int count = [sources_ count];
5838 case 0: return (offset_ == 0 ? count : offset_);
5839 case 1: return count - offset_;
5845 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5847 switch (indexPath.section) {
5848 case 0: idx = indexPath.row; break;
5849 case 1: idx = indexPath.row + offset_; break;
5853 return [sources_ objectAtIndex:idx];
5856 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5857 Source *source = [self sourceAtIndexPath:indexPath];
5858 return [source description] == nil ? 56 : 73;
5861 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5862 static NSString *cellIdentifier = @"SourceCell";
5864 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5865 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5866 [cell setSource:[self sourceAtIndexPath:indexPath]];
5871 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5872 return UITableViewCellAccessoryDisclosureIndicator;
5875 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5876 Source *source = [self sourceAtIndexPath:indexPath];
5878 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5879 initWithDatabase:database_
5880 title:[source label]
5881 filter:@selector(isVisibleInSource:)
5885 [packages setDelegate:delegate_];
5887 [[self navigationController] pushViewController:packages animated:YES];
5890 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5891 Source *source = [self sourceAtIndexPath:indexPath];
5892 return [source record] != nil;
5895 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5896 Source *source = [self sourceAtIndexPath:indexPath];
5897 [Sources_ removeObjectForKey:[source key]];
5898 [delegate_ syncData];
5902 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5905 @"./", @"Distribution",
5906 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5908 [delegate_ syncData];
5911 - (NSString *) getWarning {
5912 NSString *href(href_);
5913 NSRange colon([href rangeOfString:@"://"]);
5914 if (colon.location != NSNotFound)
5915 href = [href substringFromIndex:(colon.location + 3)];
5916 href = [href stringByAddingPercentEscapes];
5917 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5918 href = [href stringByCachingURLWithCurrentCDN];
5920 NSURL *url([NSURL URLWithString:href]);
5922 NSStringEncoding encoding;
5923 NSError *error(nil);
5925 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5926 return [warning length] == 0 ? nil : warning;
5930 - (void) _endConnection:(NSURLConnection *)connection {
5931 NSURLConnection **field = NULL;
5932 if (connection == trivial_)
5934 else if (connection == trivial_bz2_)
5935 field = &trivial_bz2_;
5936 else if (connection == trivial_gz_)
5937 field = &trivial_gz_;
5938 _assert(field != NULL);
5939 [connection release];
5944 trivial_bz2_ == nil &&
5950 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5953 UIAlertView *alert = [[[UIAlertView alloc]
5954 initWithTitle:UCLocalize("SOURCE_WARNING")
5957 cancelButtonTitle:UCLocalize("CANCEL")
5958 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5961 [alert setContext:@"warning"];
5962 [alert setNumberOfRows:1];
5966 } else if (error_ != nil) {
5967 UIAlertView *alert = [[[UIAlertView alloc]
5968 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5969 message:[error_ localizedDescription]
5971 cancelButtonTitle:UCLocalize("OK")
5972 otherButtonTitles:nil
5975 [alert setContext:@"urlerror"];
5978 UIAlertView *alert = [[[UIAlertView alloc]
5979 initWithTitle:UCLocalize("NOT_REPOSITORY")
5980 message:UCLocalize("NOT_REPOSITORY_EX")
5982 cancelButtonTitle:UCLocalize("OK")
5983 otherButtonTitles:nil
5986 [alert setContext:@"trivial"];
5990 [delegate_ setStatusBarShowsProgress:NO];
5991 [delegate_ removeProgressHUD:hud_];
6001 if (error_ != nil) {
6008 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6009 switch ([response statusCode]) {
6015 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6016 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6018 error_ = [error retain];
6019 [self _endConnection:connection];
6022 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6023 [self _endConnection:connection];
6026 - (NSString *) title { return UCLocalize("SOURCES"); }
6028 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6029 NSMutableURLRequest *request = [NSMutableURLRequest
6030 requestWithURL:[NSURL URLWithString:href]
6031 cachePolicy:NSURLRequestUseProtocolCachePolicy
6032 timeoutInterval:120.0
6035 [request setHTTPMethod:method];
6037 if (Machine_ != NULL)
6038 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6039 if (UniqueID_ != nil)
6040 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6042 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6044 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6047 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6048 NSString *context([alert context]);
6050 if ([context isEqualToString:@"source"]) {
6053 NSString *href = [[alert textField] text];
6055 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6057 if (![href hasSuffix:@"/"])
6058 href_ = [href stringByAppendingString:@"/"];
6061 href_ = [href_ retain];
6063 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6064 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6065 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6066 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6070 hud_ = [[delegate_ addProgressHUD] retain];
6071 [hud_ setText:UCLocalize("VERIFYING_URL")];
6080 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6081 } else if ([context isEqualToString:@"trivial"])
6082 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6083 else if ([context isEqualToString:@"urlerror"])
6084 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6085 else if ([context isEqualToString:@"warning"]) {
6100 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6104 - (id) initWithDatabase:(Database *)database {
6105 if ((self = [super init]) != nil) {
6106 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6107 [self updateButtonsForEditingStatus:NO animated:NO];
6109 database_ = database;
6110 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6112 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6113 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6114 [[self view] addSubview:list_];
6116 [list_ setDataSource:self];
6117 [list_ setDelegate:self];
6123 - (void) reloadData {
6125 if (!list.ReadMainList())
6128 [sources_ removeAllObjects];
6129 [sources_ addObjectsFromArray:[database_ sources]];
6131 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6134 int count([sources_ count]);
6136 for (int i = 0; i != count; i++) {
6137 if ([[sources_ objectAtIndex:i] record] == nil) break;
6141 [list_ setEditing:NO];
6142 [self updateButtonsForEditingStatus:NO animated:NO];
6146 - (void) addButtonClicked {
6147 /*[book_ pushPage:[[[AddSourceController alloc]
6152 UIAlertView *alert = [[[UIAlertView alloc]
6153 initWithTitle:UCLocalize("ENTER_APT_URL")
6156 cancelButtonTitle:UCLocalize("CANCEL")
6157 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6160 [alert setContext:@"source"];
6161 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6163 [alert setNumberOfRows:1];
6164 [alert addTextFieldWithValue:@"http://" label:@""];
6166 UITextInputTraits *traits = [[alert textField] textInputTraits];
6167 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6168 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6169 [traits setKeyboardType:UIKeyboardTypeURL];
6170 // XXX: UIReturnKeyDone
6171 [traits setReturnKeyType:UIReturnKeyNext];
6176 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6177 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
6178 initWithTitle:UCLocalize("ADD")
6179 style:UIBarButtonItemStylePlain
6181 action:@selector(addButtonClicked)
6183 [[self navigationItem] setLeftBarButtonItem:editing ? leftItem : [[self navigationItem] backBarButtonItem] animated:animated];
6186 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6187 initWithTitle:editing ? UCLocalize("DONE") : UCLocalize("EDIT")
6188 style:editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6190 action:@selector(editButtonClicked)
6192 [[self navigationItem] setRightBarButtonItem:rightItem animated:animated];
6193 [rightItem release];
6195 if (IsWildcat_ && !editing) {
6196 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6197 initWithTitle:UCLocalize("SETTINGS")
6198 style:UIBarButtonItemStylePlain
6200 action:@selector(settingsButtonClicked)
6202 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6203 [settingsItem release];
6207 - (void) settingsButtonClicked {
6208 [delegate_ showSettings];
6211 - (void) editButtonClicked {
6212 [list_ setEditing:![list_ isEditing] animated:YES];
6214 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6220 /* Installed Controller {{{ */
6221 @interface InstalledController : FilteredPackageController {
6225 - (id) initWithDatabase:(Database *)database;
6227 - (void) updateRoleButton;
6228 - (void) queueStatusDidChange;
6232 @implementation InstalledController
6238 - (NSString *) title { return UCLocalize("INSTALLED"); }
6240 - (id) initWithDatabase:(Database *)database {
6241 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6242 [self updateRoleButton];
6243 [self queueStatusDidChange];
6248 - (void) queueButtonClicked {
6253 - (void) queueStatusDidChange {
6256 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6257 initWithTitle:UCLocalize("QUEUE")
6258 style:UIBarButtonItemStyleDone
6260 action:@selector(queueButtonClicked)
6262 if (Queuing_) [[self navigationItem] setLeftBarButtonItem:queueItem];
6263 else [[self navigationItem] setLeftBarButtonItem:nil];
6264 [queueItem release];
6269 - (void) reloadData {
6270 [packages_ reloadData];
6273 - (void) updateRoleButton {
6274 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6275 initWithTitle:expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")
6276 style:expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6278 action:@selector(roleButtonClicked)
6280 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) [[self navigationItem] setRightBarButtonItem:rightItem];
6281 [rightItem release];
6284 - (void) roleButtonClicked {
6285 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6286 [packages_ reloadData];
6289 [self updateRoleButton];
6292 - (void) setDelegate:(id)delegate {
6293 [super setDelegate:delegate];
6294 [packages_ setDelegate:delegate];
6300 /* Home Controller {{{ */
6301 @interface HomeController : CYBrowserController {
6306 @implementation HomeController
6308 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6309 [super _setMoreHeaders:request];
6312 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6313 if (UniqueID_ != nil)
6314 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6316 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6319 - (void) aboutButtonClicked {
6320 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6322 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6323 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6324 [alert setCancelButtonIndex:0];
6327 @"Copyright (C) 2008-2010\n"
6328 "Jay Freeman (saurik)\n"
6329 "saurik@saurik.com\n"
6330 "http://www.saurik.com/"
6336 - (void) viewWillAppear:(BOOL)animated {
6337 [super viewWillAppear:animated];
6338 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6341 - (void) viewWillDisappear:(BOOL)animated {
6342 [super viewWillDisappear:animated];
6343 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6347 if ((self = [super init]) != nil) {
6348 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6349 initWithTitle:UCLocalize("ABOUT")
6350 style:UIBarButtonItemStylePlain
6352 action:@selector(aboutButtonClicked)
6359 /* Manage Controller {{{ */
6360 @interface ManageController : CYBrowserController {
6363 - (void) queueStatusDidChange;
6366 @implementation ManageController
6369 if ((self = [super init]) != nil) {
6370 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6372 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6373 initWithTitle:UCLocalize("SETTINGS")
6374 style:UIBarButtonItemStylePlain
6376 action:@selector(settingsButtonClicked)
6378 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6379 [settingsItem release];
6381 [self queueStatusDidChange];
6385 - (void) settingsButtonClicked {
6386 [delegate_ showSettings];
6390 - (void) queueButtonClicked {
6394 - (void) applyLoadingTitle {
6395 // No "Loading" title.
6398 - (void) applyRightButton {
6403 - (void) queueStatusDidChange {
6405 if (!IsWildcat_ && Queuing_) {
6406 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6407 initWithTitle:UCLocalize("QUEUE")
6408 style:UIBarButtonItemStyleDone
6410 action:@selector(queueButtonClicked)
6412 [[self navigationItem] setRightBarButtonItem:queueItem];
6414 [queueItem release];
6416 [[self navigationItem] setRightBarButtonItem:nil];
6421 - (bool) isLoading {
6428 /* Refresh Bar {{{ */
6429 @interface RefreshBar : UINavigationBar {
6430 UIProgressIndicator *indicator_;
6431 UITextLabel *prompt_;
6432 UIProgressBar *progress_;
6433 UINavigationButton *cancel_;
6438 @implementation RefreshBar
6440 - (void) positionViews {
6441 CGRect frame = [cancel_ frame];
6442 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6443 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6444 [cancel_ setFrame:frame];
6446 CGSize prgsize = {75, 100};
6448 [self frame].size.width - prgsize.width - 10,
6449 ([self frame].size.height - prgsize.height) / 2
6451 [progress_ setFrame:prgrect];
6453 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6454 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6455 CGRect indrect = {{indoffset, indoffset}, indsize};
6456 [indicator_ setFrame:indrect];
6458 CGSize prmsize = {215, indsize.height + 4};
6460 indoffset * 2 + indsize.width,
6461 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6463 [prompt_ setFrame:prmrect];
6466 - (void)setFrame:(CGRect)frame {
6467 [super setFrame:frame];
6469 [self positionViews];
6472 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6473 if ((self = [super initWithFrame:frame])) {
6474 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6476 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6477 [self setBarStyle:UIBarStyleBlack];
6479 UIBarStyle barstyle([self _barStyle:NO]);
6480 bool ugly(barstyle == UIBarStyleDefault);
6482 UIProgressIndicatorStyle style = ugly ?
6483 UIProgressIndicatorStyleMediumBrown :
6484 UIProgressIndicatorStyleMediumWhite;
6486 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6487 [indicator_ setStyle:style];
6488 [indicator_ startAnimation];
6489 [self addSubview:indicator_];
6491 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6492 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6493 [prompt_ setBackgroundColor:[UIColor clearColor]];
6494 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6495 [self addSubview:prompt_];
6497 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6498 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6499 [progress_ setStyle:0];
6500 [self addSubview:progress_];
6502 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6503 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6504 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6505 [cancel_ setBarStyle:barstyle];
6507 [self positionViews];
6512 [cancel_ removeFromSuperview];
6516 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6517 [progress_ setProgress:0];
6518 [self addSubview:cancel_];
6522 [cancel_ removeFromSuperview];
6525 - (void) setPrompt:(NSString *)prompt {
6526 [prompt_ setText:prompt];
6529 - (void) setProgress:(float)progress {
6530 [progress_ setProgress:progress];
6536 @class CYNavigationController;
6538 /* Cydia Tab Bar Controller {{{ */
6539 @interface CYTabBarController : UITabBarController {
6540 Database *database_;
6545 @implementation CYTabBarController
6547 /* XXX: some logic should probably go here related to
6548 freeing the view controllers on tab change */
6550 - (void) reloadData {
6551 size_t count([[self viewControllers] count]);
6552 for (size_t i(0); i != count; ++i) {
6553 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6558 - (id) initWithDatabase:(Database *)database {
6559 if ((self = [super init]) != nil) {
6560 database_ = database;
6567 /* Cydia Navigation Controller {{{ */
6568 @interface CYNavigationController : UINavigationController {
6569 _transient Database *database_;
6570 id<UINavigationControllerDelegate> delegate_;
6573 - (id) initWithDatabase:(Database *)database;
6574 - (void) reloadData;
6579 @implementation CYNavigationController
6581 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6582 // Inherit autorotation settings for modal parents.
6583 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6584 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6586 return [super shouldAutorotateToInterfaceOrientation:orientation];
6594 - (void) reloadData {
6595 size_t count([[self viewControllers] count]);
6596 for (size_t i(0); i != count; ++i) {
6597 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6602 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6603 delegate_ = delegate;
6606 - (id) initWithDatabase:(Database *)database {
6607 if ((self = [super init]) != nil) {
6608 database_ = database;
6614 /* Cydia:// Protocol {{{ */
6615 @interface CydiaURLProtocol : NSURLProtocol {
6620 @implementation CydiaURLProtocol
6622 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6623 NSURL *url([request URL]);
6626 NSString *scheme([[url scheme] lowercaseString]);
6627 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6632 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6636 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6637 id<NSURLProtocolClient> client([self client]);
6639 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6641 NSData *data(UIImagePNGRepresentation(icon));
6643 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6644 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6645 [client URLProtocol:self didLoadData:data];
6646 [client URLProtocolDidFinishLoading:self];
6650 - (void) startLoading {
6651 id<NSURLProtocolClient> client([self client]);
6652 NSURLRequest *request([self request]);
6654 NSURL *url([request URL]);
6655 NSString *href([url absoluteString]);
6657 NSString *path([href substringFromIndex:8]);
6658 NSRange slash([path rangeOfString:@"/"]);
6661 if (slash.location == NSNotFound) {
6665 command = [path substringToIndex:slash.location];
6666 path = [path substringFromIndex:(slash.location + 1)];
6669 Database *database([Database sharedInstance]);
6671 if ([command isEqualToString:@"package-icon"]) {
6674 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6675 Package *package([database packageWithName:path]);
6678 UIImage *icon([package icon]);
6679 [self _returnPNGWithImage:icon forRequest:request];
6680 } else if ([command isEqualToString:@"source-icon"]) {
6683 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6684 NSString *source(Simplify(path));
6685 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6687 icon = [UIImage applicationImageNamed:@"unknown.png"];
6688 [self _returnPNGWithImage:icon forRequest:request];
6689 } else if ([command isEqualToString:@"uikit-image"]) {
6692 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6693 UIImage *icon(_UIImageWithName(path));
6694 [self _returnPNGWithImage:icon forRequest:request];
6695 } else if ([command isEqualToString:@"section-icon"]) {
6698 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6699 NSString *section(Simplify(path));
6700 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6702 icon = [UIImage applicationImageNamed:@"unknown.png"];
6703 [self _returnPNGWithImage:icon forRequest:request];
6705 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6709 - (void) stopLoading {
6715 /* Sections Controller {{{ */
6716 @interface SectionsController : CYViewController <
6717 UITableViewDataSource,
6720 _transient Database *database_;
6721 NSMutableArray *sections_;
6722 NSMutableArray *filtered_;
6728 - (id) initWithDatabase:(Database *)database;
6729 - (void) reloadData;
6732 - (void) editButtonClicked;
6736 @implementation SectionsController
6739 [list_ setDataSource:nil];
6740 [list_ setDelegate:nil];
6742 [sections_ release];
6743 [filtered_ release];
6745 [accessory_ release];
6749 - (void) viewDidAppear:(BOOL)animated {
6750 [super viewDidAppear:animated];
6751 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6754 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6755 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6759 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6760 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6763 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6767 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6768 static NSString *reuseIdentifier = @"SectionCell";
6770 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6771 if (cell == nil) cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6772 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6777 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6781 Section *section = [self sectionAtIndexPath:indexPath];
6782 NSString *name = [section name];
6785 if ([indexPath row] == 0) {
6788 title = UCLocalize("ALL_PACKAGES");
6791 name = [NSString stringWithString:name];
6792 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6795 title = UCLocalize("NO_SECTION");
6799 FilteredPackageController *table = [[[FilteredPackageController alloc]
6800 initWithDatabase:database_
6802 filter:@selector(isVisibleInSection:)
6806 [table setDelegate:delegate_];
6808 [[self navigationController] pushViewController:table animated:YES];
6811 - (NSString *) title { return UCLocalize("SECTIONS"); }
6813 - (id) initWithDatabase:(Database *)database {
6814 if ((self = [super init]) != nil) {
6815 database_ = database;
6817 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6819 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6820 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6822 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6823 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6824 [list_ setRowHeight:45.0f];
6825 [[self view] addSubview:list_];
6827 [list_ setDataSource:self];
6828 [list_ setDelegate:self];
6834 - (void) reloadData {
6835 NSArray *packages = [database_ packages];
6837 [sections_ removeAllObjects];
6838 [filtered_ removeAllObjects];
6841 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6842 SectionMap sections;
6843 sections.resize(64);
6845 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6849 for (Package *package in packages) {
6850 NSString *name([package section]);
6851 NSString *key(name == nil ? @"" : name);
6856 _profile(SectionsView$reloadData$Section)
6857 section = §ions[key];
6858 if (*section == nil) {
6859 _profile(SectionsView$reloadData$Section$Allocate)
6860 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6865 [*section addToCount];
6867 _profile(SectionsView$reloadData$Filter)
6868 if (![package valid] || ![package visible])
6872 [*section addToRow];
6876 _profile(SectionsView$reloadData$Section)
6877 section = [sections objectForKey:key];
6878 if (section == nil) {
6879 _profile(SectionsView$reloadData$Section$Allocate)
6880 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6881 [sections setObject:section forKey:key];
6886 [section addToCount];
6888 _profile(SectionsView$reloadData$Filter)
6889 if (![package valid] || ![package visible])
6899 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6900 [sections_ addObject:i->second];
6902 [sections_ addObjectsFromArray:[sections allValues]];
6905 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6907 for (Section *section in sections_) {
6908 size_t count([section row]);
6912 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6913 [section setCount:count];
6914 [filtered_ addObject:section];
6917 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6918 initWithTitle:[sections_ count] == 0 ? nil : UCLocalize("EDIT")
6919 style:UIBarButtonItemStylePlain
6921 action:@selector(editButtonClicked)
6923 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] != nil];
6924 [rightItem release];
6930 - (void) resetView {
6932 [self editButtonClicked];
6935 - (void) editButtonClicked {
6936 if ((editing_ = !editing_))
6939 [delegate_ updateData];
6941 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6942 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6943 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6946 - (UIView *) accessoryView {
6952 /* Changes Controller {{{ */
6953 @interface ChangesController : CYViewController <
6954 UITableViewDataSource,
6957 _transient Database *database_;
6958 NSMutableArray *packages_;
6959 NSMutableArray *sections_;
6962 BOOL hasSentFirstLoad_;
6965 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6966 - (void) reloadData;
6970 @implementation ChangesController
6973 [list_ setDelegate:nil];
6974 [list_ setDataSource:nil];
6976 [packages_ release];
6977 [sections_ release];
6982 - (void) viewDidAppear:(BOOL)animated {
6983 [super viewDidAppear:animated];
6984 if (!hasSentFirstLoad_) {
6985 hasSentFirstLoad_ = YES;
6986 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6988 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6992 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6993 NSInteger count([sections_ count]);
6994 return count == 0 ? 1 : count;
6997 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6998 if ([sections_ count] == 0)
7000 return [[sections_ objectAtIndex:section] name];
7003 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7004 if ([sections_ count] == 0)
7006 return [[sections_ objectAtIndex:section] count];
7009 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7010 Section *section([sections_ objectAtIndex:[path section]]);
7011 NSInteger row([path row]);
7012 return [packages_ objectAtIndex:([section row] + row)];
7015 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7016 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7018 cell = [[[PackageCell alloc] init] autorelease];
7019 [cell setPackage:[self packageAtIndexPath:path]];
7023 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7024 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7027 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7028 Package *package([self packageAtIndexPath:path]);
7029 PackageController *view([delegate_ packageController]);
7030 [view setDelegate:delegate_];
7031 [view setPackage:package];
7032 [[self navigationController] pushViewController:view animated:YES];
7036 - (void) refreshButtonClicked {
7037 [delegate_ beginUpdate];
7038 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7041 - (void) upgradeButtonClicked {
7042 [delegate_ distUpgrade];
7045 - (NSString *) title { return UCLocalize("CHANGES"); }
7047 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7048 if ((self = [super init]) != nil) {
7049 database_ = database;
7050 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7052 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
7053 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7055 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7056 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7057 [list_ setRowHeight:73.0f];
7058 [[self view] addSubview:list_];
7060 [list_ setDataSource:self];
7061 [list_ setDelegate:self];
7063 delegate_ = delegate;
7067 - (void) _reloadPackages:(NSArray *)packages {
7069 for (Package *package in packages)
7071 [package uninstalled] && [package valid] && [package visible] ||
7072 [package upgradableAndEssential:YES]
7074 [packages_ addObject:package];
7077 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7081 - (void) reloadData {
7082 NSArray *packages = [database_ packages];
7084 [packages_ removeAllObjects];
7085 [sections_ removeAllObjects];
7087 UIProgressHUD *hud([delegate_ addProgressHUD]);
7089 [hud setText:@"Loading Changes"];
7090 //NSLog(@"HUD:%@::%@", delegate_, hud);
7091 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7092 [delegate_ removeProgressHUD:hud];
7094 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7095 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7096 Section *section = nil;
7100 bool unseens = false;
7102 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7104 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7105 Package *package = [packages_ objectAtIndex:offset];
7107 BOOL uae = [package upgradableAndEssential:YES];
7113 _profile(ChangesController$reloadData$Remember)
7114 seen = [package seen];
7117 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7122 name = UCLocalize("UNKNOWN");
7124 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7128 _profile(ChangesController$reloadData$Allocate)
7129 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7130 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7131 [sections_ addObject:section];
7135 [section addToCount];
7136 } else if ([package ignored])
7137 [ignored addToCount];
7140 [upgradable addToCount];
7145 CFRelease(formatter);
7148 Section *last = [sections_ lastObject];
7149 size_t count = [last count];
7150 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7151 [sections_ removeLastObject];
7154 if ([ignored count] != 0)
7155 [sections_ insertObject:ignored atIndex:0];
7157 [sections_ insertObject:upgradable atIndex:0];
7161 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7162 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7163 style:UIBarButtonItemStylePlain
7165 action:@selector(upgradeButtonClicked)
7167 if (upgrades_ > 0) [[self navigationItem] setRightBarButtonItem:rightItem];
7168 [rightItem release];
7170 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
7171 initWithTitle:UCLocalize("REFRESH")
7172 style:UIBarButtonItemStylePlain
7174 action:@selector(refreshButtonClicked)
7176 if (![delegate_ updating]) [[self navigationItem] setLeftBarButtonItem:leftItem];
7182 /* Search Controller {{{ */
7183 @interface SearchController : FilteredPackageController <
7186 UISearchBar *search_;
7189 - (id) initWithDatabase:(Database *)database;
7190 - (void) reloadData;
7194 @implementation SearchController
7201 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7202 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7203 [search_ resignFirstResponder];
7207 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7208 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7212 - (NSString *) title { return nil; }
7214 - (id) initWithDatabase:(Database *)database {
7215 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7218 - (void)viewDidAppear:(BOOL)animated {
7219 [super viewDidAppear:animated];
7221 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7222 [search_ layoutSubviews];
7223 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7224 UITextField *textField = [search_ searchField];
7225 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7226 [search_ setDelegate:self];
7227 [textField setEnablesReturnKeyAutomatically:NO];
7228 [[self navigationItem] setTitleView:textField];
7232 - (void) _reloadData {
7235 - (void) reloadData {
7236 _profile(SearchController$reloadData)
7237 [packages_ reloadData];
7240 [packages_ resetCursor];
7243 - (void) didSelectPackage:(Package *)package {
7244 [search_ resignFirstResponder];
7245 [super didSelectPackage:package];
7250 /* Settings Controller {{{ */
7251 @interface SettingsController : CYViewController <
7252 UITableViewDataSource,
7255 _transient Database *database_;
7258 UITableView *table_;
7259 id subscribedSwitch_;
7261 UITableViewCell *subscribedCell_;
7262 UITableViewCell *ignoredCell_;
7265 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7269 @implementation SettingsController
7273 if (package_ != nil)
7276 [subscribedSwitch_ release];
7277 [ignoredSwitch_ release];
7278 [subscribedCell_ release];
7279 [ignoredCell_ release];
7284 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7285 if (package_ == nil)
7291 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7292 if (package_ == nil)
7298 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7299 return UCLocalize("SHOW_ALL_CHANGES_EX");
7302 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7303 if (package_ == nil)
7306 NSMutableDictionary *metadata([package_ metadata]);
7309 if (NSNumber *number = [metadata objectForKey:key])
7310 before = [number boolValue];
7314 if (value != before) {
7315 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7317 [delegate_ updateData];
7321 - (void) onSubscribed:(id)control {
7322 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7325 - (void) onIgnored:(id)control {
7326 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
7329 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7330 if (package_ == nil)
7333 switch ([indexPath row]) {
7334 case 0: return subscribedCell_;
7335 case 1: return ignoredCell_;
7343 - (NSString *) title { return UCLocalize("SETTINGS"); }
7345 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7346 if ((self = [super init])) {
7347 database_ = database;
7348 name_ = [package retain];
7350 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7352 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7353 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7354 [[self view] addSubview:table_];
7356 subscribedSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7357 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7358 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7360 ignoredSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7361 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7362 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7364 subscribedCell_ = [[UITableViewCell alloc] init];
7365 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7366 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7367 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7369 ignoredCell_ = [[UITableViewCell alloc] init];
7370 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7371 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7372 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7374 [table_ setDataSource:self];
7375 [table_ setDelegate:self];
7380 - (void) reloadData {
7381 if (package_ != nil)
7382 [package_ autorelease];
7383 package_ = [database_ packageWithName:name_];
7384 if (package_ != nil) {
7386 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7387 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7390 [table_ reloadData];
7395 /* Signature Controller {{{ */
7396 @interface SignatureController : CYBrowserController {
7397 _transient Database *database_;
7401 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7405 @implementation SignatureController
7412 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7414 [super webView:view didClearWindowObject:window forFrame:frame];
7417 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7418 if ((self = [super init]) != nil) {
7419 database_ = database;
7420 package_ = [package retain];
7425 - (void) reloadData {
7426 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7432 /* Role Controller {{{ */
7433 @interface RoleController : CYViewController <
7434 UITableViewDataSource,
7437 _transient Database *database_;
7439 UITableView *table_;
7440 UISegmentedControl *segment_;
7444 - (void) showDoneButton;
7445 - (void) resizeSegmentedControl;
7449 @implementation RoleController
7453 [container_ release];
7458 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7459 if ((self = [super init])) {
7460 database_ = database;
7461 roledelegate_ = delegate;
7463 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7465 NSArray *items = [NSArray arrayWithObjects:
7467 UCLocalize("HACKER"),
7468 UCLocalize("DEVELOPER"),
7470 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7471 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7472 [container_ addSubview:segment_];
7475 if ([Role_ isEqualToString:@"User"]) index = 0;
7476 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7477 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7479 [segment_ setSelectedSegmentIndex:index];
7480 [self showDoneButton];
7483 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7484 [self resizeSegmentedControl];
7486 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7487 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7488 [table_ setDelegate:self];
7489 [table_ setDataSource:self];
7490 [[self view] addSubview:table_];
7491 [table_ reloadData];
7495 - (void) resizeSegmentedControl {
7496 CGFloat width = [[self view] frame].size.width;
7497 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7500 - (void) viewWillAppear:(BOOL)animated {
7501 [super viewWillAppear:animated];
7503 [self resizeSegmentedControl];
7506 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7507 [self resizeSegmentedControl];
7510 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7511 [self resizeSegmentedControl];
7515 NSString *role(nil);
7517 switch ([segment_ selectedSegmentIndex]) {
7518 case 0: role = @"User"; break;
7519 case 1: role = @"Hacker"; break;
7520 case 2: role = @"Developer"; break;
7525 if (![role isEqualToString:Role_]) {
7526 bool rolling(Role_ == nil);
7529 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7533 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7538 [roledelegate_ loadData];
7540 [roledelegate_ updateData];
7544 - (void) segmentChanged:(UISegmentedControl *)control {
7545 [self showDoneButton];
7548 - (void) doneButtonClicked {
7550 [[self navigationController] dismissModalViewControllerAnimated:YES];
7553 - (void) showDoneButton {
7554 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7555 initWithTitle:UCLocalize("DONE")
7556 style:UIBarButtonItemStyleDone
7558 action:@selector(doneButtonClicked)
7560 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] == nil];
7561 [rightItem release];
7564 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7565 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7569 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7573 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7574 return nil; // This method is required by the protocol.
7577 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7579 return UCLocalize("ROLE_EX");
7581 return [NSString stringWithFormat:
7582 @"%@: %@\n%@: %@\n%@: %@",
7583 UCLocalize("USER"), UCLocalize("USER_EX"),
7584 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7585 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7590 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7591 if (section == 3) return 44.0f;
7595 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7596 if (section == 3) return container_;
7602 /* Stash Controller {{{ */
7603 @interface CYStashController : CYViewController {
7604 UIActivityIndicatorView *spinner_;
7610 @implementation CYStashController
7612 if ((self = [super init])) {
7613 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7615 spinner_ = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
7616 CGRect spinrect = [spinner_ frame];
7617 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7618 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7619 [spinner_ setFrame:spinrect];
7620 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7621 [[self view] addSubview:spinner_];
7623 [spinner_ startAnimating];
7626 captrect.size.width = [[self view] frame].size.width;
7627 captrect.size.height = 40.0f;
7628 captrect.origin.x = 0;
7629 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7630 caption_ = [[UILabel alloc] initWithFrame:captrect];
7631 [caption_ setText:@"Initializing Filesystem"];
7632 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7633 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7634 [caption_ setTextColor:[UIColor whiteColor]];
7635 [caption_ setBackgroundColor:[UIColor clearColor]];
7636 [caption_ setShadowColor:[UIColor blackColor]];
7637 [caption_ setTextAlignment:UITextAlignmentCenter];
7638 [[self view] addSubview:caption_];
7642 statusrect.size.width = [[self view] frame].size.width;
7643 statusrect.size.height = 30.0f;
7644 statusrect.origin.x = 0;
7645 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7646 status_ = [[UILabel alloc] initWithFrame:statusrect];
7647 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7648 [status_ setText:@"(Cydia will exit when complete.)"];
7649 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7650 [status_ setTextColor:[UIColor whiteColor]];
7651 [status_ setBackgroundColor:[UIColor clearColor]];
7652 [status_ setShadowColor:[UIColor blackColor]];
7653 [status_ setTextAlignment:UITextAlignmentCenter];
7654 [[self view] addSubview:status_];
7659 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7660 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7665 /* Cydia Container {{{ */
7666 @interface CYContainer : UIViewController <ProgressDelegate> {
7667 _transient Database *database_;
7668 RefreshBar *refreshbar_;
7673 UITabBarController *root_;
7676 - (void) setTabBarController:(UITabBarController *)controller;
7678 - (void) dropBar:(BOOL)animated;
7679 - (void) beginUpdate;
7680 - (void) raiseBar:(BOOL)animated;
7685 @implementation CYContainer
7687 - (BOOL) _reallyWantsFullScreenLayout {
7691 // NOTE: UIWindow only sends the top controller these messages,
7692 // So we have to forward them on.
7694 - (void) viewDidAppear:(BOOL)animated {
7695 [super viewDidAppear:animated];
7696 [root_ viewDidAppear:animated];
7699 - (void) viewWillAppear:(BOOL)animated {
7700 [super viewWillAppear:animated];
7701 [root_ viewWillAppear:animated];
7704 - (void) viewDidDisappear:(BOOL)animated {
7705 [super viewDidDisappear:animated];
7706 [root_ viewDidDisappear:animated];
7709 - (void) viewWillDisappear:(BOOL)animated {
7710 [super viewWillDisappear:animated];
7711 [root_ viewWillDisappear:animated];
7714 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7715 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7718 - (void) setTabBarController:(UITabBarController *)controller {
7720 [[self view] addSubview:[root_ view]];
7723 - (void) setUpdate:(NSDate *)date {
7727 - (void) beginUpdate {
7729 [refreshbar_ start];
7734 detachNewThreadSelector:@selector(performUpdate)
7740 - (void) performUpdate { _pooled
7742 status.setDelegate(self);
7743 [database_ updateWithStatus:status];
7746 performSelectorOnMainThread:@selector(completeUpdate)
7752 - (void) completeUpdate {
7753 if (!updating_) return;
7756 [self raiseBar:YES];
7758 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7761 - (void) cancelUpdate {
7763 [self raiseBar:YES];
7765 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7768 - (void) cancelPressed {
7769 [self cancelUpdate];
7776 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7777 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7780 - (void) startProgress {
7783 - (void) setProgressTitle:(NSString *)title {
7785 performSelectorOnMainThread:@selector(_setProgressTitle:)
7791 - (bool) isCancelling:(size_t)received {
7795 - (void) setProgressPercent:(float)percent {
7797 performSelectorOnMainThread:@selector(_setProgressPercent:)
7798 withObject:[NSNumber numberWithFloat:percent]
7803 - (void) addProgressOutput:(NSString *)output {
7805 performSelectorOnMainThread:@selector(_addProgressOutput:)
7811 - (void) _setProgressTitle:(NSString *)title {
7812 [refreshbar_ setPrompt:title];
7815 - (void) _setProgressPercent:(NSNumber *)percent {
7816 [refreshbar_ setProgress:[percent floatValue]];
7819 - (void) _addProgressOutput:(NSString *)output {
7822 - (void) setUpdateDelegate:(id)delegate {
7823 updatedelegate_ = delegate;
7826 - (CGFloat) statusBarHeight {
7827 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7828 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7830 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7834 - (void) dropBar:(BOOL)animated {
7835 if (dropped_) return;
7838 [[self view] addSubview:refreshbar_];
7840 CGFloat sboffset = [self statusBarHeight];
7842 CGRect barframe = [refreshbar_ frame];
7843 barframe.origin.y = sboffset;
7844 [refreshbar_ setFrame:barframe];
7846 if (animated) [UIView beginAnimations:nil context:NULL];
7847 CGRect viewframe = [[root_ view] frame];
7848 viewframe.origin.y += barframe.size.height + sboffset;
7849 viewframe.size.height -= barframe.size.height + sboffset;
7850 [[root_ view] setFrame:viewframe];
7851 if (animated) [UIView commitAnimations];
7853 // Ensure bar has the proper width for our view, it might have changed
7854 barframe.size.width = viewframe.size.width;
7855 [refreshbar_ setFrame:barframe];
7857 // XXX: fix Apple's layout bug
7858 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7861 - (void) raiseBar:(BOOL)animated {
7862 if (!dropped_) return;
7865 [refreshbar_ removeFromSuperview];
7867 CGFloat sboffset = [self statusBarHeight];
7869 if (animated) [UIView beginAnimations:nil context:NULL];
7870 CGRect barframe = [refreshbar_ frame];
7871 CGRect viewframe = [[root_ view] frame];
7872 viewframe.origin.y -= barframe.size.height + sboffset;
7873 viewframe.size.height += barframe.size.height + sboffset;
7874 [[root_ view] setFrame:viewframe];
7875 if (animated) [UIView commitAnimations];
7877 // XXX: fix Apple's layout bug
7878 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7881 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7882 // XXX: fix Apple's layout bug
7883 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7886 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7892 // XXX: fix Apple's layout bug
7893 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7896 - (void) statusBarFrameChanged:(NSNotification *)notification {
7904 [refreshbar_ release];
7905 [[NSNotificationCenter defaultCenter] removeObserver:self];
7909 - (id) initWithDatabase:(Database *)database {
7910 if ((self = [super init]) != nil) {
7911 database_ = database;
7913 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7914 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7916 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7933 @interface Cydia : UIApplication <
7934 ConfirmationControllerDelegate,
7935 ProgressControllerDelegate,
7937 UINavigationControllerDelegate
7940 CYContainer *container_;
7943 NSMutableArray *essential_;
7944 NSMutableArray *broken_;
7946 Database *database_;
7950 UIKeyboard *keyboard_;
7951 UIProgressHUD *hud_;
7953 SectionsController *sections_;
7954 ChangesController *changes_;
7955 ManageController *manage_;
7956 SearchController *search_;
7957 SourceTable *sources_;
7958 InstalledController *installed_;
7961 CYStashController *stash_;
7966 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7967 - (void) setPage:(CYViewController *)page;
7972 static _finline void _setHomePage(Cydia *self) {
7973 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7976 @implementation Cydia
7978 - (void) beginUpdate {
7979 [container_ beginUpdate];
7983 return [container_ updating];
7986 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7991 if ([broken_ count] != 0) {
7992 int count = [broken_ count];
7994 UIAlertView *alert = [[[UIAlertView alloc]
7995 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7996 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7998 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7999 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8002 [alert setContext:@"fixhalf"];
8004 } else if (!Ignored_ && [essential_ count] != 0) {
8005 int count = [essential_ count];
8007 UIAlertView *alert = [[[UIAlertView alloc]
8008 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8009 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8011 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8012 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8015 [alert setContext:@"upgrade"];
8020 - (void) _saveConfig {
8023 NSString *error(nil);
8024 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8026 NSError *error(nil);
8027 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8028 NSLog(@"failure to save metadata data: %@", error);
8031 NSLog(@"failure to serialize metadata: %@", error);
8039 - (void) _updateData {
8042 /* XXX: this is just stupid */
8043 if (tag_ != 1 && sections_ != nil)
8044 [sections_ reloadData];
8045 if (tag_ != 2 && changes_ != nil)
8046 [changes_ reloadData];
8047 if (tag_ != 4 && search_ != nil)
8048 [search_ reloadData];
8050 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8053 - (int)indexOfTabWithTag:(int)tag {
8055 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8056 if ([[controller tabBarItem] tag] == tag) return i;
8063 - (void) _refreshIfPossible {
8064 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8066 bool recently = false;
8067 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8068 if (update != nil) {
8069 NSTimeInterval interval([update timeIntervalSinceNow]);
8070 if (interval <= 0 && interval > -(15*60))
8074 // Don't automatic refresh if:
8075 // - We already refreshed recently.
8076 // - We already auto-refreshed this launch.
8077 // - Auto-refresh is disabled.
8078 if (recently || loaded_ || ManualRefresh) {
8079 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8081 // If we are cancelling due to ManualRefresh or a recent refresh
8082 // we need to make sure it knows it's already loaded.
8086 // We are going to load, so remember that.
8090 SCNetworkReachabilityFlags flags; {
8091 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8092 SCNetworkReachabilityGetFlags(reachability, &flags);
8093 CFRelease(reachability);
8096 // XXX: this elaborate mess is what Apple is using to determine this? :(
8097 // XXX: do we care if the user has to intervene? maybe that's ok?
8099 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8100 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8101 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8102 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8103 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8104 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8108 // If we can reach the server, auto-refresh!
8110 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8115 - (void) refreshIfPossible {
8116 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8119 - (void) _reloadData {
8120 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8121 [hud setText:UCLocalize("RELOADING_DATA")];
8123 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8126 if (hud) [self removeProgressHUD:hud];
8130 [essential_ removeAllObjects];
8131 [broken_ removeAllObjects];
8133 NSArray *packages([database_ packages]);
8134 for (Package *package in packages) {
8136 [broken_ addObject:package];
8137 if ([package upgradableAndEssential:NO]) {
8138 if ([package essential])
8139 [essential_ addObject:package];
8144 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8146 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8147 [changesItem setBadgeValue:badge];
8148 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8150 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8151 [self setApplicationBadge:badge];
8153 [self setApplicationBadgeString:badge];
8155 [changesItem setBadgeValue:nil];
8156 [changesItem setAnimatedBadge:NO];
8158 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8159 [self removeApplicationBadge];
8160 else // XXX: maybe use setApplicationBadgeString also?
8161 [self setApplicationIconBadgeNumber:0];
8166 [self refreshIfPossible];
8169 - (void) updateData {
8170 [database_ setVisible];
8179 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8180 _assert(file != NULL);
8182 for (NSString *key in [Sources_ allKeys]) {
8183 NSDictionary *source([Sources_ objectForKey:key]);
8185 fprintf(file, "%s %s %s\n",
8186 [[source objectForKey:@"Type"] UTF8String],
8187 [[source objectForKey:@"URI"] UTF8String],
8188 [[source objectForKey:@"Distribution"] UTF8String]
8196 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8197 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8198 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8199 [container_ presentModalViewController:navigation animated:YES];
8202 detachNewThreadSelector:@selector(update_)
8205 title:UCLocalize("UPDATING_SOURCES")
8209 - (void) reloadData {
8210 @synchronized (self) {
8216 pkgProblemResolver *resolver = [database_ resolver];
8218 resolver->InstallProtect();
8219 if (!resolver->Resolve(true))
8223 - (CGRect) popUpBounds {
8224 return [[tabbar_ view] bounds];
8228 if (![database_ prepare])
8231 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8232 [page setDelegate:self];
8233 CYNavigationController *confirm_ = [[CYNavigationController alloc] initWithRootViewController:page];
8234 [confirm_ setDelegate:self];
8236 if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8237 [container_ presentModalViewController:confirm_ animated:YES];
8243 @synchronized (self) {
8248 - (void) clearPackage:(Package *)package {
8249 @synchronized (self) {
8256 - (void) installPackages:(NSArray *)packages {
8257 @synchronized (self) {
8258 for (Package *package in packages)
8265 - (void) installPackage:(Package *)package {
8266 @synchronized (self) {
8273 - (void) removePackage:(Package *)package {
8274 @synchronized (self) {
8281 - (void) distUpgrade {
8282 @synchronized (self) {
8283 if (![database_ upgrade])
8290 @synchronized (self) {
8295 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8296 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8298 if (navigation != nil) {
8299 [navigation pushViewController:progress animated:YES];
8301 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8302 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8303 [container_ presentModalViewController:navigation animated:YES];
8307 detachNewThreadSelector:@selector(perform)
8310 title:UCLocalize("RUNNING")
8314 - (void) progressControllerIsComplete:(ProgressController *)progress {
8318 - (void) setPage:(CYViewController *)page {
8319 [page setDelegate:self];
8321 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8322 [navController setViewControllers:[NSArray arrayWithObject:page]];
8323 for (CYNavigationController *page in [tabbar_ viewControllers]) {
8324 if (page != navController) [page setViewControllers:nil];
8328 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8329 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8330 [browser loadURL:url];
8334 - (SectionsController *) sectionsController {
8335 if (sections_ == nil)
8336 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8340 - (ChangesController *) changesController {
8341 if (changes_ == nil)
8342 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8346 - (ManageController *) manageController {
8347 if (manage_ == nil) {
8348 manage_ = (ManageController *) [[self
8349 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8350 withClass:[ManageController class]
8352 if (!IsWildcat_) queueDelegate_ = manage_;
8357 - (SearchController *) searchController {
8359 search_ = [[SearchController alloc] initWithDatabase:database_];
8363 - (SourceTable *) sourcesController {
8364 if (sources_ == nil)
8365 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8369 - (InstalledController *) installedController {
8370 if (installed_ == nil) {
8371 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8372 if (IsWildcat_) queueDelegate_ = installed_;
8377 - (void) tabBarController:(id)tabBarController didSelectViewController:(UIViewController *)viewController {
8378 int tag = [[viewController tabBarItem] tag];
8380 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8382 } else if (tag_ == 1) {
8383 [[self sectionsController] resetView];
8387 case kCydiaTag: _setHomePage(self); break;
8389 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8390 case kChangesTag: [self setPage:[self changesController]]; break;
8391 case kManageTag: [self setPage:[self manageController]]; break;
8392 case kInstalledTag: [self setPage:[self installedController]]; break;
8393 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8394 case kSearchTag: [self setPage:[self searchController]]; break;
8402 - (void) showSettings {
8403 RoleController *role = [[RoleController alloc] initWithDatabase:database_ delegate:self];
8404 CYNavigationController *nav = [[CYNavigationController alloc] initWithRootViewController:role];
8405 if (IsWildcat_) [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8406 [container_ presentModalViewController:nav animated:YES];
8409 - (void) setPackageController:(PackageController *)view {
8411 [view setPackage:nil];
8415 - (PackageController *) _packageController {
8416 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8419 - (PackageController *) packageController {
8420 return [self _packageController];
8423 // Returns the navigation controller for the queuing badge.
8424 - (id) queueBadgeController {
8425 int index = [self indexOfTabWithTag:kManageTag];
8426 if (index == -1) index = [self indexOfTabWithTag:kInstalledTag];
8428 return [[tabbar_ viewControllers] objectAtIndex:index];
8431 - (void) cancelAndClear:(bool)clear {
8432 @synchronized (self) {
8435 pkgCacheFile &cache([database_ cache]);
8436 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
8437 // Unmark method taken from Synaptic Package Manager.
8438 // Thanks for being sane, unlike Aptitude.
8439 if (!cache[iterator].Keep()) {
8440 cache->MarkKeep(iterator, false);
8441 cache->SetReInstall(iterator, false);
8447 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
8451 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8454 // Show the changes in the current view.
8455 [(CYNavigationController *) [tabbar_ selectedViewController] reloadData];
8456 [queueDelegate_ queueStatusDidChange];
8460 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8461 NSString *context([alert context]);
8463 if ([context isEqualToString:@"fixhalf"]) {
8464 if (button == [alert firstOtherButtonIndex]) {
8465 @synchronized (self) {
8466 for (Package *broken in broken_) {
8469 NSString *id = [broken id];
8470 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8471 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8472 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8473 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8479 } else if (button == [alert cancelButtonIndex]) {
8480 [broken_ removeAllObjects];
8484 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8485 } else if ([context isEqualToString:@"upgrade"]) {
8486 if (button == [alert firstOtherButtonIndex]) {
8487 @synchronized (self) {
8488 for (Package *essential in essential_)
8489 [essential install];
8494 } else if (button == [alert firstOtherButtonIndex] + 1) {
8496 } else if (button == [alert cancelButtonIndex]) {
8500 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8504 - (void) system:(NSString *)command { _pooled
8505 system([command UTF8String]);
8508 - (void) applicationWillSuspend {
8510 [super applicationWillSuspend];
8513 - (void) applicationSuspend:(__GSEvent *)event {
8514 // Use external process status API internally.
8515 // This is probably a really bad idea.
8516 uint64_t status = 0;
8518 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8519 notify_get_state(notify_token, &status);
8520 notify_cancel(notify_token);
8523 if (hud_ == nil && status == 0)
8524 [super applicationSuspend:event];
8527 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8529 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8532 - (void) _setSuspended:(BOOL)value {
8534 [super _setSuspended:value];
8537 - (UIProgressHUD *) addProgressHUD {
8538 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8539 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8541 [window_ setUserInteractionEnabled:NO];
8544 UIViewController *target = container_;
8545 while ([target modalViewController] != nil) target = [target modalViewController];
8546 [[target view] addSubview:hud];
8551 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8553 [hud removeFromSuperview];
8554 [window_ setUserInteractionEnabled:YES];
8557 - (CYViewController *) pageForPackage:(NSString *)name {
8558 if (Package *package = [database_ packageWithName:name]) {
8559 PackageController *view([self packageController]);
8560 [view setPackage:package];
8563 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8564 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8565 return [self _pageForURL:url withClass:[CYBrowserController class]];
8569 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8573 NSString *href([url absoluteString]);
8574 if ([href hasPrefix:@"apptapp://package/"])
8575 return [self pageForPackage:[href substringFromIndex:18]];
8577 NSString *scheme([[url scheme] lowercaseString]);
8578 if (![scheme isEqualToString:@"cydia"])
8580 NSString *path([url absoluteString]);
8581 if ([path length] < 8)
8583 path = [path substringFromIndex:8];
8584 if (![path hasPrefix:@"/"])
8585 path = [@"/" stringByAppendingString:path];
8587 if ([path isEqualToString:@"/add-source"])
8588 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8589 else if ([path isEqualToString:@"/storage"])
8590 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8591 else if ([path isEqualToString:@"/sources"])
8592 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8593 else if ([path isEqualToString:@"/packages"])
8594 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8595 else if ([path hasPrefix:@"/url/"])
8596 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8597 else if ([path hasPrefix:@"/launch/"])
8598 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8599 else if ([path hasPrefix:@"/package-settings/"])
8600 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8601 else if ([path hasPrefix:@"/package-signature/"])
8602 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8603 else if ([path hasPrefix:@"/package/"])
8604 return [self pageForPackage:[path substringFromIndex:9]];
8605 else if ([path hasPrefix:@"/files/"]) {
8606 NSString *name = [path substringFromIndex:7];
8608 if (Package *package = [database_ packageWithName:name]) {
8609 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8610 [files setPackage:package];
8618 - (void) applicationOpenURL:(NSURL *)url {
8619 [super applicationOpenURL:url];
8621 if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
8622 [self setPage:page];
8624 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8628 - (void) applicationWillResignActive:(UIApplication *)application {
8629 // Stop refreshing if you get a phone call or lock the device.
8630 if ([container_ updating]) [container_ cancelUpdate];
8632 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8633 [super applicationWillResignActive:application];
8636 - (void) addStashController {
8637 stash_ = [[CYStashController alloc] init];
8638 [window_ addSubview:[stash_ view]];
8641 - (void) removeStashController {
8642 [[stash_ view] removeFromSuperview];
8647 [self setIdleTimerDisabled:YES];
8649 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8650 [self setStatusBarShowsProgress:YES];
8651 UpdateExternalStatus(1);
8653 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8655 UpdateExternalStatus(0);
8656 [self setStatusBarShowsProgress:NO];
8658 [self removeStashController];
8660 if (ExecFork() == 0) {
8661 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8662 perror("launchctl stop");
8666 - (void) setupTabBarController {
8667 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8668 [tabbar_ setDelegate:self];
8670 NSMutableArray *items([NSMutableArray arrayWithObjects:
8671 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8672 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8673 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8674 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8678 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8679 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8681 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8684 NSMutableArray *controllers([NSMutableArray array]);
8686 for (UITabBarItem *item in items) {
8687 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8688 [controller setTabBarItem:item];
8689 [controllers addObject:controller];
8692 [tabbar_ setViewControllers:controllers];
8693 [tabbar_ setSelectedIndex:0];
8696 - (void) applicationDidFinishLaunching:(id)unused {
8697 [CYBrowserController _initialize];
8699 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8701 Font12_ = [[UIFont systemFontOfSize:12] retain];
8702 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8703 Font14_ = [[UIFont systemFontOfSize:14] retain];
8704 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8705 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8709 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8710 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8712 UIScreen *screen([UIScreen mainScreen]);
8714 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8715 [window_ orderFront:self];
8716 [window_ makeKey:self];
8717 [window_ setHidden:NO];
8720 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8721 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8722 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8723 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8724 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8725 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8726 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8727 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8728 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8731 [self addStashController];
8732 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8736 database_ = [Database sharedInstance];
8738 [self setupTabBarController];
8740 container_ = [[CYContainer alloc] initWithDatabase:database_];
8741 [container_ setUpdateDelegate:self];
8742 [container_ setTabBarController:tabbar_];
8743 [window_ addSubview:[container_ view]];
8745 // Show pinstripes while loading data.
8746 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8748 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8753 [self showSettings];
8757 [UIKeyboard initImplementationNow];
8759 [window_ setUserInteractionEnabled:NO];
8761 UIView *container = [[UIView alloc] init];
8762 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8764 UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
8765 [spinner startAnimating];
8766 [container addSubview:spinner];
8769 UILabel *label = [[UILabel alloc] init];
8770 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8771 [label setBackgroundColor:[UIColor clearColor]];
8772 [label setTextColor:[UIColor blackColor]];
8773 [label setShadowColor:[UIColor whiteColor]];
8774 [label setShadowOffset:CGSizeMake(0, 1)];
8775 [label setText:UCLocalize("LOADING_DATA")];
8776 [container addSubview:label];
8779 CGSize viewsize = [[tabbar_ view] frame].size;
8780 CGSize spinnersize = [spinner bounds].size;
8781 CGSize textsize = [[label text] sizeWithFont:[label font]];
8782 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8784 CGRect containrect = {
8785 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8786 CGSizeMake(bothwidth, spinnersize.height)
8789 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8797 [container setFrame:containrect];
8798 [spinner setFrame:spinrect];
8799 [label setFrame:textrect];
8800 [[container_ view] addSubview:container];
8801 [container release];
8806 // Show the home page
8808 [window_ setUserInteractionEnabled:YES];
8810 // XXX: does this actually slow anything down?
8811 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8812 [container removeFromSuperview];
8815 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8816 if (item != nil && IsWildcat_) {
8817 [sheet showFromBarButtonItem:item animated:YES];
8819 [sheet showInView:window_];
8826 id Alloc_(id self, SEL selector) {
8827 id object = alloc_(self, selector);
8828 lprintf("[%s]A-%p\n", self->isa->name, object);
8833 id Dealloc_(id self, SEL selector) {
8834 id object = dealloc_(self, selector);
8835 lprintf("[%s]D-%p\n", self->isa->name, object);
8839 Class $WebDefaultUIKitDelegate;
8841 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8842 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8843 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8844 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8847 static NSNumber *shouldPlayKeyboardSounds;
8851 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8853 case 1104: // Keyboard Button Clicked
8854 case 1105: // Keyboard Delete Repeated
8855 if (shouldPlayKeyboardSounds == nil) {
8856 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8857 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8860 if (![shouldPlayKeyboardSounds boolValue])
8864 _UIHardware$_playSystemSound$(self, _cmd, sound);
8868 int main(int argc, char *argv[]) { _pooled
8871 if (Class $UIDevice = objc_getClass("UIDevice")) {
8872 UIDevice *device([$UIDevice currentDevice]);
8873 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8877 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8879 /* Library Hacks {{{ */
8880 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8882 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8883 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8884 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8885 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8886 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8889 $UIHardware = objc_getClass("UIHardware");
8890 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8891 if (UIHardware$_playSystemSound$ != NULL) {
8892 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8893 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8896 /* Set Locale {{{ */
8897 Locale_ = CFLocaleCopyCurrent();
8898 Languages_ = [NSLocale preferredLanguages];
8899 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8900 //NSLog(@"%@", [Languages_ description]);
8903 if (Languages_ == nil || [Languages_ count] == 0)
8904 // XXX: consider just setting to C and then falling through?
8907 lang = [[Languages_ objectAtIndex:0] UTF8String];
8908 setenv("LANG", lang, true);
8911 //std::setlocale(LC_ALL, lang);
8912 NSLog(@"Setting Language: %s", lang);
8915 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8917 /* Parse Arguments {{{ */
8918 bool substrate(false);
8924 for (int argi(1); argi != argc; ++argi)
8925 if (strcmp(argv[argi], "--") == 0) {
8927 argv[argi] = argv[0];
8933 for (int argi(1); argi != arge; ++argi)
8934 if (strcmp(args[argi], "--substrate") == 0)
8937 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8941 App_ = [[NSBundle mainBundle] bundlePath];
8942 Home_ = NSHomeDirectory();
8948 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8949 alloc_ = alloc->method_imp;
8950 alloc->method_imp = (IMP) &Alloc_;*/
8952 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8953 dealloc_ = dealloc->method_imp;
8954 dealloc->method_imp = (IMP) &Dealloc_;*/
8956 /* System Information {{{ */
8960 size = sizeof(maxproc);
8961 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8962 perror("sysctlbyname(\"kern.maxproc\", ?)");
8963 else if (maxproc < 64) {
8965 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8966 perror("sysctlbyname(\"kern.maxproc\", #)");
8969 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8970 char *osversion = new char[size];
8971 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8972 perror("sysctlbyname(\"kern.osversion\", ?)");
8974 System_ = [NSString stringWithUTF8String:osversion];
8976 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8977 char *machine = new char[size];
8978 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8979 perror("sysctlbyname(\"hw.machine\", ?)");
8983 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8984 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8985 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8986 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8990 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8991 NSData *data((NSData *) ecid);
8992 size_t length([data length]);
8993 uint8_t bytes[length];
8994 [data getBytes:bytes];
8995 char string[length * 2 + 1];
8996 for (size_t i(0); i != length; ++i)
8997 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8998 ChipID_ = [NSString stringWithUTF8String:string];
9002 IOObjectRelease(service);
9006 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9008 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9009 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9010 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9012 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9013 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9014 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9016 if (mcc != NULL && mnc != NULL)
9017 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9024 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9025 Build_ = [system objectForKey:@"ProductBuildVersion"];
9026 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9027 Product_ = [info objectForKey:@"SafariProductVersion"];
9028 Safari_ = [info objectForKey:@"CFBundleVersion"];
9031 /* Load Database {{{ */
9033 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9035 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9038 if (Metadata_ == NULL)
9039 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9041 Settings_ = [Metadata_ objectForKey:@"Settings"];
9043 Packages_ = [Metadata_ objectForKey:@"Packages"];
9044 Sections_ = [Metadata_ objectForKey:@"Sections"];
9045 Sources_ = [Metadata_ objectForKey:@"Sources"];
9047 Token_ = [Metadata_ objectForKey:@"Token"];
9050 if (Settings_ != nil)
9051 Role_ = [Settings_ objectForKey:@"Role"];
9053 if (Packages_ == nil) {
9054 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
9055 [Metadata_ setObject:Packages_ forKey:@"Packages"];
9058 if (Sections_ == nil) {
9059 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9060 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9063 if (Sources_ == nil) {
9064 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9065 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9069 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9071 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9072 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9073 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9074 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9075 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9076 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9078 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9080 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9081 unlink("/tmp/.cydia.fw");
9083 } else if (access("/User", F_OK) != 0 || version < 2) {
9086 system("/usr/libexec/cydia/firmware.sh");
9090 _assert([[NSFileManager defaultManager]
9091 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9092 withIntermediateDirectories:YES
9097 if (access("/tmp/cydia.chk", F_OK) == 0) {
9098 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9099 _assert(errno == ENOENT);
9100 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9101 _assert(errno == ENOENT);
9104 /* APT Initialization {{{ */
9105 _assert(pkgInitConfig(*_config));
9106 _assert(pkgInitSystem(*_config, _system));
9109 _config->Set("APT::Acquire::Translation", lang);
9111 // XXX: this timeout might be important :(
9112 //_config->Set("Acquire::http::Timeout", 15);
9114 _config->Set("Acquire::http::MaxParallel", 3);
9116 /* Color Choices {{{ */
9117 space_ = CGColorSpaceCreateDeviceRGB();
9119 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9120 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9121 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9122 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9123 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9124 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9125 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9126 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9127 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9129 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9130 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9132 /* UIKit Configuration {{{ */
9133 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9134 if ($GSFontSetUseLegacyFontMetrics != NULL)
9135 $GSFontSetUseLegacyFontMetrics(YES);
9137 // XXX: I have a feeling this was important
9138 //UIKeyboardDisableAutomaticAppearance();
9141 Colon_ = UCLocalize("COLON_DELIMITED");
9142 Error_ = UCLocalize("ERROR");
9143 Warning_ = UCLocalize("WARNING");
9146 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9148 CGColorSpaceRelease(space_);