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 <UIKit/UIKit.h>
63 #include "iPhonePrivate.h"
65 #include <IOKit/IOKitLib.h>
67 #include <WebCore/WebCoreThread.h>
74 #include <ext/stdio_filebuf.h>
78 #include <apt-pkg/acquire.h>
79 #include <apt-pkg/acquire-item.h>
80 #include <apt-pkg/algorithms.h>
81 #include <apt-pkg/cachefile.h>
82 #include <apt-pkg/clean.h>
83 #include <apt-pkg/configuration.h>
84 #include <apt-pkg/debindexfile.h>
85 #include <apt-pkg/debmetaindex.h>
86 #include <apt-pkg/error.h>
87 #include <apt-pkg/init.h>
88 #include <apt-pkg/mmap.h>
89 #include <apt-pkg/pkgrecords.h>
90 #include <apt-pkg/sha1.h>
91 #include <apt-pkg/sourcelist.h>
92 #include <apt-pkg/sptr.h>
93 #include <apt-pkg/strutl.h>
94 #include <apt-pkg/tagfile.h>
96 #include <apr-1/apr_pools.h>
98 #include <sys/types.h>
100 #include <sys/sysctl.h>
101 #include <sys/param.h>
102 #include <sys/mount.h>
109 #include <mach-o/nlist.h>
119 #include <ext/hash_map>
121 #include "UICaboodle/BrowserView.h"
122 #include "UICaboodle/ResetView.h"
124 #include "substrate.h"
126 // Apple's sample Reachability code, ASPL licensed.
127 #include "Reachability.h"
134 #define _timestamp ({ \
136 gettimeofday(&tv, NULL); \
137 tv.tv_sec * 1000000 + tv.tv_usec; \
140 typedef std::vector<class ProfileTime *> TimeList;
150 ProfileTime(const char *name) :
154 times_.push_back(this);
157 void AddTime(uint64_t time) {
164 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
176 ProfileTimer(ProfileTime &time) :
183 time_.AddTime(_timestamp - start_);
188 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
190 std::cerr << "========" << std::endl;
193 #define _profile(name) { \
194 static ProfileTime name(#name); \
195 ProfileTimer _ ## name(name);
200 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
202 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
204 void NSLogPoint(const char *fix, const CGPoint &point) {
205 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
208 void NSLogRect(const char *fix, const CGRect &rect) {
209 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
212 static _finline NSString *CydiaURL(NSString *path) {
214 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
215 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
216 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
217 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
218 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
219 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
222 static _finline void UpdateExternalStatus(uint64_t newStatus) {
224 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
225 notify_set_state(notify_token, newStatus);
226 notify_cancel(notify_token);
228 notify_post("com.saurik.Cydia.status");
231 /* [NSObject yieldToSelector:(withObject:)] {{{*/
232 @interface NSObject (Cydia)
233 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
234 - (id) yieldToSelector:(SEL)selector;
237 @implementation NSObject (Cydia)
242 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
243 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
244 id object([[context objectAtIndex:1] nonretainedObjectValue]);
245 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
247 /* XXX: deal with exceptions */
248 id value([self performSelector:selector withObject:object]);
250 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
251 [context removeAllObjects];
252 if ([signature methodReturnLength] != 0 && value != nil)
253 [context addObject:value];
258 performSelectorOnMainThread:@selector(doNothing)
264 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
265 /*return [self performSelector:selector withObject:object];*/
267 volatile bool stopped(false);
269 NSMutableArray *context([NSMutableArray arrayWithObjects:
270 [NSValue valueWithPointer:selector],
271 [NSValue valueWithNonretainedObject:object],
272 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
275 NSThread *thread([[[NSThread alloc]
277 selector:@selector(_yieldToContext:)
283 NSRunLoop *loop([NSRunLoop currentRunLoop]);
284 NSDate *future([NSDate distantFuture]);
286 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
288 return [context count] == 0 ? nil : [context objectAtIndex:0];
291 - (id) yieldToSelector:(SEL)selector {
292 return [self yieldToSelector:selector withObject:nil];
298 @interface CYActionSheet : UIAlertView {
302 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
305 @implementation CYActionSheet
307 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
308 if ((self = [super init])) {
309 [self setTitle:title];
310 [self setDelegate:self];
311 for (NSString *button in buttons) [self addButtonWithTitle:button];
312 [self setCancelButtonIndex:index];
316 - (void)_updateFrameForDisplay {
317 [super _updateFrameForDisplay];
318 if ([self cancelButtonIndex] == -1) {
319 NSArray *buttons = [self buttons];
320 if ([buttons count]) {
321 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
322 for (UIThreePartButton *button in buttons)
323 [button setBackground:background forState:0];
328 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
329 button_ = buttonIndex + 1;
333 [self dismissWithClickedButtonIndex:-1 animated:YES];
336 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
337 [self setRunsModal:YES];
345 /* NSForcedOrderingSearch doesn't work on the iPhone */
346 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
347 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
348 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
350 /* Information Dictionaries {{{ */
351 @interface NSMutableArray (Cydia)
352 - (void) addInfoDictionary:(NSDictionary *)info;
355 @implementation NSMutableArray (Cydia)
357 - (void) addInfoDictionary:(NSDictionary *)info {
358 [self addObject:info];
363 @interface NSMutableDictionary (Cydia)
364 - (void) addInfoDictionary:(NSDictionary *)info;
367 @implementation NSMutableDictionary (Cydia)
369 - (void) addInfoDictionary:(NSDictionary *)info {
370 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
376 #define lprintf(args...) fprintf(stderr, args)
379 #define TraceLogging (1 && !ForRelease)
380 #define HistogramInsertionSort (0 && !ForRelease)
381 #define ProfileTimes (0 && !ForRelease)
382 #define ForSaurik (0 && !ForRelease)
383 #define LogBrowser (0 && !ForRelease)
384 #define TrackResize (0 && !ForRelease)
385 #define ManualRefresh (0 && !ForRelease)
386 #define ShowInternals (0 && !ForRelease)
387 #define IgnoreInstall (0 && !ForRelease)
388 #define RecycleWebViews 0
389 #define RotationEnabled 1
390 #define RecyclePackageViews (1 && ForRelease)
391 #define AlwaysReload (1 && !ForRelease)
395 #define _trace(args...)
400 #define _profile(name) {
403 #define PrintTimes() do {} while (false)
407 typedef uint32_t (*SKRadixFunction)(id, void *);
409 @interface NSMutableArray (Radix)
410 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
411 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
419 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
420 struct RadixItem_ *lhs(swap), *rhs(swap + count);
422 static const size_t width = 32;
423 static const size_t bits = 11;
424 static const size_t slots = 1 << bits;
425 static const size_t passes = (width + (bits - 1)) / bits;
427 size_t *hist(new size_t[slots]);
429 for (size_t pass(0); pass != passes; ++pass) {
430 memset(hist, 0, sizeof(size_t) * slots);
432 for (size_t i(0); i != count; ++i) {
433 uint32_t key(lhs[i].key);
435 key &= _not(uint32_t) >> width - bits;
440 for (size_t i(0); i != slots; ++i) {
441 size_t local(offset);
446 for (size_t i(0); i != count; ++i) {
447 uint32_t key(lhs[i].key);
449 key &= _not(uint32_t) >> width - bits;
450 rhs[hist[key]++] = lhs[i];
453 RadixItem_ *tmp(lhs);
460 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
461 for (size_t i(0); i != count; ++i)
462 [values addObject:[self objectAtIndex:lhs[i].index]];
463 [self setArray:values];
468 @implementation NSMutableArray (Radix)
470 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
471 size_t count([self count]);
476 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
477 [invocation setSelector:selector];
478 [invocation setArgument:&object atIndex:2];
480 /* XXX: this is an unsafe optimization of doomy hell */
481 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
482 _assert(method != NULL);
483 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
484 _assert(imp != NULL);
487 struct RadixItem_ *swap(new RadixItem_[count * 2]);
489 for (size_t i(0); i != count; ++i) {
490 RadixItem_ &item(swap[i]);
493 id object([self objectAtIndex:i]);
496 [invocation setTarget:object];
498 [invocation getReturnValue:&item.key];
500 item.key = imp(object, selector, object);
504 RadixSort_(self, count, swap);
507 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
508 size_t count([self count]);
509 struct RadixItem_ *swap(new RadixItem_[count * 2]);
511 for (size_t i(0); i != count; ++i) {
512 RadixItem_ &item(swap[i]);
515 id object([self objectAtIndex:i]);
516 item.key = function(object, argument);
519 RadixSort_(self, count, swap);
524 /* Insertion Sort {{{ */
526 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
527 const char *ptr = (const char *)list;
529 CFIndex half = count / 2;
530 const char *probe = ptr + elementSize * half;
531 CFComparisonResult cr = comparator(element, probe, context);
532 if (0 == cr) return (probe - (const char *)list) / elementSize;
533 ptr = (cr < 0) ? ptr : probe + elementSize;
534 count = (cr < 0) ? half : (half + (count & 1) - 1);
536 return (ptr - (const char *)list) / elementSize;
539 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
540 const char *ptr = (const char *)list;
542 CFIndex half = count / 2;
543 const char *probe = ptr + elementSize * half;
544 CFComparisonResult cr = comparator(element, probe, context);
545 if (0 == cr) return (probe - (const char *)list) / elementSize;
546 ptr = (cr < 0) ? ptr : probe + elementSize;
547 count = (cr < 0) ? half : (half + (count & 1) - 1);
549 return (ptr - (const char *)list) / elementSize;
552 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
553 if (range.length == 0)
555 const void **values(new const void *[range.length]);
556 CFArrayGetValues(array, range, values);
558 #if HistogramInsertionSort
559 uint32_t total(0), *offsets(new uint32_t[range.length]);
562 for (CFIndex index(1); index != range.length; ++index) {
563 const void *value(values[index]);
564 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
565 CFIndex correct(index);
566 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
569 if (correct != index) {
570 size_t offset(index - correct);
571 #if HistogramInsertionSort
575 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
577 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
578 values[correct] = value;
582 CFArrayReplaceValues(array, range, values, range.length);
585 #if HistogramInsertionSort
586 for (CFIndex index(0); index != range.length; ++index)
587 if (offsets[index] != 0)
588 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
589 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
596 /* Apple Bug Fixes {{{ */
597 @implementation UIWebDocumentView (Cydia)
599 - (void) _setScrollerOffset:(CGPoint)offset {
600 UIScroller *scroller([self _scroller]);
602 CGSize size([scroller contentSize]);
603 CGSize bounds([scroller bounds].size);
606 max.x = size.width - bounds.width;
607 max.y = size.height - bounds.height;
615 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
616 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
618 [scroller setOffset:offset];
624 NSUInteger WebScriptObject$countByEnumeratingWithState$objects$count$(WebScriptObject *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
625 size_t length([self count] - state->state);
628 else if (length > count)
630 for (size_t i(0); i != length; ++i)
631 objects[i] = [self objectAtIndex:state->state++];
632 state->itemsPtr = objects;
633 state->mutationsPtr = (unsigned long *) self;
637 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
638 size_t length([self length] - state->state);
641 else if (length > count)
643 for (size_t i(0); i != length; ++i)
644 objects[i] = [self item:state->state++];
645 state->itemsPtr = objects;
646 state->mutationsPtr = (unsigned long *) self;
650 /* Cydia NSString Additions {{{ */
651 @interface NSString (Cydia)
652 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
653 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
654 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
655 - (NSComparisonResult) compareByPath:(NSString *)other;
656 - (NSString *) stringByCachingURLWithCurrentCDN;
657 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
660 @implementation NSString (Cydia)
662 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
663 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
666 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
667 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
668 memcpy(data, bytes, length);
669 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
672 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
673 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
676 - (NSComparisonResult) compareByPath:(NSString *)other {
677 NSString *prefix = [self commonPrefixWithString:other options:0];
678 size_t length = [prefix length];
680 NSRange lrange = NSMakeRange(length, [self length] - length);
681 NSRange rrange = NSMakeRange(length, [other length] - length);
683 lrange = [self rangeOfString:@"/" options:0 range:lrange];
684 rrange = [other rangeOfString:@"/" options:0 range:rrange];
686 NSComparisonResult value;
688 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
689 value = NSOrderedSame;
690 else if (lrange.location == NSNotFound)
691 value = NSOrderedAscending;
692 else if (rrange.location == NSNotFound)
693 value = NSOrderedDescending;
695 value = NSOrderedSame;
697 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
698 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
699 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
700 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
702 NSComparisonResult result = [lpath compare:rpath];
703 return result == NSOrderedSame ? value : result;
706 - (NSString *) stringByCachingURLWithCurrentCDN {
708 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
709 withString:@"://cache.cydia.saurik.com/"
713 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
714 return [(id)CFURLCreateStringByAddingPercentEscapes(
719 kCFStringEncodingUTF8
726 /* C++ NSString Wrapper Cache {{{ */
733 _finline void clear_() {
734 if (cache_ != NULL) {
741 _finline bool empty() const {
745 _finline size_t size() const {
749 _finline char *data() const {
753 _finline void clear() {
758 _finline CYString() :
765 _finline ~CYString() {
769 void operator =(const CYString &rhs) {
773 if (rhs.cache_ == nil)
776 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
779 void set(apr_pool_t *pool, const char *data, size_t size) {
785 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
786 memcpy(temp, data, size);
793 _finline void set(apr_pool_t *pool, const char *data) {
794 set(pool, data, data == NULL ? 0 : strlen(data));
797 _finline void set(apr_pool_t *pool, const std::string &rhs) {
798 set(pool, rhs.data(), rhs.size());
801 bool operator ==(const CYString &rhs) const {
802 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
805 operator CFStringRef() {
806 if (cache_ == NULL) {
809 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
811 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
815 _finline operator id() {
816 return (NSString *) static_cast<CFStringRef>(*this);
820 /* C++ NSString Algorithm Adapters {{{ */
822 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
825 struct NSStringMapHash :
826 std::unary_function<NSString *, size_t>
828 _finline size_t operator ()(NSString *value) const {
829 return CFStringHashNSString((CFStringRef) value);
833 struct NSStringMapLess :
834 std::binary_function<NSString *, NSString *, bool>
836 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
837 return [lhs compare:rhs] == NSOrderedAscending;
841 struct NSStringMapEqual :
842 std::binary_function<NSString *, NSString *, bool>
844 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
845 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
846 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
847 //[lhs isEqualToString:rhs];
852 /* Perl-Compatible RegEx {{{ */
862 Pcre(const char *regex) :
867 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
870 lprintf("%d:%s\n", offset, error);
874 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
875 matches_ = new int[(capture_ + 1) * 3];
883 NSString *operator [](size_t match) {
884 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
887 bool operator ()(NSString *data) {
888 // XXX: length is for characters, not for bytes
889 return operator ()([data UTF8String], [data length]);
892 bool operator ()(const char *data, size_t size) {
894 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
898 /* Mime Addresses {{{ */
899 @interface Address : NSObject {
905 - (NSString *) address;
907 - (void) setAddress:(NSString *)address;
909 + (Address *) addressWithString:(NSString *)string;
910 - (Address *) initWithString:(NSString *)string;
913 @implementation Address
922 - (NSString *) name {
926 - (NSString *) address {
930 - (void) setAddress:(NSString *)address {
932 [address_ autorelease];
936 address_ = [address retain];
939 + (Address *) addressWithString:(NSString *)string {
940 return [[[Address alloc] initWithString:string] autorelease];
943 + (NSArray *) _attributeKeys {
944 return [NSArray arrayWithObjects:@"address", @"name", nil];
947 - (NSArray *) attributeKeys {
948 return [[self class] _attributeKeys];
951 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
952 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
955 - (Address *) initWithString:(NSString *)string {
956 if ((self = [super init]) != nil) {
957 const char *data = [string UTF8String];
958 size_t size = [string length];
960 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
962 if (address_r(data, size)) {
963 name_ = [address_r[1] retain];
964 address_ = [address_r[2] retain];
966 name_ = [string retain];
974 /* CoreGraphics Primitives {{{ */
985 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
988 Set(space, red, green, blue, alpha);
993 CGColorRelease(color_);
1000 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1002 float color[] = {red, green, blue, alpha};
1003 color_ = CGColorCreate(space, color);
1006 operator CGColorRef() {
1012 /* Random Global Variables {{{ */
1013 static const int PulseInterval_ = 50000;
1014 static const int ButtonBarWidth_ = 60;
1015 static const int ButtonBarHeight_ = 48;
1016 static const float KeyboardTime_ = 0.3f;
1019 static NSArray *Finishes_;
1021 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1022 #define NotifyConfig_ "/etc/notify.conf"
1024 static bool Queuing_;
1026 static CGColor Blue_;
1027 static CGColor Blueish_;
1028 static CGColor Black_;
1029 static CGColor Off_;
1030 static CGColor White_;
1031 static CGColor Gray_;
1032 static CGColor Green_;
1033 static CGColor Purple_;
1034 static CGColor Purplish_;
1036 static UIColor *InstallingColor_;
1037 static UIColor *RemovingColor_;
1039 static NSString *App_;
1040 static NSString *Home_;
1042 static BOOL Advanced_;
1043 static BOOL Ignored_;
1045 static UIFont *Font12_;
1046 static UIFont *Font12Bold_;
1047 static UIFont *Font14_;
1048 static UIFont *Font18Bold_;
1049 static UIFont *Font22Bold_;
1051 static const char *Machine_ = NULL;
1052 static const NSString *System_ = NULL;
1053 static const NSString *SerialNumber_ = nil;
1054 static const NSString *ChipID_ = nil;
1055 static const NSString *Token_ = nil;
1056 static const NSString *UniqueID_ = nil;
1057 static const NSString *Build_ = nil;
1058 static const NSString *Product_ = nil;
1059 static const NSString *Safari_ = nil;
1061 static CFLocaleRef Locale_;
1062 static NSArray *Languages_;
1063 static CGColorSpaceRef space_;
1065 static NSDictionary *SectionMap_;
1066 static NSMutableDictionary *Metadata_;
1067 static _transient NSMutableDictionary *Settings_;
1068 static _transient NSString *Role_;
1069 static _transient NSMutableDictionary *Packages_;
1070 static _transient NSMutableDictionary *Sections_;
1071 static _transient NSMutableDictionary *Sources_;
1072 static bool Changed_;
1073 static NSDate *now_;
1075 static bool IsWildcat_;
1078 static NSMutableArray *Documents_;
1082 /* Display Helpers {{{ */
1083 inline float Interpolate(float begin, float end, float fraction) {
1084 return (end - begin) * fraction + begin;
1087 /* XXX: localize this! */
1088 NSString *SizeString(double size) {
1089 bool negative = size < 0;
1094 while (size > 1024) {
1099 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1101 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1104 static _finline CFStringRef CFCString(const char *value) {
1105 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1108 const char *StripVersion_(const char *version) {
1109 const char *colon(strchr(version, ':'));
1111 version = colon + 1;
1115 CFStringRef StripVersion(const char *version) {
1116 const char *colon(strchr(version, ':'));
1118 version = colon + 1;
1119 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1121 return CFCString(version);
1124 NSString *LocalizeSection(NSString *section) {
1125 static Pcre title_r("^(.*?) \\((.*)\\)$");
1126 if (title_r(section)) {
1127 NSString *parent(title_r[1]);
1128 NSString *child(title_r[2]);
1130 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1131 LocalizeSection(parent),
1132 LocalizeSection(child)
1136 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1139 NSString *Simplify(NSString *title) {
1140 const char *data = [title UTF8String];
1141 size_t size = [title length];
1143 static Pcre square_r("^\\[(.*)\\]$");
1144 if (square_r(data, size))
1145 return Simplify(square_r[1]);
1147 static Pcre paren_r("^\\((.*)\\)$");
1148 if (paren_r(data, size))
1149 return Simplify(paren_r[1]);
1151 static Pcre title_r("^(.*?) \\((.*)\\)$");
1152 if (title_r(data, size))
1153 return Simplify(title_r[1]);
1159 NSString *GetLastUpdate() {
1160 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1163 return UCLocalize("NEVER_OR_UNKNOWN");
1165 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1166 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1168 CFRelease(formatter);
1170 return [(NSString *) formatted autorelease];
1173 bool isSectionVisible(NSString *section) {
1174 NSDictionary *metadata([Sections_ objectForKey:section]);
1175 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1176 return hidden == nil || ![hidden boolValue];
1181 /* Delegate Prototypes {{{ */
1185 @interface NSObject (ProgressDelegate)
1188 @protocol ProgressDelegate
1189 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1190 - (void) setProgressTitle:(NSString *)title;
1191 - (void) setProgressPercent:(float)percent;
1192 - (void) startProgress;
1193 - (void) addProgressOutput:(NSString *)output;
1194 - (bool) isCancelling:(size_t)received;
1197 @protocol ConfigurationDelegate
1198 - (void) repairWithSelector:(SEL)selector;
1199 - (void) setConfigurationData:(NSString *)data;
1202 @class PackageController;
1204 @protocol CydiaDelegate
1205 - (void) setPackageController:(PackageController *)view;
1206 - (void) clearPackage:(Package *)package;
1207 - (void) installPackage:(Package *)package;
1208 - (void) installPackages:(NSArray *)packages;
1209 - (void) removePackage:(Package *)package;
1210 - (void) beginUpdate;
1212 - (void) distUpgrade;
1214 - (void) updateData;
1216 - (void) showSettings;
1217 - (UIProgressHUD *) addProgressHUD;
1218 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1219 - (UCViewController *) pageForPackage:(NSString *)name;
1220 - (PackageController *) packageController;
1221 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1225 /* Status Delegation {{{ */
1227 public pkgAcquireStatus
1230 _transient NSObject<ProgressDelegate> *delegate_;
1238 void setDelegate(id delegate) {
1239 delegate_ = delegate;
1242 NSObject<ProgressDelegate> *getDelegate() const {
1246 virtual bool MediaChange(std::string media, std::string drive) {
1250 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1253 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1254 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1255 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1258 virtual void Done(pkgAcquire::ItemDesc &item) {
1261 virtual void Fail(pkgAcquire::ItemDesc &item) {
1263 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1264 item.Owner->Status == pkgAcquire::Item::StatDone
1268 std::string &error(item.Owner->ErrorText);
1272 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1273 NSArray *fields([description componentsSeparatedByString:@" "]);
1274 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1276 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1277 withObject:[NSArray arrayWithObjects:
1278 [NSString stringWithUTF8String:error.c_str()],
1285 virtual bool Pulse(pkgAcquire *Owner) {
1286 bool value = pkgAcquireStatus::Pulse(Owner);
1289 double(CurrentBytes + CurrentItems) /
1290 double(TotalBytes + TotalItems)
1293 [delegate_ setProgressPercent:percent];
1294 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1297 virtual void Start() {
1298 [delegate_ startProgress];
1301 virtual void Stop() {
1305 /* Progress Delegation {{{ */
1310 _transient id<ProgressDelegate> delegate_;
1314 virtual void Update() {
1315 /*if (abs(Percent - percent_) > 2)
1316 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1320 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1321 [delegate_ setProgressPercent:(Percent / 100)];*/
1331 void setDelegate(id delegate) {
1332 delegate_ = delegate;
1335 id getDelegate() const {
1339 virtual void Done() {
1341 //[delegate_ setProgressPercent:1];
1346 /* Database Interface {{{ */
1347 typedef std::map< unsigned long, _H<Source> > SourceMap;
1349 @interface Database : NSObject {
1355 pkgCacheFile cache_;
1356 pkgDepCache::Policy *policy_;
1357 pkgRecords *records_;
1358 pkgProblemResolver *resolver_;
1359 pkgAcquire *fetcher_;
1361 SPtr<pkgPackageManager> manager_;
1362 pkgSourceList *list_;
1365 NSMutableArray *packages_;
1367 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1376 + (Database *) sharedInstance;
1379 - (void) _readCydia:(NSNumber *)fd;
1380 - (void) _readStatus:(NSNumber *)fd;
1381 - (void) _readOutput:(NSNumber *)fd;
1385 - (Package *) packageWithName:(NSString *)name;
1387 - (pkgCacheFile &) cache;
1388 - (pkgDepCache::Policy *) policy;
1389 - (pkgRecords *) records;
1390 - (pkgProblemResolver *) resolver;
1391 - (pkgAcquire &) fetcher;
1392 - (pkgSourceList &) list;
1393 - (NSArray *) packages;
1394 - (NSArray *) sources;
1395 - (void) reloadData;
1403 - (void) setVisible;
1405 - (void) updateWithStatus:(Status &)status;
1407 - (void) setDelegate:(id)delegate;
1408 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1411 /* Delegate Helpers {{{ */
1412 @implementation NSObject (ProgressDelegate)
1414 - (void) _setProgressErrorPackage:(NSArray *)args {
1415 [self performSelector:@selector(setProgressError:forPackage:)
1416 withObject:[args objectAtIndex:0]
1417 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1421 - (void) _setProgressErrorTitle:(NSArray *)args {
1422 [self performSelector:@selector(setProgressError:withTitle:)
1423 withObject:[args objectAtIndex:0]
1424 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1428 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1429 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1430 withObject:[NSArray arrayWithObjects:error, title, nil]
1435 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1436 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1437 // XXX: holy typecast batman!
1438 [(id<ProgressDelegate>)self setProgressError:error withTitle:(package == nil ? id : [package name])];
1444 /* Source Class {{{ */
1445 @interface Source : NSObject {
1446 CYString depiction_;
1447 CYString description_;
1453 CYString distribution_;
1458 NSString *authority_;
1460 CYString defaultIcon_;
1462 NSDictionary *record_;
1466 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1468 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1470 - (NSString *) depictionForPackage:(NSString *)package;
1471 - (NSString *) supportForPackage:(NSString *)package;
1473 - (NSDictionary *) record;
1477 - (NSString *) distribution;
1478 - (NSString *) type;
1480 - (NSString *) host;
1482 - (NSString *) name;
1483 - (NSString *) description;
1484 - (NSString *) label;
1485 - (NSString *) origin;
1486 - (NSString *) version;
1488 - (NSString *) defaultIcon;
1492 @implementation Source
1496 distribution_.clear();
1499 description_.clear();
1505 defaultIcon_.clear();
1507 if (record_ != nil) {
1517 if (authority_ != nil) {
1518 [authority_ release];
1528 + (NSArray *) _attributeKeys {
1529 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1532 - (NSArray *) attributeKeys {
1533 return [[self class] _attributeKeys];
1536 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1537 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1540 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1543 trusted_ = index->IsTrusted();
1545 uri_.set(pool, index->GetURI());
1546 distribution_.set(pool, index->GetDist());
1547 type_.set(pool, index->GetType());
1549 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1550 if (dindex != NULL) {
1552 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1555 pkgTagFile tags(&fd);
1557 pkgTagSection section;
1564 {"default-icon", &defaultIcon_},
1565 {"depiction", &depiction_},
1566 {"description", &description_},
1568 {"origin", &origin_},
1569 {"support", &support_},
1570 {"version", &version_},
1573 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1574 const char *start, *end;
1576 if (section.Find(names[i].name_, start, end)) {
1577 CYString &value(*names[i].value_);
1578 value.set(pool, start, end - start);
1584 record_ = [Sources_ objectForKey:[self key]];
1586 record_ = [record_ retain];
1588 NSURL *url([NSURL URLWithString:uri_]);
1592 host_ = [[host_ lowercaseString] retain];
1597 authority_ = [url path];
1599 if (authority_ != nil)
1600 authority_ = [authority_ retain];
1603 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1604 if ((self = [super init]) != nil) {
1605 [self setMetaIndex:index inPool:pool];
1609 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1610 NSDictionary *lhr = [self record];
1611 NSDictionary *rhr = [source record];
1614 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1616 NSString *lhs = [self name];
1617 NSString *rhs = [source name];
1619 if ([lhs length] != 0 && [rhs length] != 0) {
1620 unichar lhc = [lhs characterAtIndex:0];
1621 unichar rhc = [rhs characterAtIndex:0];
1623 if (isalpha(lhc) && !isalpha(rhc))
1624 return NSOrderedAscending;
1625 else if (!isalpha(lhc) && isalpha(rhc))
1626 return NSOrderedDescending;
1629 return [lhs compare:rhs options:LaxCompareOptions_];
1632 - (NSString *) depictionForPackage:(NSString *)package {
1633 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1636 - (NSString *) supportForPackage:(NSString *)package {
1637 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1640 - (NSDictionary *) record {
1648 - (NSString *) uri {
1652 - (NSString *) distribution {
1653 return distribution_;
1656 - (NSString *) type {
1660 - (NSString *) key {
1661 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1664 - (NSString *) host {
1668 - (NSString *) name {
1669 return origin_.empty() ? authority_ : origin_;
1672 - (NSString *) description {
1673 return description_;
1676 - (NSString *) label {
1677 return label_.empty() ? authority_ : label_;
1680 - (NSString *) origin {
1684 - (NSString *) version {
1688 - (NSString *) defaultIcon {
1689 return defaultIcon_;
1694 /* Relationship Class {{{ */
1695 @interface Relationship : NSObject {
1700 - (NSString *) type;
1702 - (NSString *) name;
1706 @implementation Relationship
1714 - (NSString *) type {
1722 - (NSString *) name {
1729 /* Package Class {{{ */
1730 @interface Package : NSObject {
1734 pkgCache::VerIterator version_;
1735 pkgCache::PkgIterator iterator_;
1736 _transient Database *database_;
1737 pkgCache::VerFileIterator file_;
1744 NSString *section$_;
1751 CYString installed_;
1757 CYString depiction_;
1768 NSMutableArray *tags_;
1771 NSArray *relationships_;
1773 NSMutableDictionary *metadata_;
1774 _transient NSDate *firstSeen_;
1775 _transient NSDate *lastSeen_;
1779 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1780 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1782 - (pkgCache::PkgIterator) iterator;
1785 - (NSString *) section;
1786 - (NSString *) simpleSection;
1788 - (NSString *) longSection;
1789 - (NSString *) shortSection;
1793 - (Address *) maintainer;
1795 - (NSString *) longDescription;
1796 - (NSString *) shortDescription;
1799 - (NSMutableDictionary *) metadata;
1801 - (BOOL) subscribed;
1804 - (NSString *) latest;
1805 - (NSString *) installed;
1806 - (BOOL) uninstalled;
1809 - (BOOL) upgradableAndEssential:(BOOL)essential;
1812 - (BOOL) unfiltered;
1816 - (BOOL) halfConfigured;
1817 - (BOOL) halfInstalled;
1819 - (NSString *) mode;
1821 - (void) setVisible;
1824 - (NSString *) name;
1826 - (NSString *) homepage;
1827 - (NSString *) depiction;
1828 - (Address *) author;
1830 - (NSString *) support;
1832 - (NSArray *) files;
1833 - (NSArray *) relationships;
1834 - (NSArray *) warnings;
1835 - (NSArray *) applications;
1837 - (Source *) source;
1838 - (NSString *) role;
1840 - (BOOL) matches:(NSString *)text;
1842 - (bool) hasSupportingRole;
1843 - (BOOL) hasTag:(NSString *)tag;
1844 - (NSString *) primaryPurpose;
1845 - (NSArray *) purposes;
1846 - (bool) isCommercial;
1848 - (CYString &) cyname;
1850 - (uint32_t) compareBySection:(NSArray *)sections;
1852 - (uint32_t) compareForChanges;
1857 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1858 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1859 - (bool) isInstalledAndVisible:(NSNumber *)number;
1860 - (bool) isVisibleInSection:(NSString *)section;
1861 - (bool) isVisibleInSource:(Source *)source;
1865 uint32_t PackageChangesRadix(Package *self, void *) {
1870 uint32_t timestamp : 30;
1871 uint32_t ignored : 1;
1872 uint32_t upgradable : 1;
1876 bool upgradable([self upgradableAndEssential:YES]);
1877 value.bits.upgradable = upgradable ? 1 : 0;
1880 value.bits.timestamp = 0;
1881 value.bits.ignored = [self ignored] ? 0 : 1;
1882 value.bits.upgradable = 1;
1884 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1885 value.bits.ignored = 0;
1886 value.bits.upgradable = 0;
1889 return _not(uint32_t) - value.key;
1892 _finline static void Stifle(uint8_t &value) {
1895 uint32_t PackagePrefixRadix(Package *self, void *context) {
1896 size_t offset(reinterpret_cast<size_t>(context));
1897 CYString &name([self cyname]);
1899 size_t size(name.size());
1902 char *text(name.data());
1905 if (!isdigit(text[0]))
1909 while (size != digits && isdigit(text[digits]))
1919 if (offset == 0 && zeros != 0) {
1920 memset(data, '0', zeros);
1921 memcpy(data + zeros, text, 4 - zeros);
1923 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1924 if (size <= offset - zeros)
1927 text += offset - zeros;
1928 size -= offset - zeros;
1931 memcpy(data, text, 4);
1933 memcpy(data, text, size);
1934 memset(data + size, 0, 4 - size);
1937 for (size_t i(0); i != 4; ++i)
1938 if (isalpha(data[i]))
1943 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1945 /* XXX: ntohl may be more honest */
1946 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1949 CYString &(*PackageName)(Package *self, SEL sel);
1951 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1952 _profile(PackageNameCompare)
1953 CYString &lhi(PackageName(lhs, @selector(cyname)));
1954 CYString &rhi(PackageName(rhs, @selector(cyname)));
1955 CFStringRef lhn(lhi), rhn(rhi);
1958 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1959 else if (rhn == NULL)
1960 return NSOrderedDescending;
1962 _profile(PackageNameCompare$NumbersLast)
1963 if (!lhi.empty() && !rhi.empty()) {
1964 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1965 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1966 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1967 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1968 return lha ? NSOrderedAscending : NSOrderedDescending;
1972 CFIndex length = CFStringGetLength(lhn);
1974 _profile(PackageNameCompare$Compare)
1975 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1980 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1981 return PackageNameCompare(*lhs, *rhs, context);
1984 struct PackageNameOrdering :
1985 std::binary_function<Package *, Package *, bool>
1987 _finline bool operator ()(Package *lhs, Package *rhs) const {
1988 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1992 @implementation Package
1994 - (NSString *) description {
1995 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2001 if (section$_ != nil)
2002 [section$_ release];
2007 if (sponsor$_ != nil)
2008 [sponsor$_ release];
2009 if (author$_ != nil)
2016 if (relationships_ != nil)
2017 [relationships_ release];
2018 if (metadata_ != nil)
2019 [metadata_ release];
2024 + (NSString *) webScriptNameForSelector:(SEL)selector {
2025 if (selector == @selector(hasTag:))
2031 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2032 return [self webScriptNameForSelector:selector] == nil;
2035 + (NSArray *) _attributeKeys {
2036 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];
2039 - (NSArray *) attributeKeys {
2040 return [[self class] _attributeKeys];
2043 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2044 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2054 _profile(Package$parse)
2055 pkgRecords::Parser *parser;
2057 _profile(Package$parse$Lookup)
2058 parser = &[database_ records]->Lookup(file_);
2063 _profile(Package$parse$Find)
2069 {"depiction", &depiction_},
2070 {"homepage", &homepage_},
2071 {"website", &website},
2073 {"support", &support_},
2074 {"sponsor", &sponsor_},
2075 {"author", &author_},
2078 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2079 const char *start, *end;
2081 if (parser->Find(names[i].name_, start, end)) {
2082 CYString &value(*names[i].value_);
2083 _profile(Package$parse$Value)
2084 value.set(pool_, start, end - start);
2090 _profile(Package$parse$Tagline)
2091 const char *start, *end;
2092 if (parser->ShortDesc(start, end)) {
2093 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2096 while (stop != start && stop[-1] == '\r')
2098 tagline_.set(pool_, start, stop - start);
2102 _profile(Package$parse$Retain)
2103 if (homepage_.empty())
2104 homepage_ = website;
2105 if (homepage_ == depiction_)
2111 - (void) setVisible {
2112 visible_ = required_ && [self unfiltered];
2115 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2116 if ((self = [super init]) != nil) {
2117 _profile(Package$initWithVersion)
2118 @synchronized (database) {
2119 era_ = [database era];
2123 iterator_ = version.ParentPkg();
2124 database_ = database;
2126 _profile(Package$initWithVersion$Latest)
2127 latest_ = (NSString *) StripVersion(version_.VerStr());
2130 pkgCache::VerIterator current;
2131 _profile(Package$initWithVersion$Versions)
2132 current = iterator_.CurrentVer();
2134 installed_.set(pool_, StripVersion_(current.VerStr()));
2136 if (!version_.end())
2137 file_ = version_.FileList();
2139 pkgCache &cache([database_ cache]);
2140 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2144 _profile(Package$initWithVersion$Name)
2145 id_.set(pool_, iterator_.Name());
2146 name_.set(pool, iterator_.Display());
2150 _profile(Package$initWithVersion$Source)
2151 source_ = [database_ getSource:file_.File()];
2160 _profile(Package$initWithVersion$Tags)
2161 pkgCache::TagIterator tag(iterator_.TagList());
2163 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2165 const char *name(tag.Name());
2166 [tags_ addObject:(NSString *)CFCString(name)];
2167 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2168 role_ = (NSString *) CFCString(name + 6);
2169 if (required_ && strncmp(name, "require::", 9) == 0 && (
2174 } while (!tag.end());
2178 bool changed(false);
2179 NSString *key([id_ lowercaseString]);
2181 _profile(Package$initWithVersion$Metadata)
2182 metadata_ = [Packages_ objectForKey:key];
2184 if (metadata_ == nil) {
2187 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2188 firstSeen_, @"FirstSeen",
2189 latest_, @"LastVersion",
2194 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2195 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2197 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2198 subscribed_ = [subscribed boolValue];
2200 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2202 if (firstSeen_ == nil) {
2203 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2204 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2208 if (version == nil) {
2209 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2211 } else if (![version isEqualToString:latest_]) {
2212 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2214 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2219 metadata_ = [metadata_ retain];
2222 [Packages_ setObject:metadata_ forKey:key];
2227 _profile(Package$initWithVersion$Section)
2228 section_.set(pool_, iterator_.Section());
2231 obsolete_ = [self hasTag:@"cydia::obsolete"];
2232 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2234 } _end } return self;
2237 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2238 @synchronized ([Database class]) {
2239 pkgCache::VerIterator version;
2241 _profile(Package$packageWithIterator$GetCandidateVer)
2242 version = [database policy]->GetCandidateVer(iterator);
2248 return [[[Package alloc]
2249 initWithVersion:version
2256 - (pkgCache::PkgIterator) iterator {
2260 - (NSString *) section {
2261 if (section$_ == nil) {
2262 if (section_.empty())
2265 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2266 NSString *name(section_);
2269 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2270 if (NSString *rename = [value objectForKey:@"Rename"]) {
2275 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2279 - (NSString *) simpleSection {
2280 if (NSString *section = [self section])
2281 return Simplify(section);
2286 - (NSString *) longSection {
2287 return LocalizeSection([self section]);
2290 - (NSString *) shortSection {
2291 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2294 - (NSString *) uri {
2297 pkgIndexFile *index;
2298 pkgCache::PkgFileIterator file(file_.File());
2299 if (![database_ list].FindIndex(file, index))
2301 return [NSString stringWithUTF8String:iterator_->Path];
2302 //return [NSString stringWithUTF8String:file.Site()];
2303 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2307 - (Address *) maintainer {
2310 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2311 const std::string &maintainer(parser->Maintainer());
2312 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2316 return version_.end() ? 0 : version_->InstalledSize;
2319 - (NSString *) longDescription {
2322 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2323 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2325 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2326 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2327 if ([lines count] < 2)
2330 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2331 for (size_t i(1), e([lines count]); i != e; ++i) {
2332 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2333 [trimmed addObject:trim];
2336 return [trimmed componentsJoinedByString:@"\n"];
2339 - (NSString *) shortDescription {
2344 _profile(Package$index)
2345 CFStringRef name((CFStringRef) [self name]);
2346 if (CFStringGetLength(name) == 0)
2348 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2349 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2351 return toupper(character);
2355 - (NSMutableDictionary *) metadata {
2360 if (subscribed_ && lastSeen_ != nil)
2365 - (BOOL) subscribed {
2370 NSDictionary *metadata([self metadata]);
2371 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2372 return [ignored boolValue];
2377 - (NSString *) latest {
2381 - (NSString *) installed {
2385 - (BOOL) uninstalled {
2386 return installed_.empty();
2390 return !version_.end();
2393 - (BOOL) upgradableAndEssential:(BOOL)essential {
2394 _profile(Package$upgradableAndEssential)
2395 pkgCache::VerIterator current(iterator_.CurrentVer());
2397 return essential && essential_ && visible_;
2399 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2403 - (BOOL) essential {
2408 return [database_ cache][iterator_].InstBroken();
2411 - (BOOL) unfiltered {
2412 NSString *section([self section]);
2413 return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
2421 unsigned char current(iterator_->CurrentState);
2422 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2425 - (BOOL) halfConfigured {
2426 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2429 - (BOOL) halfInstalled {
2430 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2434 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2435 return state.Mode != pkgDepCache::ModeKeep;
2438 - (NSString *) mode {
2439 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2441 switch (state.Mode) {
2442 case pkgDepCache::ModeDelete:
2443 if ((state.iFlags & pkgDepCache::Purge) != 0)
2447 case pkgDepCache::ModeKeep:
2448 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2449 return @"REINSTALL";
2450 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2454 case pkgDepCache::ModeInstall:
2455 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2456 return @"REINSTALL";
2457 else*/ switch (state.Status) {
2459 return @"DOWNGRADE";
2465 return @"NEW_INSTALL";
2476 - (NSString *) name {
2477 return name_.empty() ? id_ : name_;
2480 - (UIImage *) icon {
2481 NSString *section = [self simpleSection];
2485 if ([icon_ hasPrefix:@"file:///"])
2486 // XXX: correct escaping
2487 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2488 if (icon == nil) if (section != nil)
2489 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2490 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2491 if ([dicon hasPrefix:@"file:///"])
2492 // XXX: correct escaping
2493 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2495 icon = [UIImage applicationImageNamed:@"unknown.png"];
2499 - (NSString *) homepage {
2503 - (NSString *) depiction {
2504 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2507 - (Address *) sponsor {
2508 if (sponsor$_ == nil) {
2509 if (sponsor_.empty())
2511 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2515 - (Address *) author {
2516 if (author$_ == nil) {
2517 if (author_.empty())
2519 author$_ = [[Address addressWithString:author_] retain];
2523 - (NSString *) support {
2524 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2527 - (NSArray *) files {
2528 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2529 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2532 fin.open([path UTF8String]);
2537 while (std::getline(fin, line))
2538 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2543 - (NSArray *) relationships {
2544 return relationships_;
2547 - (NSArray *) warnings {
2548 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2549 const char *name(iterator_.Name());
2551 size_t length(strlen(name));
2552 if (length < 2) invalid:
2553 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2554 else for (size_t i(0); i != length; ++i)
2556 /* XXX: technically this is not allowed */
2557 (name[i] < 'A' || name[i] > 'Z') &&
2558 (name[i] < 'a' || name[i] > 'z') &&
2559 (name[i] < '0' || name[i] > '9') &&
2560 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2563 if (strcmp(name, "cydia") != 0) {
2566 bool _private = false;
2569 bool repository = [[self section] isEqualToString:@"Repositories"];
2571 if (NSArray *files = [self files])
2572 for (NSString *file in files)
2573 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2575 else if (!user && [file isEqualToString:@"/User"])
2577 else if (!_private && [file isEqualToString:@"/private"])
2579 else if (!stash && [file isEqualToString:@"/var/stash"])
2582 /* XXX: this is not sensitive enough. only some folders are valid. */
2583 if (cydia && !repository)
2584 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2586 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2588 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2590 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2593 return [warnings count] == 0 ? nil : warnings;
2596 - (NSArray *) applications {
2597 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2599 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2601 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2602 if (NSArray *files = [self files])
2603 for (NSString *file in files)
2604 if (application_r(file)) {
2605 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2606 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2607 if ([id isEqualToString:me])
2610 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2612 display = application_r[1];
2614 NSString *bundle([file stringByDeletingLastPathComponent]);
2615 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2616 if (icon == nil || [icon length] == 0)
2618 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2620 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2621 [applications addObject:application];
2623 [application addObject:id];
2624 [application addObject:display];
2625 [application addObject:url];
2628 return [applications count] == 0 ? nil : applications;
2631 - (Source *) source {
2633 @synchronized (database_) {
2634 if ([database_ era] != era_ || file_.end())
2637 source_ = [database_ getSource:file_.File()];
2649 - (NSString *) role {
2653 - (BOOL) matches:(NSString *)text {
2659 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2660 if (range.location != NSNotFound)
2663 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2664 if (range.location != NSNotFound)
2667 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2668 if (range.location != NSNotFound)
2674 - (bool) hasSupportingRole {
2677 if ([role_ isEqualToString:@"enduser"])
2679 if ([Role_ isEqualToString:@"User"])
2681 if ([role_ isEqualToString:@"hacker"])
2683 if ([Role_ isEqualToString:@"Hacker"])
2685 if ([role_ isEqualToString:@"developer"])
2687 if ([Role_ isEqualToString:@"Developer"])
2692 - (BOOL) hasTag:(NSString *)tag {
2693 return tags_ == nil ? NO : [tags_ containsObject:tag];
2696 - (NSString *) primaryPurpose {
2697 for (NSString *tag in tags_)
2698 if ([tag hasPrefix:@"purpose::"])
2699 return [tag substringFromIndex:9];
2703 - (NSArray *) purposes {
2704 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2705 for (NSString *tag in tags_)
2706 if ([tag hasPrefix:@"purpose::"])
2707 [purposes addObject:[tag substringFromIndex:9]];
2708 return [purposes count] == 0 ? nil : purposes;
2711 - (bool) isCommercial {
2712 return [self hasTag:@"cydia::commercial"];
2715 - (CYString &) cyname {
2716 return name_.empty() ? id_ : name_;
2719 - (uint32_t) compareBySection:(NSArray *)sections {
2720 NSString *section([self section]);
2721 for (size_t i(0), e([sections count]); i != e; ++i) {
2722 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2726 return _not(uint32_t);
2729 - (uint32_t) compareForChanges {
2734 uint32_t timestamp : 30;
2735 uint32_t ignored : 1;
2736 uint32_t upgradable : 1;
2740 bool upgradable([self upgradableAndEssential:YES]);
2741 value.bits.upgradable = upgradable ? 1 : 0;
2744 value.bits.timestamp = 0;
2745 value.bits.ignored = [self ignored] ? 0 : 1;
2746 value.bits.upgradable = 1;
2748 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2749 value.bits.ignored = 0;
2750 value.bits.upgradable = 0;
2753 return _not(uint32_t) - value.key;
2757 pkgProblemResolver *resolver = [database_ resolver];
2758 resolver->Clear(iterator_);
2759 resolver->Protect(iterator_);
2763 pkgProblemResolver *resolver = [database_ resolver];
2764 resolver->Clear(iterator_);
2765 resolver->Protect(iterator_);
2766 pkgCacheFile &cache([database_ cache]);
2767 cache->MarkInstall(iterator_, false);
2768 pkgDepCache::StateCache &state((*cache)[iterator_]);
2769 if (!state.Install())
2770 cache->SetReInstall(iterator_, true);
2774 pkgProblemResolver *resolver = [database_ resolver];
2775 resolver->Clear(iterator_);
2776 resolver->Protect(iterator_);
2777 resolver->Remove(iterator_);
2778 [database_ cache]->MarkDelete(iterator_, true);
2781 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2782 _profile(Package$isUnfilteredAndSearchedForBy)
2785 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2786 value &= [self unfiltered];
2789 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2790 value &= [self matches:search];
2797 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2798 if ([search length] == 0)
2801 _profile(Package$isUnfilteredAndSelectedForBy)
2804 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2805 value &= [self unfiltered];
2808 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2809 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2816 - (bool) isInstalledAndVisible:(NSNumber *)number {
2817 return (![number boolValue] || [self visible]) && ![self uninstalled];
2820 - (bool) isVisibleInSection:(NSString *)name {
2821 NSString *section = [self section];
2826 section == nil && [name length] == 0 ||
2827 [name isEqualToString:section]
2831 - (bool) isVisibleInSource:(Source *)source {
2832 return [self source] == source && [self visible];
2837 /* Section Class {{{ */
2838 @interface Section : NSObject {
2843 NSString *localized_;
2846 - (NSComparisonResult) compareByLocalized:(Section *)section;
2847 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2848 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2849 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2850 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2851 - (NSString *) name;
2858 - (void) addToCount;
2860 - (void) setCount:(size_t)count;
2861 - (NSString *) localized;
2865 @implementation Section
2869 if (localized_ != nil)
2870 [localized_ release];
2874 - (NSComparisonResult) compareByLocalized:(Section *)section {
2875 NSString *lhs(localized_);
2876 NSString *rhs([section localized]);
2878 /*if ([lhs length] != 0 && [rhs length] != 0) {
2879 unichar lhc = [lhs characterAtIndex:0];
2880 unichar rhc = [rhs characterAtIndex:0];
2882 if (isalpha(lhc) && !isalpha(rhc))
2883 return NSOrderedAscending;
2884 else if (!isalpha(lhc) && isalpha(rhc))
2885 return NSOrderedDescending;
2888 return [lhs compare:rhs options:LaxCompareOptions_];
2891 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2892 if ((self = [self initWithName:name localize:NO]) != nil) {
2893 if (localized != nil)
2894 localized_ = [localized retain];
2898 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2899 return [self initWithName:name row:0 localize:localize];
2902 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2903 if ((self = [super init]) != nil) {
2904 name_ = [name retain];
2908 localized_ = [LocalizeSection(name_) retain];
2912 /* XXX: localize the index thingees */
2913 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2914 if ((self = [super init]) != nil) {
2915 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2921 - (NSString *) name {
2941 - (void) addToCount {
2945 - (void) setCount:(size_t)count {
2949 - (NSString *) localized {
2956 static NSString *Colon_;
2957 static NSString *Error_;
2958 static NSString *Warning_;
2960 /* Database Implementation {{{ */
2961 @implementation Database
2963 + (Database *) sharedInstance {
2964 static Database *instance;
2965 if (instance == nil)
2966 instance = [[Database alloc] init];
2976 NSRecycleZone(zone_);
2977 // XXX: malloc_destroy_zone(zone_);
2978 apr_pool_destroy(pool_);
2982 - (void) _readCydia:(NSNumber *)fd { _pooled
2983 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2984 std::istream is(&ib);
2987 static Pcre finish_r("^finish:([^:]*)$");
2989 while (std::getline(is, line)) {
2990 const char *data(line.c_str());
2991 size_t size = line.size();
2992 lprintf("C:%s\n", data);
2994 if (finish_r(data, size)) {
2995 NSString *finish = finish_r[1];
2996 int index = [Finishes_ indexOfObject:finish];
2997 if (index != INT_MAX && index > Finish_)
3005 - (void) _readStatus:(NSNumber *)fd { _pooled
3006 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3007 std::istream is(&ib);
3010 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3011 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3013 while (std::getline(is, line)) {
3014 const char *data(line.c_str());
3015 size_t size(line.size());
3016 lprintf("S:%s\n", data);
3018 if (conffile_r(data, size)) {
3019 [delegate_ setConfigurationData:conffile_r[1]];
3020 } else if (strncmp(data, "status: ", 8) == 0) {
3021 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3022 [delegate_ setProgressTitle:string];
3023 } else if (pmstatus_r(data, size)) {
3024 std::string type([pmstatus_r[1] UTF8String]);
3025 NSString *id = pmstatus_r[2];
3027 float percent([pmstatus_r[3] floatValue]);
3028 [delegate_ setProgressPercent:(percent / 100)];
3030 NSString *string = pmstatus_r[4];
3032 if (type == "pmerror")
3033 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3034 withObject:[NSArray arrayWithObjects:string, id, nil]
3037 else if (type == "pmstatus") {
3038 [delegate_ setProgressTitle:string];
3039 } else if (type == "pmconffile")
3040 [delegate_ setConfigurationData:string];
3042 lprintf("E:unknown pmstatus\n");
3044 lprintf("E:unknown status\n");
3050 - (void) _readOutput:(NSNumber *)fd { _pooled
3051 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3052 std::istream is(&ib);
3055 while (std::getline(is, line)) {
3056 lprintf("O:%s\n", line.c_str());
3057 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3067 - (Package *) packageWithName:(NSString *)name {
3068 @synchronized ([Database class]) {
3069 if (static_cast<pkgDepCache *>(cache_) == NULL)
3071 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3072 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3075 - (Database *) init {
3076 if ((self = [super init]) != nil) {
3083 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3084 apr_pool_create(&pool_, NULL);
3086 packages_ = [[NSMutableArray alloc] init];
3090 _assert(pipe(fds) != -1);
3093 _config->Set("APT::Keep-Fds::", cydiafd_);
3094 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3097 detachNewThreadSelector:@selector(_readCydia:)
3099 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3102 _assert(pipe(fds) != -1);
3106 detachNewThreadSelector:@selector(_readStatus:)
3108 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3111 _assert(pipe(fds) != -1);
3112 _assert(dup2(fds[0], 0) != -1);
3113 _assert(close(fds[0]) != -1);
3115 input_ = fdopen(fds[1], "a");
3117 _assert(pipe(fds) != -1);
3118 _assert(dup2(fds[1], 1) != -1);
3119 _assert(close(fds[1]) != -1);
3122 detachNewThreadSelector:@selector(_readOutput:)
3124 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3129 - (pkgCacheFile &) cache {
3133 - (pkgDepCache::Policy *) policy {
3137 - (pkgRecords *) records {
3141 - (pkgProblemResolver *) resolver {
3145 - (pkgAcquire &) fetcher {
3149 - (pkgSourceList &) list {
3153 - (NSArray *) packages {
3157 - (NSArray *) sources {
3158 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3159 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3160 [sources addObject:i->second];
3164 - (NSArray *) issues {
3165 if (cache_->BrokenCount() == 0)
3168 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3170 for (Package *package in packages_) {
3171 if (![package broken])
3173 pkgCache::PkgIterator pkg([package iterator]);
3175 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3176 [entry addObject:[package name]];
3177 [issues addObject:entry];
3179 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3183 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3184 pkgCache::DepIterator start;
3185 pkgCache::DepIterator end;
3186 dep.GlobOr(start, end); // ++dep
3188 if (!cache_->IsImportantDep(end))
3190 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3193 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3194 [entry addObject:failure];
3195 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3197 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3198 if (Package *package = [self packageWithName:name])
3199 name = [package name];
3200 [failure addObject:name];
3202 pkgCache::PkgIterator target(start.TargetPkg());
3203 if (target->ProvidesList != 0)
3204 [failure addObject:@"?"];
3206 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3208 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3209 else if (!cache_[target].CandidateVerIter(cache_).end())
3210 [failure addObject:@"-"];
3211 else if (target->ProvidesList == 0)
3212 [failure addObject:@"!"];
3214 [failure addObject:@"%"];
3218 if (start.TargetVer() != 0)
3219 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3230 - (bool) popErrorWithTitle:(NSString *)title {
3232 std::string message;
3234 while (!_error->empty()) {
3236 bool warning(!_error->PopMessage(error));
3240 size_t size(error.size());
3241 if (size == 0 || error[size - 1] != '\n')
3243 error.resize(size - 1);
3245 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3247 if (!message.empty())
3252 if (fatal && !message.empty())
3253 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3258 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3259 return [self popErrorWithTitle:title] || !success;
3262 - (void) reloadData { _pooled
3263 @synchronized ([Database class]) {
3264 @synchronized (self) {
3268 [packages_ removeAllObjects];
3294 apr_pool_clear(pool_);
3295 NSRecycleZone(zone_);
3297 int chk(creat("/tmp/cydia.chk", 0644));
3301 NSString *title(UCLocalize("DATABASE"));
3304 if (!cache_.Open(progress_, true)) { pop:
3306 bool warning(!_error->PopMessage(error));
3307 lprintf("cache_.Open():[%s]\n", error.c_str());
3309 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3310 [delegate_ repairWithSelector:@selector(configure)];
3311 else if (error == "The package lists or status file could not be parsed or opened.")
3312 [delegate_ repairWithSelector:@selector(update)];
3313 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3314 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3315 // else if (error == "The list of sources could not be read.")
3317 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3326 unlink("/tmp/cydia.chk");
3328 now_ = [[NSDate date] retain];
3330 policy_ = new pkgDepCache::Policy();
3331 records_ = new pkgRecords(cache_);
3332 resolver_ = new pkgProblemResolver(cache_);
3333 fetcher_ = new pkgAcquire(&status_);
3336 list_ = new pkgSourceList();
3337 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3340 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3341 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3345 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3348 if (cache_->BrokenCount() != 0) {
3349 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3352 if (cache_->BrokenCount() != 0) {
3353 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3357 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3363 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3364 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3365 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3366 // XXX: this could be more intelligent
3367 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3368 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3370 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3377 /*std::vector<Package *> packages;
3378 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3379 [packages_ release];
3384 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3385 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3386 //packages.push_back(package);
3387 [packages_ addObject:package];
3391 /*if (packages.empty())
3392 packages_ = [[NSArray alloc] init];
3394 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3397 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3398 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3399 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3407 /*if (!packages.empty())
3408 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3409 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3411 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3413 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3415 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3421 - (void) configure {
3422 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3423 system([dpkg UTF8String]);
3427 // XXX: I don't remember this condition
3432 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3434 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3436 if ([self popErrorWithTitle:title])
3440 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3443 public pkgArchiveCleaner
3446 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3451 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3458 fetcher_->Shutdown();
3460 pkgRecords records(cache_);
3462 lock_ = new FileFd();
3463 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3465 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3467 if ([self popErrorWithTitle:title])
3471 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3474 manager_ = (_system->CreatePM(cache_));
3475 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3482 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3484 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3486 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3488 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3489 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3492 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3497 bool failed = false;
3498 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3499 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3501 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3504 std::string uri = (*item)->DescURI();
3505 std::string error = (*item)->ErrorText;
3507 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3510 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3511 withObject:[NSArray arrayWithObjects:
3512 [NSString stringWithUTF8String:error.c_str()],
3524 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3526 if (_error->PendingError()) {
3531 if (result == pkgPackageManager::Failed) {
3536 if (result != pkgPackageManager::Completed) {
3541 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3543 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3545 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3546 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3549 if (![before isEqualToArray:after])
3554 NSString *title(UCLocalize("UPGRADE"));
3555 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3561 [self updateWithStatus:status_];
3564 - (void) setVisible {
3565 for (Package *package in packages_)
3566 [package setVisible];
3569 - (void) updateWithStatus:(Status &)status {
3570 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3571 NSString *title(UCLocalize("REFRESHING_DATA"));
3574 if (!list.ReadMainList())
3575 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3578 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3579 if ([self popErrorWithTitle:title])
3582 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3583 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */;
3585 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3589 - (void) setDelegate:(id)delegate {
3590 delegate_ = delegate;
3591 status_.setDelegate(delegate);
3592 progress_.setDelegate(delegate);
3595 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3596 SourceMap::const_iterator i(sources_.find(file->ID));
3597 return i == sources_.end() ? nil : i->second;
3603 /* Confirmation Controller {{{ */
3604 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3605 if (!iterator.end())
3606 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3607 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3609 pkgCache::PkgIterator package(dep.TargetPkg());
3612 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3620 /* Web Scripting {{{ */
3621 @interface CydiaObject : NSObject {
3626 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3629 @implementation CydiaObject
3632 [indirect_ release];
3636 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3637 if ((self = [super init]) != nil) {
3638 indirect_ = [indirect retain];
3642 - (void) setDelegate:(id)delegate {
3643 delegate_ = delegate;
3646 + (NSArray *) _attributeKeys {
3647 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3650 - (NSArray *) attributeKeys {
3651 return [[self class] _attributeKeys];
3654 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3655 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3658 - (NSString *) device {
3659 return [[UIDevice currentDevice] uniqueIdentifier];
3662 #if 0 // XXX: implement!
3663 - (NSString *) mac {
3664 if (![indirect_ promptForSensitive:@"Mac Address"])
3668 - (NSString *) serial {
3669 if (![indirect_ promptForSensitive:@"Serial #"])
3673 - (NSString *) firewire {
3674 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3678 - (NSString *) imei {
3679 if (![indirect_ promptForSensitive:@"IMEI"])
3684 + (NSString *) webScriptNameForSelector:(SEL)selector {
3685 if (selector == @selector(close))
3687 else if (selector == @selector(getInstalledPackages))
3688 return @"getInstalledPackages";
3689 else if (selector == @selector(getPackageById:))
3690 return @"getPackageById";
3691 else if (selector == @selector(installPackages:))
3692 return @"installPackages";
3693 else if (selector == @selector(setAutoPopup:))
3694 return @"setAutoPopup";
3695 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3696 return @"setButtonImage";
3697 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3698 return @"setButtonTitle";
3699 else if (selector == @selector(setFinishHook:))
3700 return @"setFinishHook";
3701 else if (selector == @selector(setPopupHook:))
3702 return @"setPopupHook";
3703 else if (selector == @selector(setSpecial:))
3704 return @"setSpecial";
3705 else if (selector == @selector(setToken:))
3707 else if (selector == @selector(setViewportWidth:))
3708 return @"setViewportWidth";
3709 else if (selector == @selector(supports:))
3711 else if (selector == @selector(stringWithFormat:arguments:))
3713 else if (selector == @selector(localizedStringForKey:value:table:))
3715 else if (selector == @selector(du:))
3717 else if (selector == @selector(statfs:))
3723 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3724 return [self webScriptNameForSelector:selector] == nil;
3727 - (BOOL) supports:(NSString *)feature {
3728 return [feature isEqualToString:@"window.open"];
3731 - (NSArray *) getInstalledPackages {
3732 NSArray *packages([[Database sharedInstance] packages]);
3733 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3734 for (Package *package in packages)
3735 if ([package installed] != nil)
3736 [installed addObject:package];
3740 - (Package *) getPackageById:(NSString *)id {
3741 Package *package([[Database sharedInstance] packageWithName:id]);
3746 - (NSArray *) statfs:(NSString *)path {
3749 if (path == nil || statfs([path UTF8String], &stat) == -1)
3752 return [NSArray arrayWithObjects:
3753 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3754 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3755 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3759 - (NSNumber *) du:(NSString *)path {
3760 NSNumber *value(nil);
3763 _assert(pipe(fds) != -1);
3765 pid_t pid(ExecFork());
3767 _assert(dup2(fds[1], 1) != -1);
3768 _assert(close(fds[0]) != -1);
3769 _assert(close(fds[1]) != -1);
3770 /* XXX: this should probably not use du */
3771 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3776 _assert(close(fds[1]) != -1);
3778 if (FILE *du = fdopen(fds[0], "r")) {
3780 while (fgets(line, sizeof(line), du) != NULL) {
3781 size_t length(strlen(line));
3782 while (length != 0 && line[length - 1] == '\n')
3783 line[--length] = '\0';
3784 if (char *tab = strchr(line, '\t')) {
3786 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3791 } else _assert(close(fds[0]));
3795 if (waitpid(pid, &status, 0) == -1)
3798 else _assert(false);
3807 - (void) installPackages:(NSArray *)packages {
3808 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3811 - (void) setAutoPopup:(BOOL)popup {
3812 [indirect_ setAutoPopup:popup];
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) setFinishHook:(id)function {
3837 [indirect_ setFinishHook:function];
3840 - (void) setPopupHook:(id)function {
3841 [indirect_ setPopupHook:function];
3844 - (void) setViewportWidth:(float)width {
3845 [indirect_ setViewportWidth:width];
3848 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3849 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3850 unsigned count([arguments count]);
3852 for (unsigned i(0); i != count; ++i)
3853 values[i] = [arguments objectAtIndex:i];
3854 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3857 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3858 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3860 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3862 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3868 /* Cydia View Controller {{{ */
3869 @interface CYViewController : UCViewController { }
3872 @implementation CYViewController
3875 /* Cydia Browser Controller {{{ */
3876 @interface CYBrowserController : BrowserController {
3877 CydiaObject *cydia_;
3882 @implementation CYBrowserController
3889 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3892 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3893 [super webView:sender didClearWindowObject:window forFrame:frame];
3895 WebDataSource *source([frame dataSource]);
3896 NSURLResponse *response([source response]);
3897 NSURL *url([response URL]);
3898 NSString *scheme([url scheme]);
3900 NSHTTPURLResponse *http;
3901 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3902 http = (NSHTTPURLResponse *) response;
3906 NSDictionary *headers([http allHeaderFields]);
3907 NSString *host([url host]);
3908 [self setHeaders:headers forHost:host];
3911 [host isEqualToString:@"cydia.saurik.com"] ||
3912 [host hasSuffix:@".cydia.saurik.com"] ||
3913 [scheme isEqualToString:@"file"]
3915 [window setValue:cydia_ forKey:@"cydia"];
3918 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3919 if (System_ != NULL)
3920 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3921 if (Machine_ != NULL)
3922 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3924 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3926 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3929 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3930 NSMutableURLRequest *copy = [request mutableCopy];
3931 [self _setMoreHeaders:copy];
3935 - (void) setDelegate:(id)delegate {
3936 [super setDelegate:delegate];
3937 [cydia_ setDelegate:delegate];
3941 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3942 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3944 WebView *webview([document_ webView]);
3946 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3948 NSString *application = package == nil ? @"Cydia" : [NSString
3949 stringWithFormat:@"Cydia/%@",
3954 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3956 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3957 if (Product_ != nil)
3958 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3960 [webview setApplicationNameForUserAgent:application];
3967 /* Confirmation {{{ */
3968 @protocol ConfirmationControllerDelegate
3969 - (void) cancelAndClear:(bool)clear;
3970 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3974 @interface ConfirmationController : CYBrowserController {
3975 _transient Database *database_;
3976 UIAlertView *essential_;
3983 - (id) initWithDatabase:(Database *)database;
3987 @implementation ConfirmationController
3994 if (essential_ != nil)
3995 [essential_ release];
3999 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4000 NSString *context([alert context]);
4002 if ([context isEqualToString:@"remove"]) {
4003 if (button == [alert cancelButtonIndex]) {
4004 [self dismissModalViewControllerAnimated:YES];
4005 } else if (button == [alert firstOtherButtonIndex]) {
4008 [delegate_ confirmWithNavigationController:[self navigationController]];
4011 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4012 } else if ([context isEqualToString:@"unable"]) {
4013 [self dismissModalViewControllerAnimated:YES];
4014 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4016 [super alertView:alert clickedButtonAtIndex:button];
4020 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4021 [self dismissModalViewControllerAnimated:YES];
4022 [delegate_ cancelAndClear:NO];
4027 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4028 [super webView:sender didClearWindowObject:window forFrame:frame];
4029 [window setValue:changes_ forKey:@"changes"];
4030 [window setValue:issues_ forKey:@"issues"];
4031 [window setValue:sizes_ forKey:@"sizes"];
4032 [window setValue:self forKey:@"queue"];
4035 - (id) initWithDatabase:(Database *)database {
4036 if ((self = [super init]) != nil) {
4037 database_ = database;
4039 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4041 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4042 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4043 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4044 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4045 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4049 pkgDepCache::Policy *policy([database_ policy]);
4051 pkgCacheFile &cache([database_ cache]);
4052 NSArray *packages = [database_ packages];
4053 for (Package *package in packages) {
4054 pkgCache::PkgIterator iterator = [package iterator];
4055 pkgDepCache::StateCache &state(cache[iterator]);
4057 NSString *name([package name]);
4059 if (state.NewInstall())
4060 [installing addObject:name];
4061 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4062 [reinstalling addObject:name];
4063 else if (state.Upgrade())
4064 [upgrading addObject:name];
4065 else if (state.Downgrade())
4066 [downgrading addObject:name];
4067 else if (state.Delete()) {
4068 if ([package essential])
4070 [removing addObject:name];
4073 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4074 substrate_ |= DepSubstrate(iterator.CurrentVer());
4079 else if (Advanced_) {
4080 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4082 essential_ = [[UIAlertView alloc]
4083 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4084 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4086 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4087 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4090 [essential_ setContext:@"remove"];
4092 essential_ = [[UIAlertView alloc]
4093 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4094 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4096 cancelButtonTitle:UCLocalize("OKAY")
4097 otherButtonTitles:nil
4100 [essential_ setContext:@"unable"];
4103 changes_ = [[NSArray alloc] initWithObjects:
4111 issues_ = [database_ issues];
4113 issues_ = [issues_ retain];
4115 sizes_ = [[NSArray alloc] initWithObjects:
4116 SizeString([database_ fetcher].FetchNeeded()),
4117 SizeString([database_ fetcher].PartialPresent()),
4120 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4122 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
4123 initWithTitle:UCLocalize("CANCEL")
4124 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4125 style:UIBarButtonItemStylePlain
4127 action:@selector(cancelButtonClicked)
4129 [[self navigationItem] setLeftBarButtonItem:leftItem];
4134 - (void) applyRightButton {
4135 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
4136 initWithTitle:UCLocalize("CONFIRM")
4137 style:UIBarButtonItemStylePlain
4139 action:@selector(confirmButtonClicked)
4141 #if !AlwaysReload && !IgnoreInstall
4142 if (issues_ == nil && ![self isLoading]) [[self navigationItem] setRightBarButtonItem:rightItem];
4143 else [super applyRightButton];
4145 [[self navigationItem] setRightBarButtonItem:nil];
4147 [rightItem release];
4150 - (void) cancelButtonClicked {
4151 [self dismissModalViewControllerAnimated:YES];
4152 [delegate_ cancelAndClear:YES];
4156 - (void) confirmButtonClicked {
4160 if (essential_ != nil)
4165 [delegate_ confirmWithNavigationController:[self navigationController]];
4173 /* Progress Data {{{ */
4174 @interface ProgressData : NSObject {
4180 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4187 @implementation ProgressData
4189 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4190 if ((self = [super init]) != nil) {
4191 selector_ = selector;
4211 /* Progress Controller {{{ */
4212 @interface ProgressController : CYViewController <
4213 ConfigurationDelegate,
4216 _transient Database *database_;
4217 UIProgressBar *progress_;
4218 UITextView *output_;
4219 UITextLabel *status_;
4220 UIPushButton *close_;
4222 SHA1SumValue springlist_;
4223 SHA1SumValue notifyconf_;
4227 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4229 - (void) _retachThread;
4230 - (void) _detachNewThreadData:(ProgressData *)data;
4231 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4237 @protocol ProgressControllerDelegate
4238 - (void) progressControllerIsComplete:(ProgressController *)sender;
4241 @implementation ProgressController
4244 [database_ setDelegate:nil];
4245 [progress_ release];
4254 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4255 if ((self = [super init]) != nil) {
4256 database_ = database;
4257 [database_ setDelegate:self];
4258 delegate_ = delegate;
4260 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4262 progress_ = [[UIProgressBar alloc] init];
4263 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4264 [progress_ setStyle:0];
4266 status_ = [[UITextLabel alloc] init];
4267 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4268 [status_ setColor:[UIColor whiteColor]];
4269 [status_ setBackgroundColor:[UIColor clearColor]];
4270 [status_ setCentersHorizontally:YES];
4271 //[status_ setFont:font];
4273 output_ = [[UITextView alloc] init];
4275 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4276 //[output_ setTextFont:@"Courier New"];
4277 [output_ setFont:[[output_ font] fontWithSize:12]];
4278 [output_ setTextColor:[UIColor whiteColor]];
4279 [output_ setBackgroundColor:[UIColor clearColor]];
4280 [output_ setMarginTop:0];
4281 [output_ setAllowsRubberBanding:YES];
4282 [output_ setEditable:NO];
4283 [[self view] addSubview:output_];
4285 close_ = [[UIPushButton alloc] init];
4286 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4287 [close_ setAutosizesToFit:NO];
4288 [close_ setDrawsShadow:YES];
4289 [close_ setStretchBackground:YES];
4290 [close_ setEnabled:YES];
4291 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4292 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4293 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4294 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4298 - (void) positionViews {
4299 CGRect bounds = [[self view] bounds];
4300 CGSize prgsize = [UIProgressBar defaultSize];
4303 (bounds.size.width - prgsize.width) / 2,
4304 bounds.size.height - prgsize.height - 64
4307 float closewidth = bounds.size.width - 20;
4308 if (closewidth > 300) closewidth = 300;
4310 [progress_ setFrame:prgrect];
4311 [status_ setFrame:CGRectMake(
4313 bounds.size.height - prgsize.height - 94,
4314 bounds.size.width - 20,
4317 [output_ setFrame:CGRectMake(
4320 bounds.size.width - 20,
4321 bounds.size.height - 106
4323 [close_ setFrame:CGRectMake(
4324 (bounds.size.width - closewidth) / 2,
4325 bounds.size.height - prgsize.height - 94,
4331 - (void) viewWillAppear:(BOOL)animated {
4332 [super viewDidAppear:animated];
4333 [[self navigationItem] setHidesBackButton:YES];
4334 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4336 [self positionViews];
4339 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4340 [self positionViews];
4343 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4344 NSString *context([alert context]);
4346 if ([context isEqualToString:@"conffile"]) {
4347 FILE *input = [database_ input];
4348 if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
4349 else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
4354 - (void) closeButtonPushed {
4357 UpdateExternalStatus(0);
4361 [self dismissModalViewControllerAnimated:YES];
4365 [delegate_ terminateWithSuccess];
4366 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4367 [delegate_ suspendWithAnimation:YES];
4369 [delegate_ suspend];*/
4373 system("launchctl stop com.apple.SpringBoard");
4377 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4386 - (void) _retachThread {
4387 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4389 [[self view] addSubview:close_];
4390 [progress_ removeFromSuperview];
4391 [status_ removeFromSuperview];
4393 [database_ popErrorWithTitle:title_];
4394 [delegate_ progressControllerIsComplete:self];
4398 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4401 MMap mmap(file, MMap::ReadOnly);
4403 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4404 if (!(notifyconf_ == sha1.Result()))
4411 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4414 MMap mmap(file, MMap::ReadOnly);
4416 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4417 if (!(springlist_ == sha1.Result()))
4423 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4424 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4425 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4426 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4427 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4430 system("su -c /usr/bin/uicache mobile");
4432 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4434 [delegate_ setStatusBarShowsProgress:NO];
4437 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4438 [[data target] performSelector:[data selector] withObject:[data object]];
4441 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4444 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4445 UpdateExternalStatus(1);
4452 title_ = [title retain];
4454 [[self navigationItem] setTitle:title_];
4456 [status_ setText:nil];
4457 [output_ setText:@""];
4458 [progress_ setProgress:0];
4460 [close_ removeFromSuperview];
4461 [[self view] addSubview:progress_];
4462 [[self view] addSubview:status_];
4464 [delegate_ setStatusBarShowsProgress:YES];
4469 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4472 MMap mmap(file, MMap::ReadOnly);
4474 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4475 notifyconf_ = sha1.Result();
4481 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4484 MMap mmap(file, MMap::ReadOnly);
4486 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4487 springlist_ = sha1.Result();
4492 detachNewThreadSelector:@selector(_detachNewThreadData:)
4494 withObject:[[ProgressData alloc]
4495 initWithSelector:selector
4502 - (void) repairWithSelector:(SEL)selector {
4504 detachNewThreadSelector:selector
4507 title:UCLocalize("REPAIRING")
4511 - (void) setConfigurationData:(NSString *)data {
4513 performSelectorOnMainThread:@selector(_setConfigurationData:)
4519 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4520 CYActionSheet *sheet([[[CYActionSheet alloc]
4522 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4523 defaultButtonIndex:0
4526 [sheet setMessage:error];
4527 [sheet yieldToPopupAlertAnimated:YES];
4531 - (void) setProgressTitle:(NSString *)title {
4533 performSelectorOnMainThread:@selector(_setProgressTitle:)
4539 - (void) setProgressPercent:(float)percent {
4541 performSelectorOnMainThread:@selector(_setProgressPercent:)
4542 withObject:[NSNumber numberWithFloat:percent]
4547 - (void) startProgress {
4550 - (void) addProgressOutput:(NSString *)output {
4552 performSelectorOnMainThread:@selector(_addProgressOutput:)
4558 - (bool) isCancelling:(size_t)received {
4562 - (void) _setConfigurationData:(NSString *)data {
4563 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4565 if (!conffile_r(data)) {
4566 lprintf("E:invalid conffile\n");
4570 NSString *ofile = conffile_r[1];
4571 //NSString *nfile = conffile_r[2];
4573 UIAlertView *alert = [[[UIAlertView alloc]
4574 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4575 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4577 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4578 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4579 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4583 [alert setContext:@"conffile"];
4587 - (void) _setProgressTitle:(NSString *)title {
4588 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4589 for (size_t i(0), e([words count]); i != e; ++i) {
4590 NSString *word([words objectAtIndex:i]);
4591 if (Package *package = [database_ packageWithName:word])
4592 [words replaceObjectAtIndex:i withObject:[package name]];
4595 [status_ setText:[words componentsJoinedByString:@" "]];
4598 - (void) _setProgressPercent:(NSNumber *)percent {
4599 [progress_ setProgress:[percent floatValue]];
4602 - (void) _addProgressOutput:(NSString *)output {
4603 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4604 CGSize size = [output_ contentSize];
4605 CGRect rect = {{0, size.height}, {size.width, 0}};
4606 [output_ scrollRectToVisible:rect animated:YES];
4609 - (BOOL) isRunning {
4616 /* Cell Content View {{{ */
4617 @protocol ContentDelegate
4618 - (void) drawContentRect:(CGRect)rect;
4621 @interface ContentView : UIView {
4622 _transient id<ContentDelegate> delegate_;
4627 @implementation ContentView
4628 - (id) initWithFrame:(CGRect)frame {
4629 if ((self = [super initWithFrame:frame]) != nil) {
4630 /* Fix landscape stretching. */
4631 [self setNeedsDisplayOnBoundsChange:YES];
4635 - (void) setDelegate:(id<ContentDelegate>)delegate {
4636 delegate_ = delegate;
4639 - (void) drawRect:(CGRect)rect {
4640 [super drawRect:rect];
4641 [delegate_ drawContentRect:rect];
4645 /* Package Cell {{{ */
4646 @interface PackageCell : UITableViewCell <
4651 NSString *description_;
4657 ContentView *content_;
4663 - (PackageCell *) init;
4664 - (void) setPackage:(Package *)package;
4666 + (int) heightForPackage:(Package *)package;
4667 - (void) drawContentRect:(CGRect)rect;
4671 @implementation PackageCell
4673 - (void) clearPackage {
4684 if (description_ != nil) {
4685 [description_ release];
4689 if (source_ != nil) {
4694 if (badge_ != nil) {
4699 if (placard_ != nil) {
4709 [self clearPackage];
4716 return faded_ ? [self selectionPercent] : fade_;
4719 - (PackageCell *) init {
4720 CGRect frame(CGRectMake(0, 0, 320, 74));
4721 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4722 UIView *content([self contentView]);
4723 CGRect bounds([content bounds]);
4725 content_ = [[ContentView alloc] initWithFrame:bounds];
4726 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4727 [content addSubview:content_];
4729 [content_ setDelegate:self];
4730 [content_ setOpaque:YES];
4731 if ([self respondsToSelector:@selector(selectionPercent)])
4736 - (void) _setBackgroundColor {
4738 if (NSString *mode = [package_ mode]) {
4739 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4740 color = remove ? RemovingColor_ : InstallingColor_;
4742 color = [UIColor whiteColor];
4744 [content_ setBackgroundColor:color];
4745 [self setNeedsDisplay];
4748 - (void) setPackage:(Package *)package {
4749 [self clearPackage];
4752 Source *source = [package source];
4754 icon_ = [[package icon] retain];
4755 name_ = [[package name] retain];
4758 description_ = [package longDescription];
4759 if (description_ == nil)
4760 description_ = [package shortDescription];
4761 if (description_ != nil)
4762 description_ = [description_ retain];
4764 commercial_ = [package isCommercial];
4766 package_ = [package retain];
4768 NSString *label = nil;
4769 bool trusted = false;
4771 if (source != nil) {
4772 label = [source label];
4773 trusted = [source trusted];
4774 } else if ([[package id] isEqualToString:@"firmware"])
4775 label = UCLocalize("APPLE");
4777 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4779 NSString *from(label);
4781 NSString *section = [package simpleSection];
4782 if (section != nil && ![section isEqualToString:label]) {
4783 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4784 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4787 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4788 source_ = [from retain];
4790 if (NSString *purpose = [package primaryPurpose])
4791 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4792 badge_ = [badge_ retain];
4794 if ([package installed] != nil)
4795 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4796 placard_ = [placard_ retain];
4798 [self _setBackgroundColor];
4799 [content_ setNeedsDisplay];
4802 - (void) drawContentRect:(CGRect)rect {
4803 bool selected([self isSelected]);
4804 float width([self bounds].size.width);
4807 CGContextRef context(UIGraphicsGetCurrentContext());
4808 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4809 CGContextFillRect(context, rect);
4814 rect.size = [icon_ size];
4816 rect.size.width /= 2;
4817 rect.size.height /= 2;
4819 rect.origin.x = 25 - rect.size.width / 2;
4820 rect.origin.y = 25 - rect.size.height / 2;
4822 [icon_ drawInRect:rect];
4825 if (badge_ != nil) {
4826 CGSize size = [badge_ size];
4828 [badge_ drawAtPoint:CGPointMake(
4829 36 - size.width / 2,
4830 36 - size.height / 2
4838 UISetColor(commercial_ ? Purple_ : Black_);
4839 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4840 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4843 UISetColor(commercial_ ? Purplish_ : Gray_);
4844 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4846 if (placard_ != nil)
4847 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4850 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4851 //[self _setBackgroundColor];
4852 [super setSelected:selected animated:fade];
4853 [content_ setNeedsDisplay];
4856 + (int) heightForPackage:(Package *)package {
4862 /* Section Cell {{{ */
4863 @interface SectionCell : UITableViewCell <
4871 ContentView *content_;
4876 - (void) setSection:(Section *)section editing:(BOOL)editing;
4880 @implementation SectionCell
4882 - (void) clearSection {
4883 if (basic_ != nil) {
4888 if (section_ != nil) {
4898 if (count_ != nil) {
4905 [self clearSection];
4913 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4914 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4915 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4916 switch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4917 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4919 UIView *content([self contentView]);
4920 CGRect bounds([content bounds]);
4922 content_ = [[ContentView alloc] initWithFrame:bounds];
4923 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4924 [content addSubview:content_];
4925 [content_ setBackgroundColor:[UIColor whiteColor]];
4927 [content_ setDelegate:self];
4931 - (void) onSwitch:(id)sender {
4932 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4933 if (metadata == nil) {
4934 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4935 [Sections_ setObject:metadata forKey:basic_];
4939 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4942 - (void) setSection:(Section *)section editing:(BOOL)editing {
4943 if (editing != editing_) {
4945 [switch_ removeFromSuperview];
4947 [self addSubview:switch_];
4951 [self clearSection];
4953 if (section == nil) {
4954 name_ = [UCLocalize("ALL_PACKAGES") retain];
4957 basic_ = [section name];
4959 basic_ = [basic_ retain];
4961 section_ = [section localized];
4962 if (section_ != nil)
4963 section_ = [section_ retain];
4965 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4966 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4969 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4972 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4973 [content_ setNeedsDisplay];
4976 - (void) setFrame:(CGRect)frame {
4977 [super setFrame:frame];
4979 CGRect rect([switch_ frame]);
4980 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4983 - (void) drawContentRect:(CGRect)rect {
4984 BOOL selected = [self isSelected];
4986 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4994 float width(rect.size.width);
4998 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5000 CGSize size = [count_ sizeWithFont:Font14_];
5004 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5010 /* File Table {{{ */
5011 @interface FileTable : CYViewController <
5012 UITableViewDataSource,
5015 _transient Database *database_;
5018 NSMutableArray *files_;
5022 - (id) initWithDatabase:(Database *)database;
5023 - (void) setPackage:(Package *)package;
5027 @implementation FileTable
5030 if (package_ != nil)
5039 - (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
5040 return files_ == nil ? 0 : [files_ count];
5043 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5047 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5048 static NSString *reuseIdentifier = @"Cell";
5050 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5052 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5053 [cell setFont:[UIFont systemFontOfSize:16]];
5055 [cell setText:[files_ objectAtIndex:indexPath.row]];
5056 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5061 - (id) initWithDatabase:(Database *)database {
5062 if ((self = [super init]) != nil) {
5063 database_ = database;
5065 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5067 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5069 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5070 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5071 [list_ setRowHeight:24.0f];
5072 [[self view] addSubview:list_];
5074 [list_ setDataSource:self];
5075 [list_ setDelegate:self];
5079 - (void) setPackage:(Package *)package {
5080 if (package_ != nil) {
5081 [package_ autorelease];
5090 [files_ removeAllObjects];
5092 if (package != nil) {
5093 package_ = [package retain];
5094 name_ = [[package id] retain];
5096 if (NSArray *files = [package files])
5097 [files_ addObjectsFromArray:files];
5099 if ([files_ count] != 0) {
5100 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5101 [files_ removeObjectAtIndex:0];
5102 [files_ sortUsingSelector:@selector(compareByPath:)];
5104 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5105 [stack addObject:@"/"];
5107 for (int i(0), e([files_ count]); i != e; ++i) {
5108 NSString *file = [files_ objectAtIndex:i];
5109 while (![file hasPrefix:[stack lastObject]])
5110 [stack removeLastObject];
5111 NSString *directory = [stack lastObject];
5112 [stack addObject:[file stringByAppendingString:@"/"]];
5113 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5114 ([stack count] - 2) * 3, "",
5115 [file substringFromIndex:[directory length]]
5124 - (void) reloadData {
5125 [self setPackage:[database_ packageWithName:name_]];
5130 /* Package Controller {{{ */
5131 @interface PackageController : CYBrowserController <
5132 UIActionSheetDelegate
5134 _transient Database *database_;
5138 NSMutableArray *buttons_;
5141 - (id) initWithDatabase:(Database *)database;
5142 - (void) setPackage:(Package *)package;
5146 @implementation PackageController
5149 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 *)sender didFinishLoadForFrame:(WebFrame *)frame {
5192 return [super webView:sender didFinishLoadForFrame:frame];
5195 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5196 [super webView:sender didClearWindowObject:window forFrame:frame];
5197 [window setValue:package_ forKey:@"package"];
5200 - (bool) _allowJavaScriptPanel {
5205 - (void) _customButtonClicked {
5206 int count([buttons_ count]);
5211 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5213 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5214 [buttons addObjectsFromArray:buttons_];
5216 UIActionSheet *sheet = [[[UIActionSheet alloc]
5219 cancelButtonTitle:nil
5220 destructiveButtonTitle:nil
5221 otherButtonTitles:nil
5224 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5226 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5227 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5229 [sheet setContext:@"modify"];
5231 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5235 // We don't want to allow non-commercial packages to do custom things to the install button,
5236 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5237 - (void) customButtonClicked {
5239 [super customButtonClicked];
5241 [self _customButtonClicked];
5244 - (void) reloadButtonClicked {
5245 // Don't reload a package view by clicking the button.
5248 - (void) applyLoadingTitle {
5249 // Don't show "Loading" as the title. Ever.
5252 - (UIBarButtonItem *) rightButton {
5253 int count = [buttons_ count];
5254 return [[[UIBarButtonItem alloc]
5255 initWithTitle:count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0]
5256 style:UIBarButtonItemStylePlain
5258 action:@selector(customButtonClicked)
5263 - (id) initWithDatabase:(Database *)database {
5264 if ((self = [super init]) != nil) {
5265 database_ = database;
5266 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5267 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5271 - (void) setPackage:(Package *)package {
5272 if (package_ != nil) {
5273 [package_ autorelease];
5282 [buttons_ removeAllObjects];
5284 if (package != nil) {
5287 package_ = [package retain];
5288 name_ = [[package id] retain];
5289 commercial_ = [package isCommercial];
5291 if ([package_ mode] != nil)
5292 [buttons_ addObject:UCLocalize("CLEAR")];
5293 if ([package_ source] == nil);
5294 else if ([package_ upgradableAndEssential:NO])
5295 [buttons_ addObject:UCLocalize("UPGRADE")];
5296 else if ([package_ uninstalled])
5297 [buttons_ addObject:UCLocalize("INSTALL")];
5299 [buttons_ addObject:UCLocalize("REINSTALL")];
5300 if (![package_ uninstalled])
5301 [buttons_ addObject:UCLocalize("REMOVE")];
5303 if (special_ != NULL) {
5304 CGRect frame([document_ frame]);
5305 frame.size.height = 0;
5306 [document_ setFrame:frame];
5308 if ([scroller_ respondsToSelector:@selector(scrollPointVisibleAtTopLeft:)])
5309 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5311 [scroller_ scrollRectToVisible:CGRectZero animated:NO];
5314 [[[document_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5316 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5318 [self setFinishHook:nil];
5319 [self setPopupHook:nil];
5322 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5323 [super callFunction:special_];
5328 - (bool) isLoading {
5329 return commercial_ ? [super isLoading] : false;
5332 - (void) reloadData {
5333 [self setPackage:[database_ packageWithName:name_]];
5338 /* Package Table {{{ */
5339 @interface PackageTable : UIView <
5340 UITableViewDataSource,
5343 _transient Database *database_;
5344 NSMutableArray *packages_;
5345 NSMutableArray *sections_;
5347 NSMutableArray *index_;
5348 NSMutableDictionary *indices_;
5354 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5356 - (void) setDelegate:(id)delegate;
5358 - (void) reloadData;
5359 - (void) resetCursor;
5361 - (UITableView *) list;
5363 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5365 - (void) deselectWithAnimation:(BOOL)animated;
5369 @implementation PackageTable
5372 [packages_ release];
5373 [sections_ release];
5381 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5382 NSInteger count([sections_ count]);
5383 return count == 0 ? 1 : count;
5386 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5387 if ([sections_ count] == 0)
5389 return [[sections_ objectAtIndex:section] name];
5392 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5393 if ([sections_ count] == 0)
5395 return [[sections_ objectAtIndex:section] count];
5398 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5399 Section *section([sections_ objectAtIndex:[path section]]);
5400 NSInteger row([path row]);
5401 Package *package([packages_ objectAtIndex:([section row] + row)]);
5405 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5406 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5408 cell = [[[PackageCell alloc] init] autorelease];
5409 [cell setPackage:[self packageAtIndexPath:path]];
5413 - (void) deselectWithAnimation:(BOOL)animated {
5414 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5417 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5418 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5421 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5422 Package *package([self packageAtIndexPath:path]);
5423 package = [database_ packageWithName:[package id]];
5424 [target_ performSelector:action_ withObject:package];
5428 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5429 return [packages_ count] > 20 ? index_ : nil;
5432 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5436 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5437 if ((self = [super initWithFrame:frame]) != nil) {
5438 database_ = database;
5443 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5444 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5446 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5447 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5449 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5450 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5451 [list_ setRowHeight:73.0f];
5452 [self addSubview:list_];
5454 [list_ setDataSource:self];
5455 [list_ setDelegate:self];
5459 - (void) setDelegate:(id)delegate {
5460 delegate_ = delegate;
5463 - (bool) hasPackage:(Package *)package {
5467 - (void) reloadData {
5468 NSArray *packages = [database_ packages];
5470 [packages_ removeAllObjects];
5471 [sections_ removeAllObjects];
5473 _profile(PackageTable$reloadData$Filter)
5474 for (Package *package in packages)
5475 if ([self hasPackage:package])
5476 [packages_ addObject:package];
5479 [index_ removeAllObjects];
5480 [indices_ removeAllObjects];
5482 Section *section = nil;
5484 _profile(PackageTable$reloadData$Section)
5485 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5489 _profile(PackageTable$reloadData$Section$Package)
5490 package = [packages_ objectAtIndex:offset];
5491 index = [package index];
5494 if (section == nil || [section index] != index) {
5495 _profile(PackageTable$reloadData$Section$Allocate)
5496 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5499 [index_ addObject:[section name]];
5500 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5502 _profile(PackageTable$reloadData$Section$Add)
5503 [sections_ addObject:section];
5507 [section addToCount];
5511 _profile(PackageTable$reloadData$List)
5516 - (void) resetCursor {
5517 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5520 - (UITableView *) list {
5524 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5525 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5530 /* Filtered Package Table {{{ */
5531 @interface FilteredPackageTable : PackageTable {
5537 - (void) setObject:(id)object;
5538 - (void) setObject:(id)object forFilter:(SEL)filter;
5540 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5544 @implementation FilteredPackageTable
5552 - (void) setFilter:(SEL)filter {
5555 /* XXX: this is an unsafe optimization of doomy hell */
5556 Method method(class_getInstanceMethod([Package class], filter));
5557 _assert(method != NULL);
5558 imp_ = method_getImplementation(method);
5559 _assert(imp_ != NULL);
5562 - (void) setObject:(id)object {
5568 object_ = [object retain];
5571 - (void) setObject:(id)object forFilter:(SEL)filter {
5572 [self setFilter:filter];
5573 [self setObject:object];
5576 - (bool) hasPackage:(Package *)package {
5577 _profile(FilteredPackageTable$hasPackage)
5578 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5582 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5583 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5584 [self setFilter:filter];
5585 object_ = [object retain];
5593 /* Filtered Package Controller {{{ */
5594 @interface FilteredPackageController : CYViewController {
5595 _transient Database *database_;
5596 FilteredPackageTable *packages_;
5600 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5604 @implementation FilteredPackageController
5607 [packages_ release];
5613 - (void) viewDidAppear:(BOOL)animated {
5614 [super viewDidAppear:animated];
5615 [packages_ deselectWithAnimation:animated];
5618 - (void) didSelectPackage:(Package *)package {
5619 PackageController *view([delegate_ packageController]);
5620 [view setPackage:package];
5621 [view setDelegate:delegate_];
5622 [[self navigationController] pushViewController:view animated:YES];
5625 - (id) title { return title_; }
5627 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5628 if ((self = [super init]) != nil) {
5629 database_ = database;
5630 title_ = [title copy];
5631 [[self navigationItem] setTitle:title_];
5633 packages_ = [[FilteredPackageTable alloc]
5634 initWithFrame:[[self view] bounds]
5637 action:@selector(didSelectPackage:)
5642 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5643 [[self view] addSubview:packages_];
5647 - (void) reloadData {
5648 [packages_ reloadData];
5651 - (void) setDelegate:(id)delegate {
5652 [super setDelegate:delegate];
5653 [packages_ setDelegate:delegate];
5660 /* Add Source Controller {{{ */
5661 @interface AddSourceController : CYViewController {
5662 _transient Database *database_;
5665 - (id) initWithDatabase:(Database *)database;
5669 @implementation AddSourceController
5671 - (id) initWithDatabase:(Database *)database {
5672 if ((self = [super init]) != nil) {
5673 database_ = database;
5679 /* Source Cell {{{ */
5680 @interface SourceCell : UITableViewCell <
5685 NSString *description_;
5687 ContentView *content_;
5690 - (void) setSource:(Source *)source;
5694 @implementation SourceCell
5696 - (void) clearSource {
5699 [description_ release];
5708 - (void) setSource:(Source *)source {
5712 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5714 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5715 icon_ = [icon_ retain];
5717 origin_ = [[source name] retain];
5718 label_ = [[source uri] retain];
5719 description_ = [[source description] retain];
5721 [content_ setNeedsDisplay];
5730 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5731 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5732 UIView *content([self contentView]);
5733 CGRect bounds([content bounds]);
5735 content_ = [[ContentView alloc] initWithFrame:bounds];
5736 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5737 [content_ setBackgroundColor:[UIColor whiteColor]];
5738 [content addSubview:content_];
5740 [content_ setDelegate:self];
5741 [content_ setOpaque:YES];
5745 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5746 [super setSelected:selected animated:animated];
5747 [content_ setNeedsDisplay];
5750 - (void) drawContentRect:(CGRect)rect {
5751 bool selected([self isSelected]);
5752 float width(rect.size.width);
5755 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5762 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5766 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5770 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5775 /* Source Table {{{ */
5776 @interface SourceTable : CYViewController <
5777 UITableViewDataSource,
5780 _transient Database *database_;
5782 NSMutableArray *sources_;
5786 UIProgressHUD *hud_;
5789 //NSURLConnection *installer_;
5790 NSURLConnection *trivial_;
5791 NSURLConnection *trivial_bz2_;
5792 NSURLConnection *trivial_gz_;
5793 //NSURLConnection *automatic_;
5798 - (id) initWithDatabase:(Database *)database;
5800 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5804 @implementation SourceTable
5806 - (void) _deallocConnection:(NSURLConnection *)connection {
5807 if (connection != nil) {
5808 [connection cancel];
5809 //[connection setDelegate:nil];
5810 [connection release];
5822 //[self _deallocConnection:installer_];
5823 [self _deallocConnection:trivial_];
5824 [self _deallocConnection:trivial_gz_];
5825 [self _deallocConnection:trivial_bz2_];
5826 //[self _deallocConnection:automatic_];
5833 - (void) viewDidAppear:(BOOL)animated {
5834 [super viewDidAppear:animated];
5835 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5838 - (int) numberOfSectionsInTableView:(UITableView *)tableView {
5839 return offset_ == 0 ? 1 : 2;
5842 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(int)section {
5843 switch (section + (offset_ == 0 ? 1 : 0)) {
5844 case 0: return UCLocalize("ENTERED_BY_USER");
5845 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5851 - (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
5852 int count = [sources_ count];
5854 case 0: return (offset_ == 0 ? count : offset_);
5855 case 1: return count - offset_;
5861 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5863 switch (indexPath.section) {
5864 case 0: idx = indexPath.row; break;
5865 case 1: idx = indexPath.row + offset_; break;
5869 return [sources_ objectAtIndex:idx];
5872 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5873 Source *source = [self sourceAtIndexPath:indexPath];
5874 return [source description] == nil ? 56 : 73;
5877 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5878 static NSString *cellIdentifier = @"SourceCell";
5880 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5881 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5882 [cell setSource:[self sourceAtIndexPath:indexPath]];
5887 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5888 return UITableViewCellAccessoryDisclosureIndicator;
5891 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5892 Source *source = [self sourceAtIndexPath:indexPath];
5894 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5895 initWithDatabase:database_
5896 title:[source label]
5897 filter:@selector(isVisibleInSource:)
5901 [packages setDelegate:delegate_];
5903 [[self navigationController] pushViewController:packages animated:YES];
5906 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5907 Source *source = [self sourceAtIndexPath:indexPath];
5908 return [source record] != nil;
5911 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5912 Source *source = [self sourceAtIndexPath:indexPath];
5913 [Sources_ removeObjectForKey:[source key]];
5914 [delegate_ syncData];
5918 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5921 @"./", @"Distribution",
5922 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5924 [delegate_ syncData];
5927 - (NSString *) getWarning {
5928 NSString *href(href_);
5929 NSRange colon([href rangeOfString:@"://"]);
5930 if (colon.location != NSNotFound)
5931 href = [href substringFromIndex:(colon.location + 3)];
5932 href = [href stringByAddingPercentEscapes];
5933 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5934 href = [href stringByCachingURLWithCurrentCDN];
5936 NSURL *url([NSURL URLWithString:href]);
5938 NSStringEncoding encoding;
5939 NSError *error(nil);
5941 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5942 return [warning length] == 0 ? nil : warning;
5946 - (void) _endConnection:(NSURLConnection *)connection {
5947 NSURLConnection **field = NULL;
5948 if (connection == trivial_)
5950 else if (connection == trivial_bz2_)
5951 field = &trivial_bz2_;
5952 else if (connection == trivial_gz_)
5953 field = &trivial_gz_;
5954 _assert(field != NULL);
5955 [connection release];
5960 trivial_bz2_ == nil &&
5966 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5969 UIAlertView *alert = [[[UIAlertView alloc]
5970 initWithTitle:UCLocalize("SOURCE_WARNING")
5973 cancelButtonTitle:UCLocalize("CANCEL")
5974 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5977 [alert setContext:@"warning"];
5978 [alert setNumberOfRows:1];
5982 } else if (error_ != nil) {
5983 UIAlertView *alert = [[[UIAlertView alloc]
5984 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5985 message:[error_ localizedDescription]
5987 cancelButtonTitle:UCLocalize("OK")
5988 otherButtonTitles:nil
5991 [alert setContext:@"urlerror"];
5994 UIAlertView *alert = [[[UIAlertView alloc]
5995 initWithTitle:UCLocalize("NOT_REPOSITORY")
5996 message:UCLocalize("NOT_REPOSITORY_EX")
5998 cancelButtonTitle:UCLocalize("OK")
5999 otherButtonTitles:nil
6002 [alert setContext:@"trivial"];
6006 [delegate_ setStatusBarShowsProgress:NO];
6007 [delegate_ removeProgressHUD:hud_];
6017 if (error_ != nil) {
6024 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6025 switch ([response statusCode]) {
6031 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6032 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6034 error_ = [error retain];
6035 [self _endConnection:connection];
6038 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6039 [self _endConnection:connection];
6042 - (id)title { return UCLocalize("SOURCES"); }
6044 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6045 NSMutableURLRequest *request = [NSMutableURLRequest
6046 requestWithURL:[NSURL URLWithString:href]
6047 cachePolicy:NSURLRequestUseProtocolCachePolicy
6048 timeoutInterval:120.0
6051 [request setHTTPMethod:method];
6053 if (Machine_ != NULL)
6054 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6055 if (UniqueID_ != nil)
6056 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6058 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6060 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6063 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6064 NSString *context([alert context]);
6066 if ([context isEqualToString:@"source"]) {
6069 NSString *href = [[alert textField] text];
6071 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6073 if (![href hasSuffix:@"/"])
6074 href_ = [href stringByAppendingString:@"/"];
6077 href_ = [href_ retain];
6079 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6080 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6081 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6082 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6086 hud_ = [[delegate_ addProgressHUD] retain];
6087 [hud_ setText:UCLocalize("VERIFYING_URL")];
6096 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6097 } else if ([context isEqualToString:@"trivial"])
6098 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6099 else if ([context isEqualToString:@"urlerror"])
6100 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6101 else if ([context isEqualToString:@"warning"]) {
6116 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6120 - (id) initWithDatabase:(Database *)database {
6121 if ((self = [super init]) != nil) {
6122 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6123 [self updateButtonsForEditingStatus:NO animated:NO];
6125 database_ = database;
6126 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6128 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6129 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6130 [[self view] addSubview:list_];
6132 [list_ setDataSource:self];
6133 [list_ setDelegate:self];
6139 - (void) reloadData {
6141 if (!list.ReadMainList())
6144 [sources_ removeAllObjects];
6145 [sources_ addObjectsFromArray:[database_ sources]];
6147 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6150 int count([sources_ count]);
6152 for (int i = 0; i != count; i++) {
6153 if ([[sources_ objectAtIndex:i] record] == nil) break;
6157 [list_ setEditing:NO];
6158 [self updateButtonsForEditingStatus:NO animated:NO];
6162 - (void) addButtonClicked {
6163 /*[book_ pushPage:[[[AddSourceController alloc]
6168 UIAlertView *alert = [[[UIAlertView alloc]
6169 initWithTitle:UCLocalize("ENTER_APT_URL")
6172 cancelButtonTitle:UCLocalize("CANCEL")
6173 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6176 [alert setContext:@"source"];
6177 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6179 [alert setNumberOfRows:1];
6180 [alert addTextFieldWithValue:@"http://" label:@""];
6182 UITextInputTraits *traits = [[alert textField] textInputTraits];
6183 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6184 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6185 [traits setKeyboardType:UIKeyboardTypeURL];
6186 // XXX: UIReturnKeyDone
6187 [traits setReturnKeyType:UIReturnKeyNext];
6192 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6193 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
6194 initWithTitle:UCLocalize("ADD")
6195 style:UIBarButtonItemStylePlain
6197 action:@selector(addButtonClicked)
6199 [[self navigationItem] setLeftBarButtonItem:editing ? leftItem : [[self navigationItem] backBarButtonItem] animated:animated];
6202 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6203 initWithTitle:editing ? UCLocalize("DONE") : UCLocalize("EDIT")
6204 style:editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6206 action:@selector(editButtonClicked)
6208 [[self navigationItem] setRightBarButtonItem:rightItem animated:animated];
6209 [rightItem release];
6211 if (IsWildcat_ && !editing) {
6212 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6213 initWithTitle:UCLocalize("SETTINGS")
6214 style:UIBarButtonItemStylePlain
6216 action:@selector(settingsButtonClicked)
6218 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6219 [settingsItem release];
6223 - (void) settingsButtonClicked {
6224 [delegate_ showSettings];
6227 - (void) editButtonClicked {
6228 [list_ setEditing:![list_ isEditing] animated:YES];
6230 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6236 /* Installed Controller {{{ */
6237 @interface InstalledController : FilteredPackageController {
6241 - (id) initWithDatabase:(Database *)database;
6243 - (void) updateRoleButton;
6244 - (void) queueStatusDidChange;
6248 @implementation InstalledController
6254 - (id) title { return UCLocalize("INSTALLED"); }
6256 - (id) initWithDatabase:(Database *)database {
6257 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6258 [self updateRoleButton];
6259 [self queueStatusDidChange];
6264 - (void) queueButtonClicked {
6269 - (void) queueStatusDidChange {
6272 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6273 initWithTitle:UCLocalize("QUEUE")
6274 style:UIBarButtonItemStyleDone
6276 action:@selector(queueButtonClicked)
6278 if (Queuing_) [[self navigationItem] setLeftBarButtonItem:queueItem];
6279 else [[self navigationItem] setLeftBarButtonItem:nil];
6280 [queueItem release];
6285 - (void) reloadData {
6286 [packages_ reloadData];
6289 - (void) updateRoleButton {
6290 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6291 initWithTitle:expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")
6292 style:expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6294 action:@selector(roleButtonClicked)
6296 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) [[self navigationItem] setRightBarButtonItem:rightItem];
6297 [rightItem release];
6300 - (void) roleButtonClicked {
6301 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6302 [packages_ reloadData];
6305 [self updateRoleButton];
6308 - (void) setDelegate:(id)delegate {
6309 [super setDelegate:delegate];
6310 [packages_ setDelegate:delegate];
6316 /* Home Controller {{{ */
6317 @interface HomeController : CYBrowserController {
6322 @implementation HomeController
6324 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6325 [super _setMoreHeaders:request];
6327 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6328 if (UniqueID_ != nil)
6329 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6332 - (void) aboutButtonClicked {
6333 UIAlertView *alert = [[[UIAlertView alloc] init] autorelease];
6334 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6335 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6336 [alert setCancelButtonIndex:0];
6339 @"Copyright (C) 2008-2010\n"
6340 "Jay Freeman (saurik)\n"
6341 "saurik@saurik.com\n"
6342 "http://www.saurik.com/"
6348 - (void) viewWillAppear:(BOOL)animated {
6349 [super viewWillAppear:animated];
6350 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6353 - (void) viewWillDisappear:(BOOL)animated {
6354 [super viewWillDisappear:animated];
6355 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6359 if ((self = [super init]) != nil) {
6360 UIBarButtonItem *aboutItem = [[UIBarButtonItem alloc]
6361 initWithTitle:UCLocalize("ABOUT")
6362 style:UIBarButtonItemStylePlain
6364 action:@selector(aboutButtonClicked)
6366 [[self navigationItem] setLeftBarButtonItem:aboutItem];
6367 [aboutItem release];
6373 /* Manage Controller {{{ */
6374 @interface ManageController : CYBrowserController {
6377 - (void) queueStatusDidChange;
6380 @implementation ManageController
6383 if ((self = [super init]) != nil) {
6384 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6386 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6387 initWithTitle:UCLocalize("SETTINGS")
6388 style:UIBarButtonItemStylePlain
6390 action:@selector(settingsButtonClicked)
6392 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6393 [settingsItem release];
6395 [self queueStatusDidChange];
6399 - (void) settingsButtonClicked {
6400 [delegate_ showSettings];
6404 - (void) queueButtonClicked {
6408 - (void) applyLoadingTitle {
6409 // No "Loading" title.
6412 - (void) applyRightButton {
6417 - (void) queueStatusDidChange {
6419 if (!IsWildcat_ && Queuing_) {
6420 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6421 initWithTitle:UCLocalize("QUEUE")
6422 style:UIBarButtonItemStyleDone
6424 action:@selector(queueButtonClicked)
6426 [[self navigationItem] setRightBarButtonItem:queueItem];
6428 [queueItem release];
6430 [[self navigationItem] setRightBarButtonItem:nil];
6435 - (bool) isLoading {
6442 /* Refresh Bar {{{ */
6443 @interface RefreshBar : UINavigationBar {
6444 UIProgressIndicator *indicator_;
6445 UITextLabel *prompt_;
6446 UIProgressBar *progress_;
6447 UINavigationButton *cancel_;
6452 @implementation RefreshBar
6454 - (void) positionViews {
6455 CGRect frame = [cancel_ frame];
6456 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6457 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6458 [cancel_ setFrame:frame];
6460 CGSize prgsize = {75, 100};
6462 [self frame].size.width - prgsize.width - 10,
6463 ([self frame].size.height - prgsize.height) / 2
6465 [progress_ setFrame:prgrect];
6467 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6468 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6469 CGRect indrect = {{indoffset, indoffset}, indsize};
6470 [indicator_ setFrame:indrect];
6472 CGSize prmsize = {215, indsize.height + 4};
6474 indoffset * 2 + indsize.width,
6475 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6477 [prompt_ setFrame:prmrect];
6480 - (void)setFrame:(CGRect)frame {
6481 [super setFrame:frame];
6483 [self positionViews];
6486 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6487 if ((self = [super initWithFrame:frame])) {
6488 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6490 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6491 [self setBarStyle:UIBarStyleBlack];
6493 UIBarStyle barstyle([self _barStyle:NO]);
6494 bool ugly(barstyle == UIBarStyleDefault);
6496 UIProgressIndicatorStyle style = ugly ?
6497 UIProgressIndicatorStyleMediumBrown :
6498 UIProgressIndicatorStyleMediumWhite;
6500 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6501 [indicator_ setStyle:style];
6502 [indicator_ startAnimation];
6503 [self addSubview:indicator_];
6505 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6506 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6507 [prompt_ setBackgroundColor:[UIColor clearColor]];
6508 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6509 [self addSubview:prompt_];
6511 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6512 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6513 [progress_ setStyle:0];
6514 [self addSubview:progress_];
6516 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6517 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6518 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6519 [cancel_ setBarStyle:barstyle];
6521 [self positionViews];
6526 [cancel_ removeFromSuperview];
6530 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6531 [progress_ setProgress:0];
6532 [self addSubview:cancel_];
6536 [cancel_ removeFromSuperview];
6539 - (void) setPrompt:(NSString *)prompt {
6540 [prompt_ setText:prompt];
6543 - (void) setProgress:(float)progress {
6544 [progress_ setProgress:progress];
6550 @class CYNavigationController;
6552 /* Cydia Tab Bar Controller {{{ */
6553 @interface CYTabBarController : UITabBarController {
6554 Database *database_;
6559 @implementation CYTabBarController
6561 /* XXX: some logic should probably go here related to
6562 freeing the view controllers on tab change */
6564 - (void) reloadData {
6565 size_t count([[self viewControllers] count]);
6566 for (size_t i(0); i != count; ++i) {
6567 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6572 - (id) initWithDatabase:(Database *)database {
6573 if ((self = [super init]) != nil) {
6574 database_ = database;
6581 /* Cydia Navigation Controller {{{ */
6582 @interface CYNavigationController : UINavigationController {
6583 _transient Database *database_;
6587 - (id) initWithDatabase:(Database *)database;
6588 - (void) reloadData;
6593 @implementation CYNavigationController
6595 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6596 // Inherit autorotation settings for modal parents.
6597 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6598 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6600 return [super shouldAutorotateToInterfaceOrientation:orientation];
6608 - (void) reloadData {
6609 size_t count([[self viewControllers] count]);
6610 for (size_t i(0); i != count; ++i) {
6611 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6616 - (void) setDelegate:(id)delegate {
6617 delegate_ = delegate;
6620 - (id) initWithDatabase:(Database *)database {
6621 if ((self = [super init]) != nil) {
6622 database_ = database;
6628 /* Cydia:// Protocol {{{ */
6629 @interface CydiaURLProtocol : NSURLProtocol {
6634 @implementation CydiaURLProtocol
6636 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6637 NSURL *url([request URL]);
6640 NSString *scheme([[url scheme] lowercaseString]);
6641 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6646 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6650 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6651 id<NSURLProtocolClient> client([self client]);
6653 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6655 NSData *data(UIImagePNGRepresentation(icon));
6657 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6658 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6659 [client URLProtocol:self didLoadData:data];
6660 [client URLProtocolDidFinishLoading:self];
6664 - (void) startLoading {
6665 id<NSURLProtocolClient> client([self client]);
6666 NSURLRequest *request([self request]);
6668 NSURL *url([request URL]);
6669 NSString *href([url absoluteString]);
6671 NSString *path([href substringFromIndex:8]);
6672 NSRange slash([path rangeOfString:@"/"]);
6675 if (slash.location == NSNotFound) {
6679 command = [path substringToIndex:slash.location];
6680 path = [path substringFromIndex:(slash.location + 1)];
6683 Database *database([Database sharedInstance]);
6685 if ([command isEqualToString:@"package-icon"]) {
6688 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6689 Package *package([database packageWithName:path]);
6692 UIImage *icon([package icon]);
6693 [self _returnPNGWithImage:icon forRequest:request];
6694 } else if ([command isEqualToString:@"source-icon"]) {
6697 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6698 NSString *source(Simplify(path));
6699 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6701 icon = [UIImage applicationImageNamed:@"unknown.png"];
6702 [self _returnPNGWithImage:icon forRequest:request];
6703 } else if ([command isEqualToString:@"uikit-image"]) {
6706 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6707 UIImage *icon(_UIImageWithName(path));
6708 [self _returnPNGWithImage:icon forRequest:request];
6709 } else if ([command isEqualToString:@"section-icon"]) {
6712 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6713 NSString *section(Simplify(path));
6714 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6716 icon = [UIImage applicationImageNamed:@"unknown.png"];
6717 [self _returnPNGWithImage:icon forRequest:request];
6719 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6723 - (void) stopLoading {
6729 /* Sections Controller {{{ */
6730 @interface SectionsController : CYViewController <
6731 UITableViewDataSource,
6734 _transient Database *database_;
6735 NSMutableArray *sections_;
6736 NSMutableArray *filtered_;
6742 - (id) initWithDatabase:(Database *)database;
6743 - (void) reloadData;
6746 - (void) editButtonClicked;
6750 @implementation SectionsController
6753 [list_ setDataSource:nil];
6754 [list_ setDelegate:nil];
6756 [sections_ release];
6757 [filtered_ release];
6759 [accessory_ release];
6763 - (void) viewDidAppear:(BOOL)animated {
6764 [super viewDidAppear:animated];
6765 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6768 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6769 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6773 - (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
6774 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6777 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6781 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6782 static NSString *reuseIdentifier = @"SectionCell";
6784 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6785 if (cell == nil) cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6786 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6791 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6792 Section *section = [self sectionAtIndexPath:indexPath];
6793 NSString *name = [section name];
6796 if ([indexPath row] == 0) {
6799 title = UCLocalize("ALL_PACKAGES");
6802 name = [NSString stringWithString:name];
6803 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6806 title = UCLocalize("NO_SECTION");
6810 FilteredPackageController *table = [[[FilteredPackageController alloc]
6811 initWithDatabase:database_
6813 filter:@selector(isVisibleInSection:)
6817 [table setDelegate:delegate_];
6819 [[self navigationController] pushViewController:table animated:YES];
6822 - (id) title { return UCLocalize("SECTIONS"); }
6824 - (id) initWithDatabase:(Database *)database {
6825 if ((self = [super init]) != nil) {
6826 database_ = database;
6828 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6830 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6831 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6833 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6834 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6835 [list_ setRowHeight:45.0f];
6836 [[self view] addSubview:list_];
6838 [list_ setDataSource:self];
6839 [list_ setDelegate:self];
6845 - (void) reloadData {
6846 NSArray *packages = [database_ packages];
6848 [sections_ removeAllObjects];
6849 [filtered_ removeAllObjects];
6852 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6853 SectionMap sections;
6854 sections.resize(64);
6856 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6860 for (Package *package in packages) {
6861 NSString *name([package section]);
6862 NSString *key(name == nil ? @"" : name);
6867 _profile(SectionsView$reloadData$Section)
6868 section = §ions[key];
6869 if (*section == nil) {
6870 _profile(SectionsView$reloadData$Section$Allocate)
6871 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6876 [*section addToCount];
6878 _profile(SectionsView$reloadData$Filter)
6879 if (![package valid] || ![package visible])
6883 [*section addToRow];
6887 _profile(SectionsView$reloadData$Section)
6888 section = [sections objectForKey:key];
6889 if (section == nil) {
6890 _profile(SectionsView$reloadData$Section$Allocate)
6891 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6892 [sections setObject:section forKey:key];
6897 [section addToCount];
6899 _profile(SectionsView$reloadData$Filter)
6900 if (![package valid] || ![package visible])
6910 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6911 [sections_ addObject:i->second];
6913 [sections_ addObjectsFromArray:[sections allValues]];
6916 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6918 for (Section *section in sections_) {
6919 size_t count([section row]);
6923 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6924 [section setCount:count];
6925 [filtered_ addObject:section];
6928 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6929 initWithTitle:[sections_ count] == 0 ? nil : UCLocalize("EDIT")
6930 style:UIBarButtonItemStylePlain
6932 action:@selector(editButtonClicked)
6934 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] != nil];
6935 [rightItem release];
6941 - (void) resetView {
6943 [self editButtonClicked];
6946 - (void) editButtonClicked {
6947 if ((editing_ = !editing_))
6950 [delegate_ updateData];
6952 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6953 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6954 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6957 - (UIView *) accessoryView {
6963 /* Changes Controller {{{ */
6964 @interface ChangesController : CYViewController <
6965 UITableViewDataSource,
6968 _transient Database *database_;
6969 NSMutableArray *packages_;
6970 NSMutableArray *sections_;
6973 BOOL hasSentFirstLoad_;
6976 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6977 - (void) reloadData;
6981 @implementation ChangesController
6984 [list_ setDelegate:nil];
6985 [list_ setDataSource:nil];
6987 [packages_ release];
6988 [sections_ release];
6993 - (void) viewDidAppear:(BOOL)animated {
6994 [super viewDidAppear:animated];
6995 if (!hasSentFirstLoad_) {
6996 hasSentFirstLoad_ = YES;
6997 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6999 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7003 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7004 NSInteger count([sections_ count]);
7005 return count == 0 ? 1 : count;
7008 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7009 if ([sections_ count] == 0)
7011 return [[sections_ objectAtIndex:section] name];
7014 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7015 if ([sections_ count] == 0)
7017 return [[sections_ objectAtIndex:section] count];
7020 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7021 Section *section([sections_ objectAtIndex:[path section]]);
7022 NSInteger row([path row]);
7023 return [packages_ objectAtIndex:([section row] + row)];
7026 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7027 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7029 cell = [[[PackageCell alloc] init] autorelease];
7030 [cell setPackage:[self packageAtIndexPath:path]];
7034 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7035 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7038 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7039 Package *package([self packageAtIndexPath:path]);
7040 PackageController *view([delegate_ packageController]);
7041 [view setDelegate:delegate_];
7042 [view setPackage:package];
7043 [[self navigationController] pushViewController:view animated:YES];
7047 - (void) refreshButtonClicked {
7048 [delegate_ beginUpdate];
7049 [[self navigationItem] setLeftBarButtonItem:nil];
7052 - (void) upgradeButtonClicked {
7053 [delegate_ distUpgrade];
7056 - (id) title { return UCLocalize("CHANGES"); }
7058 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7059 if ((self = [super init]) != nil) {
7060 database_ = database;
7061 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7063 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
7064 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7066 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7067 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7068 [list_ setRowHeight:73.0f];
7069 [[self view] addSubview:list_];
7071 [list_ setDataSource:self];
7072 [list_ setDelegate:self];
7074 delegate_ = delegate;
7078 - (void) _reloadPackages:(NSArray *)packages {
7080 for (Package *package in packages)
7082 [package uninstalled] && [package valid] && [package visible] ||
7083 [package upgradableAndEssential:YES]
7085 [packages_ addObject:package];
7088 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7092 - (void) reloadData {
7093 NSArray *packages = [database_ packages];
7095 [packages_ removeAllObjects];
7096 [sections_ removeAllObjects];
7098 UIProgressHUD *hud([delegate_ addProgressHUD]);
7100 [hud setText:@"Loading Changes"];
7101 NSLog(@"HUD:%@::%@", delegate_, hud);
7102 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7103 [delegate_ removeProgressHUD:hud];
7105 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7106 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7107 Section *section = nil;
7111 bool unseens = false;
7113 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7115 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7116 Package *package = [packages_ objectAtIndex:offset];
7118 BOOL uae = [package upgradableAndEssential:YES];
7124 _profile(ChangesController$reloadData$Remember)
7125 seen = [package seen];
7128 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7133 name = UCLocalize("UNKNOWN");
7135 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7139 _profile(ChangesController$reloadData$Allocate)
7140 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7141 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7142 [sections_ addObject:section];
7146 [section addToCount];
7147 } else if ([package ignored])
7148 [ignored addToCount];
7151 [upgradable addToCount];
7156 CFRelease(formatter);
7159 Section *last = [sections_ lastObject];
7160 size_t count = [last count];
7161 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7162 [sections_ removeLastObject];
7165 if ([ignored count] != 0)
7166 [sections_ insertObject:ignored atIndex:0];
7168 [sections_ insertObject:upgradable atIndex:0];
7172 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7173 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7174 style:UIBarButtonItemStylePlain
7176 action:@selector(upgradeButtonClicked)
7178 if (upgrades_ > 0) [[self navigationItem] setRightBarButtonItem:rightItem];
7179 [rightItem release];
7181 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
7182 initWithTitle:UCLocalize("REFRESH")
7183 style:UIBarButtonItemStylePlain
7185 action:@selector(refreshButtonClicked)
7187 if (![delegate_ updating]) [[self navigationItem] setLeftBarButtonItem:leftItem];
7193 /* Search Controller {{{ */
7194 @interface SearchController : FilteredPackageController <
7197 UISearchBar *search_;
7200 - (id) initWithDatabase:(Database *)database;
7201 - (void) reloadData;
7205 @implementation SearchController
7212 - (void) searchBarSearchButtonClicked:(id)searchBar {
7213 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7214 [search_ resignFirstResponder];
7218 - (void) searchBar:(id)searchBar textDidChange:(NSString *)text {
7219 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7223 - (id) title { return nil; }
7225 - (id) initWithDatabase:(Database *)database {
7226 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7229 - (void)viewDidAppear:(BOOL)animated {
7230 [super viewDidAppear:animated];
7232 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7233 [search_ layoutSubviews];
7234 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7235 UITextField *textField = [search_ searchField];
7236 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7237 [search_ setDelegate:self];
7238 [textField setEnablesReturnKeyAutomatically:NO];
7239 [[self navigationItem] setTitleView:textField];
7243 - (void) _reloadData {
7246 - (void) reloadData {
7247 _profile(SearchController$reloadData)
7248 [packages_ reloadData];
7251 [packages_ resetCursor];
7254 - (void) didSelectPackage:(Package *)package {
7255 [search_ resignFirstResponder];
7256 [super didSelectPackage:package];
7261 /* Settings Controller {{{ */
7262 @interface SettingsController : CYViewController <
7263 UITableViewDataSource,
7266 _transient Database *database_;
7269 UITableView *table_;
7270 id subscribedSwitch_;
7272 UITableViewCell *subscribedCell_;
7273 UITableViewCell *ignoredCell_;
7276 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7280 @implementation SettingsController
7284 if (package_ != nil)
7287 [subscribedSwitch_ release];
7288 [ignoredSwitch_ release];
7289 [subscribedCell_ release];
7290 [ignoredCell_ release];
7295 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7296 if (package_ == nil)
7302 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7303 if (package_ == nil)
7309 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7310 return UCLocalize("SHOW_ALL_CHANGES_EX");
7313 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7314 if (package_ == nil)
7317 NSMutableDictionary *metadata([package_ metadata]);
7320 if (NSNumber *number = [metadata objectForKey:key])
7321 before = [number boolValue];
7325 if (value != before) {
7326 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7328 [delegate_ updateData];
7332 - (void) onSubscribed:(id)control {
7333 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7336 - (void) onIgnored:(id)control {
7337 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
7340 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7341 if (package_ == nil)
7344 switch ([indexPath row]) {
7345 case 0: return subscribedCell_;
7346 case 1: return ignoredCell_;
7354 - (id) title { return UCLocalize("SETTINGS"); }
7356 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7357 if ((self = [super init])) {
7358 database_ = database;
7359 name_ = [package retain];
7361 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7363 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7364 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7365 [table_ setAllowsSelection:NO];
7366 [[self view] addSubview:table_];
7368 subscribedSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7369 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7370 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7372 ignoredSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7373 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7374 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7376 subscribedCell_ = [[UITableViewCell alloc] init];
7377 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7378 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7380 ignoredCell_ = [[UITableViewCell alloc] init];
7381 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7382 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7384 [table_ setDataSource:self];
7385 [table_ setDelegate:self];
7390 - (void) reloadData {
7391 if (package_ != nil)
7392 [package_ autorelease];
7393 package_ = [database_ packageWithName:name_];
7394 if (package_ != nil) {
7396 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7397 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7400 [table_ reloadData];
7406 /* Signature Controller {{{ */
7407 @interface SignatureController : CYBrowserController {
7408 _transient Database *database_;
7412 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7416 @implementation SignatureController
7423 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7425 [super webView:sender didClearWindowObject:window forFrame:frame];
7428 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7429 if ((self = [super init]) != nil) {
7430 database_ = database;
7431 package_ = [package retain];
7436 - (void) reloadData {
7437 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7442 /* Role Controller {{{ */
7443 @interface RoleController : CYViewController <
7444 UITableViewDataSource,
7447 _transient Database *database_;
7449 UITableView *table_;
7450 UISegmentedControl *segment_;
7454 - (void) showDoneButton;
7455 - (void) resizeSegmentedControl;
7459 @implementation RoleController
7463 [container_ release];
7468 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7469 if ((self = [super init])) {
7470 database_ = database;
7471 roledelegate_ = delegate;
7473 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7475 NSArray *items = [NSArray arrayWithObjects:
7477 UCLocalize("HACKER"),
7478 UCLocalize("DEVELOPER"),
7480 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7481 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7482 [container_ addSubview:segment_];
7485 if ([Role_ isEqualToString:@"User"]) index = 0;
7486 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7487 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7489 [segment_ setSelectedSegmentIndex:index];
7490 [self showDoneButton];
7493 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7494 [self resizeSegmentedControl];
7496 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7497 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7498 [table_ setDelegate:self];
7499 [table_ setDataSource:self];
7500 [[self view] addSubview:table_];
7501 [table_ reloadData];
7505 - (void) resizeSegmentedControl {
7506 CGFloat width = [[self view] frame].size.width;
7507 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7510 - (void) viewWillAppear:(BOOL)animated {
7511 [super viewWillAppear:animated];
7513 [self resizeSegmentedControl];
7516 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7517 [self resizeSegmentedControl];
7520 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7521 [self resizeSegmentedControl];
7525 NSString *role(nil);
7527 switch ([segment_ selectedSegmentIndex]) {
7528 case 0: role = @"User"; break;
7529 case 1: role = @"Hacker"; break;
7530 case 2: role = @"Developer"; break;
7535 if (![role isEqualToString:Role_]) {
7536 bool rolling(Role_ == nil);
7539 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7543 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7548 [roledelegate_ loadData];
7550 [roledelegate_ updateData];
7554 - (void) segmentChanged:(UISegmentedControl *)control {
7555 [self showDoneButton];
7558 - (void) doneButtonClicked {
7560 [[self navigationController] dismissModalViewControllerAnimated:YES];
7563 - (void) showDoneButton {
7564 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7565 initWithTitle:UCLocalize("DONE")
7566 style:UIBarButtonItemStyleDone
7568 action:@selector(doneButtonClicked)
7570 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] == nil];
7571 [rightItem release];
7574 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7575 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7579 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7583 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7584 return nil; // This method is required by the protocol.
7587 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7589 return UCLocalize("ROLE_EX");
7591 return [NSString stringWithFormat:
7592 @"%@: %@\n%@: %@\n%@: %@",
7593 UCLocalize("USER"), UCLocalize("USER_EX"),
7594 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7595 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7600 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7601 if (section == 3) return 44.0f;
7605 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7606 if (section == 3) return container_;
7613 /* Cydia Container {{{ */
7614 @interface CYContainer : UIViewController <ProgressDelegate> {
7615 _transient Database *database_;
7616 RefreshBar *refreshbar_;
7621 UITabBarController *root_;
7624 - (void) setTabBarController:(UITabBarController *)controller;
7626 - (void) dropBar:(BOOL)animated;
7627 - (void) beginUpdate;
7628 - (void) raiseBar:(BOOL)animated;
7632 @implementation CYContainer
7634 // NOTE: UIWindow only sends the top controller these messages,
7635 // So we have to forward them on.
7637 - (void) viewDidAppear:(BOOL)animated {
7638 [super viewDidAppear:animated];
7639 [root_ viewDidAppear:animated];
7642 - (void) viewWillAppear:(BOOL)animated {
7643 [super viewWillAppear:animated];
7644 [root_ viewWillAppear:animated];
7647 - (void) viewDidDisappear:(BOOL)animated {
7648 [super viewDidDisappear:animated];
7649 [root_ viewDidDisappear:animated];
7652 - (void) viewWillDisappear:(BOOL)animated {
7653 [super viewWillDisappear:animated];
7654 [root_ viewWillDisappear:animated];
7657 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7658 #ifdef RotationEnabled
7665 - (void) setTabBarController:(UITabBarController *)controller {
7667 [[self view] addSubview:[root_ view]];
7670 - (void) setUpdate:(NSDate *)date {
7674 - (void) beginUpdate {
7676 [refreshbar_ start];
7681 detachNewThreadSelector:@selector(performUpdate)
7687 - (void) performUpdate { _pooled
7689 status.setDelegate(self);
7690 [database_ updateWithStatus:status];
7693 performSelectorOnMainThread:@selector(completeUpdate)
7699 - (void) completeUpdate {
7702 [self raiseBar:YES];
7704 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7707 - (void) cancelUpdate {
7708 [refreshbar_ cancel];
7709 [self completeUpdate];
7712 - (void) cancelPressed {
7713 [self cancelUpdate];
7720 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7721 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7724 - (void) startProgress {
7727 - (void) setProgressTitle:(NSString *)title {
7729 performSelectorOnMainThread:@selector(_setProgressTitle:)
7735 - (bool) isCancelling:(size_t)received {
7739 - (void) setProgressPercent:(float)percent {
7741 performSelectorOnMainThread:@selector(_setProgressPercent:)
7742 withObject:[NSNumber numberWithFloat:percent]
7747 - (void) addProgressOutput:(NSString *)output {
7749 performSelectorOnMainThread:@selector(_addProgressOutput:)
7755 - (void) _setProgressTitle:(NSString *)title {
7756 [refreshbar_ setPrompt:title];
7759 - (void) _setProgressPercent:(NSNumber *)percent {
7760 [refreshbar_ setProgress:[percent floatValue]];
7763 - (void) _addProgressOutput:(NSString *)output {
7766 - (void) setUpdateDelegate:(id)delegate {
7767 updatedelegate_ = delegate;
7770 - (void) dropBar:(BOOL)animated {
7771 if (dropped_) return;
7774 [[self view] addSubview:refreshbar_];
7776 if (animated) [UIView beginAnimations:nil context:NULL];
7777 CGRect barframe = [refreshbar_ frame];
7778 CGRect viewframe = [[root_ view] frame];
7779 viewframe.origin.y += barframe.size.height;
7780 viewframe.size.height -= barframe.size.height;
7781 [[root_ view] setFrame:viewframe];
7782 if (animated) [UIView commitAnimations];
7784 // Ensure bar has the proper width for our view, it might have changed
7785 barframe.size.width = viewframe.size.width;
7786 [refreshbar_ setFrame:barframe];
7788 // XXX: fix Apple's layout bug
7789 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7792 - (void) raiseBar:(BOOL)animated {
7793 if (!dropped_) return;
7796 [refreshbar_ removeFromSuperview];
7798 if (animated) [UIView beginAnimations:nil context:NULL];
7799 CGRect barframe = [refreshbar_ frame];
7800 CGRect viewframe = [[root_ view] frame];
7801 viewframe.origin.y -= barframe.size.height;
7802 viewframe.size.height += barframe.size.height;
7803 [[root_ view] setFrame:viewframe];
7804 if (animated) [UIView commitAnimations];
7806 // XXX: fix Apple's layout bug
7807 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7810 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7811 // XXX: fix Apple's layout bug
7812 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7815 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7821 // XXX: fix Apple's layout bug
7822 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7826 [refreshbar_ release];
7830 - (id) initWithDatabase: (Database *)database {
7831 if ((self = [super init]) != nil) {
7832 database_ = database;
7834 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7836 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7853 @interface Cydia : UIApplication <
7854 ConfirmationControllerDelegate,
7855 ProgressControllerDelegate,
7859 CYContainer *container_;
7863 NSMutableArray *essential_;
7864 NSMutableArray *broken_;
7866 Database *database_;
7870 UIKeyboard *keyboard_;
7871 UIProgressHUD *hud_;
7873 SectionsController *sections_;
7874 ChangesController *changes_;
7875 ManageController *manage_;
7876 SearchController *search_;
7877 SourceTable *sources_;
7878 InstalledController *installed_;
7881 #if RecyclePackageViews
7882 NSMutableArray *details_;
7888 - (UCViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7889 - (void) setPage:(UCViewController *)page;
7894 static _finline void _setHomePage(Cydia *self) {
7895 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7898 @implementation Cydia
7900 - (void) beginUpdate {
7901 [container_ beginUpdate];
7905 return [container_ updating];
7908 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7913 if ([broken_ count] != 0) {
7914 int count = [broken_ count];
7916 UIAlertView *alert = [[[UIAlertView alloc]
7917 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7918 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7920 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7921 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
7924 [alert setContext:@"fixhalf"];
7926 } else if (!Ignored_ && [essential_ count] != 0) {
7927 int count = [essential_ count];
7929 UIAlertView *alert = [[[UIAlertView alloc]
7930 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7931 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
7933 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
7934 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
7937 [alert setContext:@"upgrade"];
7942 - (void) _saveConfig {
7945 NSString *error(nil);
7946 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7948 NSError *error(nil);
7949 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7950 NSLog(@"failure to save metadata data: %@", error);
7953 NSLog(@"failure to serialize metadata: %@", error);
7961 - (void) _updateData {
7964 /* XXX: this is just stupid */
7965 if (tag_ != 1 && sections_ != nil)
7966 [sections_ reloadData];
7967 if (tag_ != 2 && changes_ != nil)
7968 [changes_ reloadData];
7969 if (tag_ != 4 && search_ != nil)
7970 [search_ reloadData];
7972 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
7975 - (int)indexOfTabWithTag:(int)tag {
7977 for (UINavigationController *controller in [tabbar_ viewControllers]) {
7978 if ([[controller tabBarItem] tag] == tag) return i;
7985 - (void) _refreshIfPossible {
7986 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
7988 Reachability* reachability = [Reachability reachabilityWithHostName:@"cydia.saurik.com"];
7989 NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
7991 if (loaded_ || ManualRefresh || remoteHostStatus == NotReachable) loaded:
7992 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
7996 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
7998 if (update != nil) {
7999 NSTimeInterval interval([update timeIntervalSinceNow]);
8000 if (interval <= 0 && interval > -(15*60))
8004 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8010 - (void) refreshIfPossible {
8011 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8014 - (void) _reloadData {
8015 UIProgressHUD *hud([self addProgressHUD]);
8016 [hud setText:(loaded_ ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
8018 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8021 [self removeProgressHUD:hud];
8025 [essential_ removeAllObjects];
8026 [broken_ removeAllObjects];
8028 NSArray *packages([database_ packages]);
8029 for (Package *package in packages) {
8031 [broken_ addObject:package];
8032 if ([package upgradableAndEssential:NO]) {
8033 if ([package essential])
8034 [essential_ addObject:package];
8040 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8041 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:badge];
8042 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:YES];
8044 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8045 [self setApplicationBadge:badge];
8047 [self setApplicationBadgeString:badge];
8049 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:nil];
8050 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:NO];
8052 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8053 [self removeApplicationBadge];
8054 else // XXX: maybe use setApplicationBadgeString also?
8055 [self setApplicationIconBadgeNumber:0];
8060 [self refreshIfPossible];
8063 - (void) updateData {
8064 [database_ setVisible];
8073 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8074 _assert(file != NULL);
8076 for (NSString *key in [Sources_ allKeys]) {
8077 NSDictionary *source([Sources_ objectForKey:key]);
8079 fprintf(file, "%s %s %s\n",
8080 [[source objectForKey:@"Type"] UTF8String],
8081 [[source objectForKey:@"URI"] UTF8String],
8082 [[source objectForKey:@"Distribution"] UTF8String]
8090 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8091 UINavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8092 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8093 [container_ presentModalViewController:navigation animated:YES];
8096 detachNewThreadSelector:@selector(update_)
8099 title:UCLocalize("UPDATING_SOURCES")
8103 - (void) reloadData {
8104 @synchronized (self) {
8110 pkgProblemResolver *resolver = [database_ resolver];
8112 resolver->InstallProtect();
8113 if (!resolver->Resolve(true))
8117 - (CGRect) popUpBounds {
8118 return [[tabbar_ view] bounds];
8122 if (![database_ prepare])
8125 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8126 [page setDelegate:self];
8127 id confirm_ = [[CYNavigationController alloc] initWithRootViewController:page];
8128 [confirm_ setDelegate:self];
8130 if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8131 [container_ presentModalViewController:confirm_ animated:YES];
8137 @synchronized (self) {
8142 - (void) clearPackage:(Package *)package {
8143 @synchronized (self) {
8150 - (void) installPackages:(NSArray *)packages {
8151 @synchronized (self) {
8152 for (Package *package in packages)
8159 - (void) installPackage:(Package *)package {
8160 @synchronized (self) {
8167 - (void) removePackage:(Package *)package {
8168 @synchronized (self) {
8175 - (void) distUpgrade {
8176 @synchronized (self) {
8177 if (![database_ upgrade])
8184 @synchronized (self) {
8189 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8190 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8192 if (navigation != nil) {
8193 [navigation pushViewController:progress animated:YES];
8195 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8196 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8197 [container_ presentModalViewController:navigation animated:YES];
8201 detachNewThreadSelector:@selector(perform)
8204 title:UCLocalize("RUNNING")
8208 - (void) progressControllerIsComplete:(ProgressController *)progress {
8212 - (void) setPage:(UCViewController *)page {
8213 [page setDelegate:self];
8215 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8216 [navController setViewControllers:[NSArray arrayWithObject:page] animated:NO];
8217 for (CYNavigationController *page in [tabbar_ viewControllers]) {
8218 if (page != navController) [page setViewControllers:nil];
8222 - (UCViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8223 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8224 [browser loadURL:url];
8228 - (SectionsController *) sectionsController {
8229 if (sections_ == nil)
8230 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8234 - (ChangesController *) changesController {
8235 if (changes_ == nil)
8236 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8240 - (ManageController *) manageController {
8241 if (manage_ == nil) {
8242 manage_ = (ManageController *) [[self
8243 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8244 withClass:[ManageController class]
8246 if (!IsWildcat_) queueDelegate_ = manage_;
8251 - (SearchController *) searchController {
8253 search_ = [[SearchController alloc] initWithDatabase:database_];
8257 - (SourceTable *) sourcesController {
8258 if (sources_ == nil)
8259 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8263 - (InstalledController *) installedController {
8264 if (installed_ == nil) {
8265 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8266 if (IsWildcat_) queueDelegate_ = installed_;
8271 - (void) tabBarController:(id)tabBarController didSelectViewController:(UIViewController *)viewController {
8272 int tag = [[viewController tabBarItem] tag];
8274 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8276 } else if (tag_ == 1) {
8277 [[self sectionsController] resetView];
8281 case kCydiaTag: _setHomePage(self); break;
8283 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8284 case kChangesTag: [self setPage:[self changesController]]; break;
8285 case kManageTag: [self setPage:[self manageController]]; break;
8286 case kInstalledTag: [self setPage:[self installedController]]; break;
8287 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8288 case kSearchTag: [self setPage:[self searchController]]; break;
8296 - (void) showSettings {
8297 RoleController *role = [[RoleController alloc] initWithDatabase:database_ delegate:self];
8298 CYNavigationController *nav = [[CYNavigationController alloc] initWithRootViewController:role];
8299 if (IsWildcat_) [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8300 [container_ presentModalViewController:nav animated:YES];
8303 - (void) setPackageController:(PackageController *)view {
8305 [view setPackage:nil];
8306 #if RecyclePackageViews
8307 if ([details_ count] < 3)
8308 [details_ addObject:view];
8313 - (PackageController *) _packageController {
8314 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8317 - (PackageController *) packageController {
8318 #if RecyclePackageViews
8319 PackageController *view;
8320 size_t count([details_ count]);
8323 view = [self _packageController];
8325 [details_ addObject:[self _packageController]];
8327 view = [[[details_ lastObject] retain] autorelease];
8328 [details_ removeLastObject];
8335 return [self _packageController];
8339 - (void) cancelAndClear:(bool)clear {
8340 @synchronized (self) {
8342 /* XXX: clear marks instead of reloading data */
8343 /*pkgCacheFile &cache([database_ cache]);
8344 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
8345 if (!cache[iterator].Keep()) cache->MarkKeep(iterator, false, false);
8351 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kManageTag] != -1 ? [self indexOfTabWithTag:kManageTag] : [self indexOfTabWithTag:kInstalledTag]] tabBarItem] setBadgeValue:nil];
8352 [queueDelegate_ queueStatusDidChange];*/
8357 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kManageTag] != -1 ? [self indexOfTabWithTag:kManageTag] : [self indexOfTabWithTag:kInstalledTag]] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8358 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8360 [queueDelegate_ queueStatusDidChange];
8365 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8366 NSString *context([alert context]);
8368 if ([context isEqualToString:@"fixhalf"]) {
8369 if (button == [alert firstOtherButtonIndex]) {
8370 @synchronized (self) {
8371 for (Package *broken in broken_) {
8374 NSString *id = [broken id];
8375 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8376 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8377 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8378 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8384 } else if (button == [alert cancelButtonIndex]) {
8385 [broken_ removeAllObjects];
8389 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8390 } else if ([context isEqualToString:@"upgrade"]) {
8391 if (button == [alert firstOtherButtonIndex]) {
8392 @synchronized (self) {
8393 for (Package *essential in essential_)
8394 [essential install];
8399 } else if (button == [alert firstOtherButtonIndex] + 1) {
8401 } else if (button == [alert cancelButtonIndex]) {
8405 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8409 - (void) system:(NSString *)command { _pooled
8410 system([command UTF8String]);
8413 - (void) applicationWillSuspend {
8415 [super applicationWillSuspend];
8418 - (void) applicationSuspend:(__GSEvent *)event {
8419 // FIXME: This needs to be fixed, but we no longer have a progress_.
8420 // What's the best solution?
8421 if (hud_ == nil)// && ![progress_ isRunning])
8422 [super applicationSuspend:event];
8425 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8427 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8430 - (void) _setSuspended:(BOOL)value {
8432 [super _setSuspended:value];
8435 - (UIProgressHUD *) addProgressHUD {
8436 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8437 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8439 [window_ setUserInteractionEnabled:NO];
8441 [[container_ view] addSubview:hud];
8445 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8447 [hud removeFromSuperview];
8448 [window_ setUserInteractionEnabled:YES];
8451 - (UCViewController *) pageForPackage:(NSString *)name {
8452 if (Package *package = [database_ packageWithName:name]) {
8453 PackageController *view([self packageController]);
8454 [view setPackage:package];
8457 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8458 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8459 return [self _pageForURL:url withClass:[CYBrowserController class]];
8463 - (UCViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8467 NSString *href([url absoluteString]);
8468 if ([href hasPrefix:@"apptapp://package/"])
8469 return [self pageForPackage:[href substringFromIndex:18]];
8471 NSString *scheme([[url scheme] lowercaseString]);
8472 if (![scheme isEqualToString:@"cydia"])
8474 NSString *path([url absoluteString]);
8475 if ([path length] < 8)
8477 path = [path substringFromIndex:8];
8478 if (![path hasPrefix:@"/"])
8479 path = [@"/" stringByAppendingString:path];
8481 if ([path isEqualToString:@"/add-source"])
8482 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8483 else if ([path isEqualToString:@"/storage"])
8484 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8485 else if ([path isEqualToString:@"/sources"])
8486 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8487 else if ([path isEqualToString:@"/packages"])
8488 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8489 else if ([path hasPrefix:@"/url/"])
8490 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8491 else if ([path hasPrefix:@"/launch/"])
8492 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8493 else if ([path hasPrefix:@"/package-settings/"])
8494 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8495 else if ([path hasPrefix:@"/package-signature/"])
8496 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8497 else if ([path hasPrefix:@"/package/"])
8498 return [self pageForPackage:[path substringFromIndex:9]];
8499 else if ([path hasPrefix:@"/files/"]) {
8500 NSString *name = [path substringFromIndex:7];
8502 if (Package *package = [database_ packageWithName:name]) {
8503 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8504 [files setPackage:package];
8512 - (void) applicationOpenURL:(NSURL *)url {
8513 [super applicationOpenURL:url];
8515 if (UCViewController *page = [self pageForURL:url hasTag:&tag]) {
8516 [self setPage:page];
8518 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8522 - (void) applicationWillResignActive:(UIApplication *)application {
8523 // Stop refreshing if you get a phone call or lock the device.
8524 if ([container_ updating]) [container_ cancelUpdate];
8526 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8527 [super applicationWillResignActive:application];
8530 - (void) applicationDidFinishLaunching:(id)unused {
8531 [CYBrowserController _initialize];
8533 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8535 Font12_ = [[UIFont systemFontOfSize:12] retain];
8536 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8537 Font14_ = [[UIFont systemFontOfSize:14] retain];
8538 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8539 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8543 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8544 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8546 UIScreen *screen([UIScreen mainScreen]);
8548 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8549 [window_ orderFront:self];
8550 [window_ makeKey:self];
8551 [window_ setHidden:NO];
8553 database_ = [Database sharedInstance];
8556 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8557 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8558 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8559 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8560 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8561 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8562 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8563 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8564 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8567 [self setIdleTimerDisabled:YES];
8569 hud_ = [self addProgressHUD];
8570 [hud_ setText:@"Reorganizing:\n\nWill Automatically\nClose When Done"];
8571 [self setStatusBarShowsProgress:YES];
8573 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8575 [self setStatusBarShowsProgress:NO];
8576 [self removeProgressHUD:hud_];
8579 if (ExecFork() == 0) {
8580 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8581 perror("launchctl stop");
8589 NSMutableArray *items([NSMutableArray arrayWithObjects:
8590 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8591 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8592 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8593 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8597 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8598 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8600 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8603 NSMutableArray *controllers([NSMutableArray array]);
8605 for (UITabBarItem *item in items) {
8606 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8607 [controller setTabBarItem:item];
8608 [controllers addObject:controller];
8611 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8612 [tabbar_ setViewControllers:controllers];
8613 [tabbar_ setDelegate:self];
8614 [tabbar_ setSelectedIndex:0];
8616 container_ = [[CYContainer alloc] initWithDatabase:database_];
8617 [container_ setUpdateDelegate:self];
8618 [container_ setTabBarController:tabbar_];
8619 [window_ addSubview:[container_ view]];
8621 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8626 [self showSettings];
8630 [UIKeyboard initImplementationNow];
8634 #if RecyclePackageViews
8635 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8636 [details_ addObject:[self _packageController]];
8637 [details_ addObject:[self _packageController]];
8645 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8646 if (item != nil && IsWildcat_) {
8647 [sheet showFromBarButtonItem:item animated:YES];
8649 [sheet showInView:window_];
8656 id Alloc_(id self, SEL selector) {
8657 id object = alloc_(self, selector);
8658 lprintf("[%s]A-%p\n", self->isa->name, object);
8663 id Dealloc_(id self, SEL selector) {
8664 id object = dealloc_(self, selector);
8665 lprintf("[%s]D-%p\n", self->isa->name, object);
8669 Class $WebDefaultUIKitDelegate;
8671 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8672 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8673 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8674 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8677 static NSNumber *shouldPlayKeyboardSounds;
8681 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8683 case 1104: // Keyboard Button Clicked
8684 case 1105: // Keyboard Delete Repeated
8685 if (shouldPlayKeyboardSounds == nil) {
8686 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8687 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8690 if (![shouldPlayKeyboardSounds boolValue])
8694 _UIHardware$_playSystemSound$(self, _cmd, sound);
8698 int main(int argc, char *argv[]) { _pooled
8701 if (Class $UIDevice = objc_getClass("UIDevice")) {
8702 UIDevice *device([$UIDevice currentDevice]);
8703 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8707 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8709 /* Library Hacks {{{ */
8710 class_addMethod(objc_getClass("WebScriptObject"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &WebScriptObject$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8711 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8713 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8714 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8715 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8716 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8717 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8720 $UIHardware = objc_getClass("UIHardware");
8721 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8722 if (UIHardware$_playSystemSound$ != NULL) {
8723 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8724 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8727 /* Set Locale {{{ */
8728 Locale_ = CFLocaleCopyCurrent();
8729 Languages_ = [NSLocale preferredLanguages];
8730 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8731 //NSLog(@"%@", [Languages_ description]);
8734 if (Languages_ == nil || [Languages_ count] == 0)
8735 // XXX: consider just setting to C and then falling through?
8738 lang = [[Languages_ objectAtIndex:0] UTF8String];
8739 setenv("LANG", lang, true);
8742 //std::setlocale(LC_ALL, lang);
8743 NSLog(@"Setting Language: %s", lang);
8746 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8748 /* Parse Arguments {{{ */
8749 bool substrate(false);
8755 for (int argi(1); argi != argc; ++argi)
8756 if (strcmp(argv[argi], "--") == 0) {
8758 argv[argi] = argv[0];
8764 for (int argi(1); argi != arge; ++argi)
8765 if (strcmp(args[argi], "--substrate") == 0)
8768 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8772 App_ = [[NSBundle mainBundle] bundlePath];
8773 Home_ = NSHomeDirectory();
8779 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8780 alloc_ = alloc->method_imp;
8781 alloc->method_imp = (IMP) &Alloc_;*/
8783 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8784 dealloc_ = dealloc->method_imp;
8785 dealloc->method_imp = (IMP) &Dealloc_;*/
8787 /* System Information {{{ */
8791 size = sizeof(maxproc);
8792 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8793 perror("sysctlbyname(\"kern.maxproc\", ?)");
8794 else if (maxproc < 64) {
8796 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8797 perror("sysctlbyname(\"kern.maxproc\", #)");
8800 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8801 char *osversion = new char[size];
8802 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8803 perror("sysctlbyname(\"kern.osversion\", ?)");
8805 System_ = [NSString stringWithUTF8String:osversion];
8807 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8808 char *machine = new char[size];
8809 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8810 perror("sysctlbyname(\"hw.machine\", ?)");
8814 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8815 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8816 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8817 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8821 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8822 NSData *data((NSData *) ecid);
8823 size_t length([data length]);
8824 uint8_t bytes[length];
8825 [data getBytes:bytes];
8826 char string[length * 2 + 1];
8827 for (size_t i(0); i != length; ++i)
8828 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8829 ChipID_ = [NSString stringWithUTF8String:string];
8833 IOObjectRelease(service);
8837 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8839 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8840 Build_ = [system objectForKey:@"ProductBuildVersion"];
8841 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8842 Product_ = [info objectForKey:@"SafariProductVersion"];
8843 Safari_ = [info objectForKey:@"CFBundleVersion"];
8846 /* Load Database {{{ */
8848 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8850 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8853 if (Metadata_ == NULL)
8854 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8856 Settings_ = [Metadata_ objectForKey:@"Settings"];
8858 Packages_ = [Metadata_ objectForKey:@"Packages"];
8859 Sections_ = [Metadata_ objectForKey:@"Sections"];
8860 Sources_ = [Metadata_ objectForKey:@"Sources"];
8862 Token_ = [Metadata_ objectForKey:@"Token"];
8865 if (Settings_ != nil)
8866 Role_ = [Settings_ objectForKey:@"Role"];
8868 if (Packages_ == nil) {
8869 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8870 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8873 if (Sections_ == nil) {
8874 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8875 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8878 if (Sources_ == nil) {
8879 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8880 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8885 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8888 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8890 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
8891 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
8892 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8893 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8894 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8895 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8897 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
8899 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8900 unlink("/tmp/.cydia.fw");
8902 } else if (access("/User", F_OK) != 0 || version < 2) {
8905 system("/usr/libexec/cydia/firmware.sh");
8909 _assert([[NSFileManager defaultManager]
8910 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8911 withIntermediateDirectories:YES
8916 if (access("/tmp/cydia.chk", F_OK) == 0) {
8917 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8918 _assert(errno == ENOENT);
8919 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8920 _assert(errno == ENOENT);
8923 /* APT Initialization {{{ */
8924 _assert(pkgInitConfig(*_config));
8925 _assert(pkgInitSystem(*_config, _system));
8928 _config->Set("APT::Acquire::Translation", lang);
8929 _config->Set("Acquire::http::Timeout", 15);
8930 _config->Set("Acquire::http::MaxParallel", 3);
8932 /* Color Choices {{{ */
8933 space_ = CGColorSpaceCreateDeviceRGB();
8935 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8936 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8937 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8938 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8939 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8940 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8941 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8942 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8943 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8945 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8946 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8948 /* UIKit Configuration {{{ */
8949 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8950 if ($GSFontSetUseLegacyFontMetrics != NULL)
8951 $GSFontSetUseLegacyFontMetrics(YES);
8953 // XXX: I have a feeling this was important
8954 //UIKeyboardDisableAutomaticAppearance();
8957 Colon_ = UCLocalize("COLON_DELIMITED");
8958 Error_ = UCLocalize("ERROR");
8959 Warning_ = UCLocalize("WARNING");
8962 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
8964 CGColorSpaceRelease(space_);