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 #import "UICaboodle/UCPlatform.h"
45 #import "UICaboodle/UCLocalize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <GraphicsServices/GraphicsServices.h>
52 #include <Foundation/Foundation.h>
55 #define DEPLOYMENT_TARGET_MACOSX 1
56 #define CF_BUILDING_CF 1
57 #include <CoreFoundation/CFInternal.h>
60 #include <CoreFoundation/CFPriv.h>
61 #include <CoreFoundation/CFUniChar.h>
63 #import <UIKit/UIKit.h>
65 #include <WebCore/WebCoreThread.h>
66 #import <WebKit/WebDefaultUIKitDelegate.h>
73 #include <ext/stdio_filebuf.h>
77 #include <apt-pkg/acquire.h>
78 #include <apt-pkg/acquire-item.h>
79 #include <apt-pkg/algorithms.h>
80 #include <apt-pkg/cachefile.h>
81 #include <apt-pkg/clean.h>
82 #include <apt-pkg/configuration.h>
83 #include <apt-pkg/debindexfile.h>
84 #include <apt-pkg/debmetaindex.h>
85 #include <apt-pkg/error.h>
86 #include <apt-pkg/init.h>
87 #include <apt-pkg/mmap.h>
88 #include <apt-pkg/pkgrecords.h>
89 #include <apt-pkg/sha1.h>
90 #include <apt-pkg/sourcelist.h>
91 #include <apt-pkg/sptr.h>
92 #include <apt-pkg/strutl.h>
93 #include <apt-pkg/tagfile.h>
95 #include <apr-1/apr_pools.h>
97 #include <sys/types.h>
99 #include <sys/sysctl.h>
100 #include <sys/param.h>
101 #include <sys/mount.h>
107 #include <mach-o/nlist.h>
117 #include <ext/hash_map>
119 #import "UICaboodle/BrowserView.h"
120 #import "UICaboodle/ResetView.h"
122 #import "substrate.h"
124 // Apple's sample Reachability code, ASPL licensed.
125 #import "Reachability.h"
128 /* Header Fixes and Updates {{{ */
130 UIModalPresentationFullScreen = 0,
131 UIModalPresentationPageSheet,
132 UIModalPresentationFormSheet,
133 UIModalPresentationCurrentContext,
134 } UIModalPresentationStyle;
136 @interface UIAlertView (Private)
137 - (void)setNumberOfRows:(int)rows;
138 - (void)setContext:(id)context;
142 @interface UIViewController (UIKit)
143 - (id)navigationItem;
144 - (id)navigationController;
148 @interface UITabBarController : UIViewController {
151 id _viewControllerTransitionView;
153 id _tabBarItemsToViewControllers;
154 id _selectedViewController;
155 id _moreNavigationController;
156 id _customizableViewControllers;
158 id _selectedViewControllerDuringWillAppear;
159 id _transientViewController;
160 unsigned int isShowingMoreItem:1;
161 unsigned int needsToRebuildItems:1;
162 unsigned int isBarHidden:1;
163 unsigned int editButtonOnLeft:1;
172 #define _timestamp ({ \
174 gettimeofday(&tv, NULL); \
175 tv.tv_sec * 1000000 + tv.tv_usec; \
178 typedef std::vector<class ProfileTime *> TimeList;
188 ProfileTime(const char *name) :
192 times_.push_back(this);
195 void AddTime(uint64_t time) {
202 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
214 ProfileTimer(ProfileTime &time) :
221 time_.AddTime(_timestamp - start_);
226 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
228 std::cerr << "========" << std::endl;
231 #define _profile(name) { \
232 static ProfileTime name(#name); \
233 ProfileTimer _ ## name(name);
238 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
240 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
242 void NSLogPoint(const char *fix, const CGPoint &point) {
243 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
246 void NSLogRect(const char *fix, const CGRect &rect) {
247 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
250 static _finline NSString *CydiaURL(NSString *path) {
252 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
253 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
254 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
255 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
256 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
257 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
260 /* [NSObject yieldToSelector:(withObject:)] {{{*/
261 @interface NSObject (Cydia)
262 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
263 - (id) yieldToSelector:(SEL)selector;
266 @implementation NSObject (Cydia)
271 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
272 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
273 id object([[context objectAtIndex:1] nonretainedObjectValue]);
274 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
276 /* XXX: deal with exceptions */
277 id value([self performSelector:selector withObject:object]);
279 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
280 [context removeAllObjects];
281 if ([signature methodReturnLength] != 0 && value != nil)
282 [context addObject:value];
287 performSelectorOnMainThread:@selector(doNothing)
293 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
294 /*return [self performSelector:selector withObject:object];*/
296 volatile bool stopped(false);
298 NSMutableArray *context([NSMutableArray arrayWithObjects:
299 [NSValue valueWithPointer:selector],
300 [NSValue valueWithNonretainedObject:object],
301 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
304 NSThread *thread([[[NSThread alloc]
306 selector:@selector(_yieldToContext:)
312 NSRunLoop *loop([NSRunLoop currentRunLoop]);
313 NSDate *future([NSDate distantFuture]);
315 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
317 return [context count] == 0 ? nil : [context objectAtIndex:0];
320 - (id) yieldToSelector:(SEL)selector {
321 return [self yieldToSelector:selector withObject:nil];
327 @interface CYActionSheet : UIAlertView {
331 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
334 @implementation CYActionSheet
336 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
337 if ((self = [super init])) {
338 [self setTitle:title];
339 [self setDelegate:self];
340 for (NSString *button in buttons) [self addButtonWithTitle:button];
341 [self setCancelButtonIndex:index];
345 - (void)_updateFrameForDisplay {
346 [super _updateFrameForDisplay];
347 if ([self cancelButtonIndex] == -1) {
348 NSArray *buttons = [self buttons];
349 if ([buttons count]) {
350 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
351 for (UIThreePartButton *button in buttons)
352 [button setBackground:background forState:0];
357 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
358 button_ = buttonIndex + 1;
362 [self dismissWithClickedButtonIndex:-1 animated:YES];
365 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
366 [self setRunsModal:YES];
374 /* NSForcedOrderingSearch doesn't work on the iPhone */
375 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
376 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
377 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
379 /* Information Dictionaries {{{ */
380 @interface NSMutableArray (Cydia)
381 - (void) addInfoDictionary:(NSDictionary *)info;
384 @implementation NSMutableArray (Cydia)
386 - (void) addInfoDictionary:(NSDictionary *)info {
387 [self addObject:info];
392 @interface NSMutableDictionary (Cydia)
393 - (void) addInfoDictionary:(NSDictionary *)info;
396 @implementation NSMutableDictionary (Cydia)
398 - (void) addInfoDictionary:(NSDictionary *)info {
399 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
405 #define lprintf(args...) fprintf(stderr, args)
408 #define TraceLogging (1 && !ForRelease)
409 #define HistogramInsertionSort (0 && !ForRelease)
410 #define ProfileTimes (0 && !ForRelease)
411 #define ForSaurik (0 && !ForRelease)
412 #define LogBrowser (0 && !ForRelease)
413 #define TrackResize (0 && !ForRelease)
414 #define ManualRefresh (0 && !ForRelease)
415 #define ShowInternals (0 && !ForRelease)
416 #define IgnoreInstall (0 && !ForRelease)
417 #define RecycleWebViews 0
418 #define RecyclePackageViews (1 && ForRelease)
419 #define AlwaysReload (1 && !ForRelease)
423 #define _trace(args...)
428 #define _profile(name) {
431 #define PrintTimes() do {} while (false)
435 typedef uint32_t (*SKRadixFunction)(id, void *);
437 @interface NSMutableArray (Radix)
438 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
439 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
447 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
448 struct RadixItem_ *lhs(swap), *rhs(swap + count);
450 static const size_t width = 32;
451 static const size_t bits = 11;
452 static const size_t slots = 1 << bits;
453 static const size_t passes = (width + (bits - 1)) / bits;
455 size_t *hist(new size_t[slots]);
457 for (size_t pass(0); pass != passes; ++pass) {
458 memset(hist, 0, sizeof(size_t) * slots);
460 for (size_t i(0); i != count; ++i) {
461 uint32_t key(lhs[i].key);
463 key &= _not(uint32_t) >> width - bits;
468 for (size_t i(0); i != slots; ++i) {
469 size_t local(offset);
474 for (size_t i(0); i != count; ++i) {
475 uint32_t key(lhs[i].key);
477 key &= _not(uint32_t) >> width - bits;
478 rhs[hist[key]++] = lhs[i];
481 RadixItem_ *tmp(lhs);
488 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
489 for (size_t i(0); i != count; ++i)
490 [values addObject:[self objectAtIndex:lhs[i].index]];
491 [self setArray:values];
496 @implementation NSMutableArray (Radix)
498 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
499 size_t count([self count]);
504 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
505 [invocation setSelector:selector];
506 [invocation setArgument:&object atIndex:2];
508 /* XXX: this is an unsafe optimization of doomy hell */
509 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
510 _assert(method != NULL);
511 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
512 _assert(imp != NULL);
515 struct RadixItem_ *swap(new RadixItem_[count * 2]);
517 for (size_t i(0); i != count; ++i) {
518 RadixItem_ &item(swap[i]);
521 id object([self objectAtIndex:i]);
524 [invocation setTarget:object];
526 [invocation getReturnValue:&item.key];
528 item.key = imp(object, selector, object);
532 RadixSort_(self, count, swap);
535 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
536 size_t count([self count]);
537 struct RadixItem_ *swap(new RadixItem_[count * 2]);
539 for (size_t i(0); i != count; ++i) {
540 RadixItem_ &item(swap[i]);
543 id object([self objectAtIndex:i]);
544 item.key = function(object, argument);
547 RadixSort_(self, count, swap);
552 /* Insertion Sort {{{ */
554 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
555 const char *ptr = (const char *)list;
557 CFIndex half = count / 2;
558 const char *probe = ptr + elementSize * half;
559 CFComparisonResult cr = comparator(element, probe, context);
560 if (0 == cr) return (probe - (const char *)list) / elementSize;
561 ptr = (cr < 0) ? ptr : probe + elementSize;
562 count = (cr < 0) ? half : (half + (count & 1) - 1);
564 return (ptr - (const char *)list) / elementSize;
567 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
568 const char *ptr = (const char *)list;
570 CFIndex half = count / 2;
571 const char *probe = ptr + elementSize * half;
572 CFComparisonResult cr = comparator(element, probe, context);
573 if (0 == cr) return (probe - (const char *)list) / elementSize;
574 ptr = (cr < 0) ? ptr : probe + elementSize;
575 count = (cr < 0) ? half : (half + (count & 1) - 1);
577 return (ptr - (const char *)list) / elementSize;
580 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
581 if (range.length == 0)
583 const void **values(new const void *[range.length]);
584 CFArrayGetValues(array, range, values);
586 #if HistogramInsertionSort
587 uint32_t total(0), *offsets(new uint32_t[range.length]);
590 for (CFIndex index(1); index != range.length; ++index) {
591 const void *value(values[index]);
592 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
593 CFIndex correct(index);
594 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
597 if (correct != index) {
598 size_t offset(index - correct);
599 #if HistogramInsertionSort
603 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
605 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
606 values[correct] = value;
610 CFArrayReplaceValues(array, range, values, range.length);
613 #if HistogramInsertionSort
614 for (CFIndex index(0); index != range.length; ++index)
615 if (offsets[index] != 0)
616 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
617 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
624 /* Apple Bug Fixes {{{ */
625 @implementation UIWebDocumentView (Cydia)
627 - (void) _setScrollerOffset:(CGPoint)offset {
628 UIScroller *scroller([self _scroller]);
630 CGSize size([scroller contentSize]);
631 CGSize bounds([scroller bounds].size);
634 max.x = size.width - bounds.width;
635 max.y = size.height - bounds.height;
643 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
644 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
646 [scroller setOffset:offset];
652 NSUInteger WebScriptObject$countByEnumeratingWithState$objects$count$(WebScriptObject *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
653 size_t length([self count] - state->state);
656 else if (length > count)
658 for (size_t i(0); i != length; ++i)
659 objects[i] = [self objectAtIndex:state->state++];
660 state->itemsPtr = objects;
661 state->mutationsPtr = (unsigned long *) self;
665 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
666 size_t length([self length] - state->state);
669 else if (length > count)
671 for (size_t i(0); i != length; ++i)
672 objects[i] = [self item:state->state++];
673 state->itemsPtr = objects;
674 state->mutationsPtr = (unsigned long *) self;
678 @interface NSString (UIKit)
679 - (NSString *) stringByAddingPercentEscapes;
682 /* Cydia NSString Additions {{{ */
683 @interface NSString (Cydia)
684 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
685 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
686 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
687 - (NSComparisonResult) compareByPath:(NSString *)other;
688 - (NSString *) stringByCachingURLWithCurrentCDN;
689 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
692 @implementation NSString (Cydia)
694 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
695 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
698 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
699 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
700 memcpy(data, bytes, length);
701 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
704 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
705 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
708 - (NSComparisonResult) compareByPath:(NSString *)other {
709 NSString *prefix = [self commonPrefixWithString:other options:0];
710 size_t length = [prefix length];
712 NSRange lrange = NSMakeRange(length, [self length] - length);
713 NSRange rrange = NSMakeRange(length, [other length] - length);
715 lrange = [self rangeOfString:@"/" options:0 range:lrange];
716 rrange = [other rangeOfString:@"/" options:0 range:rrange];
718 NSComparisonResult value;
720 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
721 value = NSOrderedSame;
722 else if (lrange.location == NSNotFound)
723 value = NSOrderedAscending;
724 else if (rrange.location == NSNotFound)
725 value = NSOrderedDescending;
727 value = NSOrderedSame;
729 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
730 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
731 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
732 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
734 NSComparisonResult result = [lpath compare:rpath];
735 return result == NSOrderedSame ? value : result;
738 - (NSString *) stringByCachingURLWithCurrentCDN {
740 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
741 withString:@"://cache.cydia.saurik.com/"
745 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
746 return [(id)CFURLCreateStringByAddingPercentEscapes(
751 kCFStringEncodingUTF8
758 /* C++ NSString Wrapper Cache {{{ */
765 _finline void clear_() {
766 if (cache_ != NULL) {
773 _finline bool empty() const {
777 _finline size_t size() const {
781 _finline char *data() const {
785 _finline void clear() {
790 _finline CYString() :
797 _finline ~CYString() {
801 void operator =(const CYString &rhs) {
805 if (rhs.cache_ == nil)
808 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
811 void set(apr_pool_t *pool, const char *data, size_t size) {
817 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
818 memcpy(temp, data, size);
825 _finline void set(apr_pool_t *pool, const char *data) {
826 set(pool, data, data == NULL ? 0 : strlen(data));
829 _finline void set(apr_pool_t *pool, const std::string &rhs) {
830 set(pool, rhs.data(), rhs.size());
833 bool operator ==(const CYString &rhs) const {
834 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
837 operator CFStringRef() {
838 if (cache_ == NULL) {
841 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
843 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
847 _finline operator id() {
848 return (NSString *) static_cast<CFStringRef>(*this);
852 /* C++ NSString Algorithm Adapters {{{ */
854 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
857 struct NSStringMapHash :
858 std::unary_function<NSString *, size_t>
860 _finline size_t operator ()(NSString *value) const {
861 return CFStringHashNSString((CFStringRef) value);
865 struct NSStringMapLess :
866 std::binary_function<NSString *, NSString *, bool>
868 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
869 return [lhs compare:rhs] == NSOrderedAscending;
873 struct NSStringMapEqual :
874 std::binary_function<NSString *, NSString *, bool>
876 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
877 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
878 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
879 //[lhs isEqualToString:rhs];
884 /* Perl-Compatible RegEx {{{ */
894 Pcre(const char *regex) :
899 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
902 lprintf("%d:%s\n", offset, error);
906 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
907 matches_ = new int[(capture_ + 1) * 3];
915 NSString *operator [](size_t match) {
916 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
919 bool operator ()(NSString *data) {
920 // XXX: length is for characters, not for bytes
921 return operator ()([data UTF8String], [data length]);
924 bool operator ()(const char *data, size_t size) {
926 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
930 /* Mime Addresses {{{ */
931 @interface Address : NSObject {
937 - (NSString *) address;
939 - (void) setAddress:(NSString *)address;
941 + (Address *) addressWithString:(NSString *)string;
942 - (Address *) initWithString:(NSString *)string;
945 @implementation Address
954 - (NSString *) name {
958 - (NSString *) address {
962 - (void) setAddress:(NSString *)address {
964 [address_ autorelease];
968 address_ = [address retain];
971 + (Address *) addressWithString:(NSString *)string {
972 return [[[Address alloc] initWithString:string] autorelease];
975 + (NSArray *) _attributeKeys {
976 return [NSArray arrayWithObjects:@"address", @"name", nil];
979 - (NSArray *) attributeKeys {
980 return [[self class] _attributeKeys];
983 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
984 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
987 - (Address *) initWithString:(NSString *)string {
988 if ((self = [super init]) != nil) {
989 const char *data = [string UTF8String];
990 size_t size = [string length];
992 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
994 if (address_r(data, size)) {
995 name_ = [address_r[1] retain];
996 address_ = [address_r[2] retain];
998 name_ = [string retain];
1006 /* CoreGraphics Primitives {{{ */
1017 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
1020 Set(space, red, green, blue, alpha);
1025 CGColorRelease(color_);
1032 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1034 float color[] = {red, green, blue, alpha};
1035 color_ = CGColorCreate(space, color);
1038 operator CGColorRef() {
1044 /* Random Global Variables {{{ */
1045 static const int PulseInterval_ = 50000;
1046 static const int ButtonBarWidth_ = 60;
1047 static const int ButtonBarHeight_ = 48;
1048 static const float KeyboardTime_ = 0.3f;
1051 static NSArray *Finishes_;
1053 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1054 #define NotifyConfig_ "/etc/notify.conf"
1056 static bool Queuing_;
1058 static CGColor Blue_;
1059 static CGColor Blueish_;
1060 static CGColor Black_;
1061 static CGColor Off_;
1062 static CGColor White_;
1063 static CGColor Gray_;
1064 static CGColor Green_;
1065 static CGColor Purple_;
1066 static CGColor Purplish_;
1068 static UIColor *InstallingColor_;
1069 static UIColor *RemovingColor_;
1071 static NSString *App_;
1072 static NSString *Home_;
1074 static BOOL Advanced_;
1075 static BOOL Ignored_;
1077 static UIFont *Font12_;
1078 static UIFont *Font12Bold_;
1079 static UIFont *Font14_;
1080 static UIFont *Font18Bold_;
1081 static UIFont *Font22Bold_;
1083 static const char *Machine_ = NULL;
1084 static const NSString *System_ = NULL;
1085 static const NSString *SerialNumber_ = nil;
1086 static const NSString *ChipID_ = nil;
1087 static const NSString *Token_ = nil;
1088 static const NSString *UniqueID_ = nil;
1089 static const NSString *Build_ = nil;
1090 static const NSString *Product_ = nil;
1091 static const NSString *Safari_ = nil;
1093 static CFLocaleRef Locale_;
1094 static NSArray *Languages_;
1095 static CGColorSpaceRef space_;
1097 static NSDictionary *SectionMap_;
1098 static NSMutableDictionary *Metadata_;
1099 static _transient NSMutableDictionary *Settings_;
1100 static _transient NSString *Role_;
1101 static _transient NSMutableDictionary *Packages_;
1102 static _transient NSMutableDictionary *Sections_;
1103 static _transient NSMutableDictionary *Sources_;
1104 static bool Changed_;
1105 static NSDate *now_;
1107 static bool IsWildcat_;
1110 static NSMutableArray *Documents_;
1114 /* Display Helpers {{{ */
1115 inline float Interpolate(float begin, float end, float fraction) {
1116 return (end - begin) * fraction + begin;
1119 /* XXX: localize this! */
1120 NSString *SizeString(double size) {
1121 bool negative = size < 0;
1126 while (size > 1024) {
1131 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1133 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1136 static _finline CFStringRef CFCString(const char *value) {
1137 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1140 const char *StripVersion_(const char *version) {
1141 const char *colon(strchr(version, ':'));
1143 version = colon + 1;
1147 CFStringRef StripVersion(const char *version) {
1148 const char *colon(strchr(version, ':'));
1150 version = colon + 1;
1151 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1153 return CFCString(version);
1156 NSString *LocalizeSection(NSString *section) {
1157 static Pcre title_r("^(.*?) \\((.*)\\)$");
1158 if (title_r(section)) {
1159 NSString *parent(title_r[1]);
1160 NSString *child(title_r[2]);
1162 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1163 LocalizeSection(parent),
1164 LocalizeSection(child)
1168 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1171 NSString *Simplify(NSString *title) {
1172 const char *data = [title UTF8String];
1173 size_t size = [title length];
1175 static Pcre square_r("^\\[(.*)\\]$");
1176 if (square_r(data, size))
1177 return Simplify(square_r[1]);
1179 static Pcre paren_r("^\\((.*)\\)$");
1180 if (paren_r(data, size))
1181 return Simplify(paren_r[1]);
1183 static Pcre title_r("^(.*?) \\((.*)\\)$");
1184 if (title_r(data, size))
1185 return Simplify(title_r[1]);
1191 NSString *GetLastUpdate() {
1192 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1195 return UCLocalize("NEVER_OR_UNKNOWN");
1197 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1198 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1200 CFRelease(formatter);
1202 return [(NSString *) formatted autorelease];
1205 bool isSectionVisible(NSString *section) {
1206 NSDictionary *metadata([Sections_ objectForKey:section]);
1207 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1208 return hidden == nil || ![hidden boolValue];
1213 /* Delegate Prototypes {{{ */
1217 @interface NSObject (ProgressDelegate)
1220 @protocol ProgressDelegate
1221 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1222 - (void) setProgressTitle:(NSString *)title;
1223 - (void) setProgressPercent:(float)percent;
1224 - (void) startProgress;
1225 - (void) addProgressOutput:(NSString *)output;
1226 - (bool) isCancelling:(size_t)received;
1229 @protocol ConfigurationDelegate
1230 - (void) repairWithSelector:(SEL)selector;
1231 - (void) setConfigurationData:(NSString *)data;
1234 @class PackageController;
1236 @protocol CydiaDelegate
1237 - (void) setPackageController:(PackageController *)view;
1238 - (void) clearPackage:(Package *)package;
1239 - (void) installPackage:(Package *)package;
1240 - (void) installPackages:(NSArray *)packages;
1241 - (void) removePackage:(Package *)package;
1242 - (void) distUpgrade;
1243 - (void) updateData;
1245 - (void) askForSettings;
1246 - (UIProgressHUD *) addProgressHUD;
1247 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1248 - (UIViewController *) pageForPackage:(NSString *)name;
1249 - (PackageController *) packageController;
1253 /* Status Delegation {{{ */
1255 public pkgAcquireStatus
1258 _transient NSObject<ProgressDelegate> *delegate_;
1266 void setDelegate(id delegate) {
1267 delegate_ = delegate;
1270 NSObject<ProgressDelegate> *getDelegate() const {
1274 virtual bool MediaChange(std::string media, std::string drive) {
1278 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1281 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1282 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1283 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1286 virtual void Done(pkgAcquire::ItemDesc &item) {
1289 virtual void Fail(pkgAcquire::ItemDesc &item) {
1291 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1292 item.Owner->Status == pkgAcquire::Item::StatDone
1296 std::string &error(item.Owner->ErrorText);
1300 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1301 NSArray *fields([description componentsSeparatedByString:@" "]);
1302 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1304 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1305 withObject:[NSArray arrayWithObjects:
1306 [NSString stringWithUTF8String:error.c_str()],
1313 virtual bool Pulse(pkgAcquire *Owner) {
1314 bool value = pkgAcquireStatus::Pulse(Owner);
1317 double(CurrentBytes + CurrentItems) /
1318 double(TotalBytes + TotalItems)
1321 [delegate_ setProgressPercent:percent];
1322 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1325 virtual void Start() {
1326 [delegate_ startProgress];
1329 virtual void Stop() {
1333 /* Progress Delegation {{{ */
1338 _transient id<ProgressDelegate> delegate_;
1342 virtual void Update() {
1343 /*if (abs(Percent - percent_) > 2)
1344 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1348 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1349 [delegate_ setProgressPercent:(Percent / 100)];*/
1359 void setDelegate(id delegate) {
1360 delegate_ = delegate;
1363 id getDelegate() const {
1367 virtual void Done() {
1369 //[delegate_ setProgressPercent:1];
1374 /* Database Interface {{{ */
1375 typedef std::map< unsigned long, _H<Source> > SourceMap;
1377 @interface Database : NSObject {
1383 pkgCacheFile cache_;
1384 pkgDepCache::Policy *policy_;
1385 pkgRecords *records_;
1386 pkgProblemResolver *resolver_;
1387 pkgAcquire *fetcher_;
1389 SPtr<pkgPackageManager> manager_;
1390 pkgSourceList *list_;
1393 NSMutableArray *packages_;
1395 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1404 + (Database *) sharedInstance;
1407 - (void) _readCydia:(NSNumber *)fd;
1408 - (void) _readStatus:(NSNumber *)fd;
1409 - (void) _readOutput:(NSNumber *)fd;
1413 - (Package *) packageWithName:(NSString *)name;
1415 - (pkgCacheFile &) cache;
1416 - (pkgDepCache::Policy *) policy;
1417 - (pkgRecords *) records;
1418 - (pkgProblemResolver *) resolver;
1419 - (pkgAcquire &) fetcher;
1420 - (pkgSourceList &) list;
1421 - (NSArray *) packages;
1422 - (NSArray *) sources;
1423 - (void) reloadData;
1431 - (void) setVisible;
1433 - (void) updateWithStatus:(Status &)status;
1435 - (void) setDelegate:(id)delegate;
1436 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1439 /* Delegate Helpers {{{ */
1440 @implementation NSObject(ProgressDelegate)
1442 - (void) _setProgressErrorPackage:(NSArray *)args {
1443 [self performSelector:@selector(setProgressError:forPackage:)
1444 withObject:[args objectAtIndex:0]
1445 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1449 - (void) _setProgressErrorTitle:(NSArray *)args {
1450 [self performSelector:@selector(setProgressError:withTitle:)
1451 withObject:[args objectAtIndex:0]
1452 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1456 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1457 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1458 withObject:[NSArray arrayWithObjects:error, title, nil]
1463 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1464 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1465 // XXX: holy typecast batman!
1466 [self setProgressError:error withTitle:(package == nil ? id : [package name])];
1472 /* Source Class {{{ */
1473 @interface Source : NSObject {
1474 CYString depiction_;
1475 CYString description_;
1481 CYString distribution_;
1486 NSString *authority_;
1488 CYString defaultIcon_;
1490 NSDictionary *record_;
1494 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1496 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1498 - (NSString *) depictionForPackage:(NSString *)package;
1499 - (NSString *) supportForPackage:(NSString *)package;
1501 - (NSDictionary *) record;
1505 - (NSString *) distribution;
1506 - (NSString *) type;
1508 - (NSString *) host;
1510 - (NSString *) name;
1511 - (NSString *) description;
1512 - (NSString *) label;
1513 - (NSString *) origin;
1514 - (NSString *) version;
1516 - (NSString *) defaultIcon;
1520 @implementation Source
1524 distribution_.clear();
1527 description_.clear();
1533 defaultIcon_.clear();
1535 if (record_ != nil) {
1545 if (authority_ != nil) {
1546 [authority_ release];
1556 + (NSArray *) _attributeKeys {
1557 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1560 - (NSArray *) attributeKeys {
1561 return [[self class] _attributeKeys];
1564 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1565 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1568 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1571 trusted_ = index->IsTrusted();
1573 uri_.set(pool, index->GetURI());
1574 distribution_.set(pool, index->GetDist());
1575 type_.set(pool, index->GetType());
1577 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1578 if (dindex != NULL) {
1580 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1583 pkgTagFile tags(&fd);
1585 pkgTagSection section;
1592 {"default-icon", &defaultIcon_},
1593 {"depiction", &depiction_},
1594 {"description", &description_},
1596 {"origin", &origin_},
1597 {"support", &support_},
1598 {"version", &version_},
1601 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1602 const char *start, *end;
1604 if (section.Find(names[i].name_, start, end)) {
1605 CYString &value(*names[i].value_);
1606 value.set(pool, start, end - start);
1612 record_ = [Sources_ objectForKey:[self key]];
1614 record_ = [record_ retain];
1616 NSURL *url([NSURL URLWithString:uri_]);
1620 host_ = [[host_ lowercaseString] retain];
1625 authority_ = [url path];
1627 if (authority_ != nil)
1628 authority_ = [authority_ retain];
1631 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1632 if ((self = [super init]) != nil) {
1633 [self setMetaIndex:index inPool:pool];
1637 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1638 NSDictionary *lhr = [self record];
1639 NSDictionary *rhr = [source record];
1642 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1644 NSString *lhs = [self name];
1645 NSString *rhs = [source name];
1647 if ([lhs length] != 0 && [rhs length] != 0) {
1648 unichar lhc = [lhs characterAtIndex:0];
1649 unichar rhc = [rhs characterAtIndex:0];
1651 if (isalpha(lhc) && !isalpha(rhc))
1652 return NSOrderedAscending;
1653 else if (!isalpha(lhc) && isalpha(rhc))
1654 return NSOrderedDescending;
1657 return [lhs compare:rhs options:LaxCompareOptions_];
1660 - (NSString *) depictionForPackage:(NSString *)package {
1661 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1664 - (NSString *) supportForPackage:(NSString *)package {
1665 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1668 - (NSDictionary *) record {
1676 - (NSString *) uri {
1680 - (NSString *) distribution {
1681 return distribution_;
1684 - (NSString *) type {
1688 - (NSString *) key {
1689 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1692 - (NSString *) host {
1696 - (NSString *) name {
1697 return origin_.empty() ? authority_ : origin_;
1700 - (NSString *) description {
1701 return description_;
1704 - (NSString *) label {
1705 return label_.empty() ? authority_ : label_;
1708 - (NSString *) origin {
1712 - (NSString *) version {
1716 - (NSString *) defaultIcon {
1717 return defaultIcon_;
1722 /* Relationship Class {{{ */
1723 @interface Relationship : NSObject {
1728 - (NSString *) type;
1730 - (NSString *) name;
1734 @implementation Relationship
1742 - (NSString *) type {
1750 - (NSString *) name {
1757 /* Package Class {{{ */
1758 @interface Package : NSObject {
1762 pkgCache::VerIterator version_;
1763 pkgCache::PkgIterator iterator_;
1764 _transient Database *database_;
1765 pkgCache::VerFileIterator file_;
1772 NSString *section$_;
1779 CYString installed_;
1785 CYString depiction_;
1796 NSMutableArray *tags_;
1799 NSArray *relationships_;
1801 NSMutableDictionary *metadata_;
1802 _transient NSDate *firstSeen_;
1803 _transient NSDate *lastSeen_;
1807 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1808 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1810 - (pkgCache::PkgIterator) iterator;
1813 - (NSString *) section;
1814 - (NSString *) simpleSection;
1816 - (NSString *) longSection;
1817 - (NSString *) shortSection;
1821 - (Address *) maintainer;
1823 - (NSString *) longDescription;
1824 - (NSString *) shortDescription;
1827 - (NSMutableDictionary *) metadata;
1829 - (BOOL) subscribed;
1832 - (NSString *) latest;
1833 - (NSString *) installed;
1834 - (BOOL) uninstalled;
1837 - (BOOL) upgradableAndEssential:(BOOL)essential;
1840 - (BOOL) unfiltered;
1844 - (BOOL) halfConfigured;
1845 - (BOOL) halfInstalled;
1847 - (NSString *) mode;
1849 - (void) setVisible;
1852 - (NSString *) name;
1854 - (NSString *) homepage;
1855 - (NSString *) depiction;
1856 - (Address *) author;
1858 - (NSString *) support;
1860 - (NSArray *) files;
1861 - (NSArray *) relationships;
1862 - (NSArray *) warnings;
1863 - (NSArray *) applications;
1865 - (Source *) source;
1866 - (NSString *) role;
1868 - (BOOL) matches:(NSString *)text;
1870 - (bool) hasSupportingRole;
1871 - (BOOL) hasTag:(NSString *)tag;
1872 - (NSString *) primaryPurpose;
1873 - (NSArray *) purposes;
1874 - (bool) isCommercial;
1876 - (CYString &) cyname;
1878 - (uint32_t) compareBySection:(NSArray *)sections;
1880 - (uint32_t) compareForChanges;
1885 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1886 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1887 - (bool) isInstalledAndVisible:(NSNumber *)number;
1888 - (bool) isVisibleInSection:(NSString *)section;
1889 - (bool) isVisibleInSource:(Source *)source;
1893 uint32_t PackageChangesRadix(Package *self, void *) {
1898 uint32_t timestamp : 30;
1899 uint32_t ignored : 1;
1900 uint32_t upgradable : 1;
1904 bool upgradable([self upgradableAndEssential:YES]);
1905 value.bits.upgradable = upgradable ? 1 : 0;
1908 value.bits.timestamp = 0;
1909 value.bits.ignored = [self ignored] ? 0 : 1;
1910 value.bits.upgradable = 1;
1912 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1913 value.bits.ignored = 0;
1914 value.bits.upgradable = 0;
1917 return _not(uint32_t) - value.key;
1920 _finline static void Stifle(uint8_t &value) {
1923 uint32_t PackagePrefixRadix(Package *self, void *context) {
1924 size_t offset(reinterpret_cast<size_t>(context));
1925 CYString &name([self cyname]);
1927 size_t size(name.size());
1930 char *text(name.data());
1933 if (!isdigit(text[0]))
1937 while (size != digits && isdigit(text[digits]))
1947 if (offset == 0 && zeros != 0) {
1948 memset(data, '0', zeros);
1949 memcpy(data + zeros, text, 4 - zeros);
1951 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1952 if (size <= offset - zeros)
1955 text += offset - zeros;
1956 size -= offset - zeros;
1959 memcpy(data, text, 4);
1961 memcpy(data, text, size);
1962 memset(data + size, 0, 4 - size);
1965 for (size_t i(0); i != 4; ++i)
1966 if (isalpha(data[i]))
1971 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1973 /* XXX: ntohl may be more honest */
1974 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1977 CYString &(*PackageName)(Package *self, SEL sel);
1979 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1980 _profile(PackageNameCompare)
1981 CYString &lhi(PackageName(lhs, @selector(cyname)));
1982 CYString &rhi(PackageName(rhs, @selector(cyname)));
1983 CFStringRef lhn(lhi), rhn(rhi);
1986 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1987 else if (rhn == NULL)
1988 return NSOrderedDescending;
1990 _profile(PackageNameCompare$NumbersLast)
1991 if (!lhi.empty() && !rhi.empty()) {
1992 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1993 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1994 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1995 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1996 return lha ? NSOrderedAscending : NSOrderedDescending;
2000 CFIndex length = CFStringGetLength(lhn);
2002 _profile(PackageNameCompare$Compare)
2003 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2008 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2009 return PackageNameCompare(*lhs, *rhs, context);
2012 struct PackageNameOrdering :
2013 std::binary_function<Package *, Package *, bool>
2015 _finline bool operator ()(Package *lhs, Package *rhs) const {
2016 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2020 @implementation Package
2022 - (NSString *) description {
2023 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2029 if (section$_ != nil)
2030 [section$_ release];
2035 if (sponsor$_ != nil)
2036 [sponsor$_ release];
2037 if (author$_ != nil)
2044 if (relationships_ != nil)
2045 [relationships_ release];
2046 if (metadata_ != nil)
2047 [metadata_ release];
2052 + (NSString *) webScriptNameForSelector:(SEL)selector {
2053 if (selector == @selector(hasTag:))
2059 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2060 return [self webScriptNameForSelector:selector] == nil;
2063 + (NSArray *) _attributeKeys {
2064 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];
2067 - (NSArray *) attributeKeys {
2068 return [[self class] _attributeKeys];
2071 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2072 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2082 _profile(Package$parse)
2083 pkgRecords::Parser *parser;
2085 _profile(Package$parse$Lookup)
2086 parser = &[database_ records]->Lookup(file_);
2091 _profile(Package$parse$Find)
2097 {"depiction", &depiction_},
2098 {"homepage", &homepage_},
2099 {"website", &website},
2101 {"support", &support_},
2102 {"sponsor", &sponsor_},
2103 {"author", &author_},
2106 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2107 const char *start, *end;
2109 if (parser->Find(names[i].name_, start, end)) {
2110 CYString &value(*names[i].value_);
2111 _profile(Package$parse$Value)
2112 value.set(pool_, start, end - start);
2118 _profile(Package$parse$Tagline)
2119 const char *start, *end;
2120 if (parser->ShortDesc(start, end)) {
2121 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2124 while (stop != start && stop[-1] == '\r')
2126 tagline_.set(pool_, start, stop - start);
2130 _profile(Package$parse$Retain)
2131 if (homepage_.empty())
2132 homepage_ = website;
2133 if (homepage_ == depiction_)
2139 - (void) setVisible {
2140 visible_ = required_ && [self unfiltered];
2143 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2144 if ((self = [super init]) != nil) {
2145 _profile(Package$initWithVersion)
2146 @synchronized (database) {
2147 era_ = [database era];
2151 iterator_ = version.ParentPkg();
2152 database_ = database;
2154 _profile(Package$initWithVersion$Latest)
2155 latest_ = (NSString *) StripVersion(version_.VerStr());
2158 pkgCache::VerIterator current;
2159 _profile(Package$initWithVersion$Versions)
2160 current = iterator_.CurrentVer();
2162 installed_.set(pool_, StripVersion_(current.VerStr()));
2164 if (!version_.end())
2165 file_ = version_.FileList();
2167 pkgCache &cache([database_ cache]);
2168 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2172 _profile(Package$initWithVersion$Name)
2173 id_.set(pool_, iterator_.Name());
2174 name_.set(pool, iterator_.Display());
2178 _profile(Package$initWithVersion$Source)
2179 source_ = [database_ getSource:file_.File()];
2188 _profile(Package$initWithVersion$Tags)
2189 pkgCache::TagIterator tag(iterator_.TagList());
2191 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2193 const char *name(tag.Name());
2194 [tags_ addObject:(NSString *)CFCString(name)];
2195 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2196 role_ = (NSString *) CFCString(name + 6);
2197 if (required_ && strncmp(name, "require::", 9) == 0 && (
2202 } while (!tag.end());
2206 bool changed(false);
2207 NSString *key([id_ lowercaseString]);
2209 _profile(Package$initWithVersion$Metadata)
2210 metadata_ = [Packages_ objectForKey:key];
2212 if (metadata_ == nil) {
2215 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2216 firstSeen_, @"FirstSeen",
2217 latest_, @"LastVersion",
2222 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2223 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2225 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2226 subscribed_ = [subscribed boolValue];
2228 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2230 if (firstSeen_ == nil) {
2231 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2232 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2236 if (version == nil) {
2237 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2239 } else if (![version isEqualToString:latest_]) {
2240 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2242 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2247 metadata_ = [metadata_ retain];
2250 [Packages_ setObject:metadata_ forKey:key];
2255 _profile(Package$initWithVersion$Section)
2256 section_.set(pool_, iterator_.Section());
2259 obsolete_ = [self hasTag:@"cydia::obsolete"];
2260 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2262 } _end } return self;
2265 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2266 @synchronized ([Database class]) {
2267 pkgCache::VerIterator version;
2269 _profile(Package$packageWithIterator$GetCandidateVer)
2270 version = [database policy]->GetCandidateVer(iterator);
2276 return [[[Package alloc]
2277 initWithVersion:version
2284 - (pkgCache::PkgIterator) iterator {
2288 - (NSString *) section {
2289 if (section$_ == nil) {
2290 if (section_.empty())
2293 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2294 NSString *name(section_);
2297 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2298 if (NSString *rename = [value objectForKey:@"Rename"]) {
2303 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2307 - (NSString *) simpleSection {
2308 if (NSString *section = [self section])
2309 return Simplify(section);
2314 - (NSString *) longSection {
2315 return LocalizeSection([self section]);
2318 - (NSString *) shortSection {
2319 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2322 - (NSString *) uri {
2325 pkgIndexFile *index;
2326 pkgCache::PkgFileIterator file(file_.File());
2327 if (![database_ list].FindIndex(file, index))
2329 return [NSString stringWithUTF8String:iterator_->Path];
2330 //return [NSString stringWithUTF8String:file.Site()];
2331 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2335 - (Address *) maintainer {
2338 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2339 const std::string &maintainer(parser->Maintainer());
2340 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2344 return version_.end() ? 0 : version_->InstalledSize;
2347 - (NSString *) longDescription {
2350 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2351 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2353 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2354 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2355 if ([lines count] < 2)
2358 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2359 for (size_t i(1), e([lines count]); i != e; ++i) {
2360 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2361 [trimmed addObject:trim];
2364 return [trimmed componentsJoinedByString:@"\n"];
2367 - (NSString *) shortDescription {
2372 _profile(Package$index)
2373 CFStringRef name((CFStringRef) [self name]);
2374 if (CFStringGetLength(name) == 0)
2376 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2377 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2379 return toupper(character);
2383 - (NSMutableDictionary *) metadata {
2388 if (subscribed_ && lastSeen_ != nil)
2393 - (BOOL) subscribed {
2398 NSDictionary *metadata([self metadata]);
2399 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2400 return [ignored boolValue];
2405 - (NSString *) latest {
2409 - (NSString *) installed {
2413 - (BOOL) uninstalled {
2414 return installed_.empty();
2418 return !version_.end();
2421 - (BOOL) upgradableAndEssential:(BOOL)essential {
2422 _profile(Package$upgradableAndEssential)
2423 pkgCache::VerIterator current(iterator_.CurrentVer());
2425 return essential && essential_ && visible_;
2427 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2431 - (BOOL) essential {
2436 return [database_ cache][iterator_].InstBroken();
2439 - (BOOL) unfiltered {
2440 NSString *section([self section]);
2441 return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
2449 unsigned char current(iterator_->CurrentState);
2450 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2453 - (BOOL) halfConfigured {
2454 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2457 - (BOOL) halfInstalled {
2458 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2462 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2463 return state.Mode != pkgDepCache::ModeKeep;
2466 - (NSString *) mode {
2467 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2469 switch (state.Mode) {
2470 case pkgDepCache::ModeDelete:
2471 if ((state.iFlags & pkgDepCache::Purge) != 0)
2475 case pkgDepCache::ModeKeep:
2476 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2477 return @"REINSTALL";
2478 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2482 case pkgDepCache::ModeInstall:
2483 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2484 return @"REINSTALL";
2485 else*/ switch (state.Status) {
2487 return @"DOWNGRADE";
2493 return @"NEW_INSTALL";
2504 - (NSString *) name {
2505 return name_.empty() ? id_ : name_;
2508 - (UIImage *) icon {
2509 NSString *section = [self simpleSection];
2513 if ([icon_ hasPrefix:@"file:///"])
2514 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2515 if (icon == nil) if (section != nil)
2516 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2517 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2518 if ([dicon hasPrefix:@"file:///"])
2519 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2521 icon = [UIImage applicationImageNamed:@"unknown.png"];
2525 - (NSString *) homepage {
2529 - (NSString *) depiction {
2530 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2533 - (Address *) sponsor {
2534 if (sponsor$_ == nil) {
2535 if (sponsor_.empty())
2537 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2541 - (Address *) author {
2542 if (author$_ == nil) {
2543 if (author_.empty())
2545 author$_ = [[Address addressWithString:author_] retain];
2549 - (NSString *) support {
2550 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2553 - (NSArray *) files {
2554 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2555 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2558 fin.open([path UTF8String]);
2563 while (std::getline(fin, line))
2564 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2569 - (NSArray *) relationships {
2570 return relationships_;
2573 - (NSArray *) warnings {
2574 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2575 const char *name(iterator_.Name());
2577 size_t length(strlen(name));
2578 if (length < 2) invalid:
2579 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2580 else for (size_t i(0); i != length; ++i)
2582 /* XXX: technically this is not allowed */
2583 (name[i] < 'A' || name[i] > 'Z') &&
2584 (name[i] < 'a' || name[i] > 'z') &&
2585 (name[i] < '0' || name[i] > '9') &&
2586 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2589 if (strcmp(name, "cydia") != 0) {
2592 bool _private = false;
2595 bool repository = [[self section] isEqualToString:@"Repositories"];
2597 if (NSArray *files = [self files])
2598 for (NSString *file in files)
2599 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2601 else if (!user && [file isEqualToString:@"/User"])
2603 else if (!_private && [file isEqualToString:@"/private"])
2605 else if (!stash && [file isEqualToString:@"/var/stash"])
2608 /* XXX: this is not sensitive enough. only some folders are valid. */
2609 if (cydia && !repository)
2610 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2612 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2614 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2616 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2619 return [warnings count] == 0 ? nil : warnings;
2622 - (NSArray *) applications {
2623 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2625 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2627 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2628 if (NSArray *files = [self files])
2629 for (NSString *file in files)
2630 if (application_r(file)) {
2631 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2632 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2633 if ([id isEqualToString:me])
2636 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2638 display = application_r[1];
2640 NSString *bundle([file stringByDeletingLastPathComponent]);
2641 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2642 if (icon == nil || [icon length] == 0)
2644 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2646 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2647 [applications addObject:application];
2649 [application addObject:id];
2650 [application addObject:display];
2651 [application addObject:url];
2654 return [applications count] == 0 ? nil : applications;
2657 - (Source *) source {
2659 @synchronized (database_) {
2660 if ([database_ era] != era_ || file_.end())
2663 source_ = [database_ getSource:file_.File()];
2675 - (NSString *) role {
2679 - (BOOL) matches:(NSString *)text {
2685 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2686 if (range.location != NSNotFound)
2689 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2690 if (range.location != NSNotFound)
2693 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2694 if (range.location != NSNotFound)
2700 - (bool) hasSupportingRole {
2703 if ([role_ isEqualToString:@"enduser"])
2705 if ([Role_ isEqualToString:@"User"])
2707 if ([role_ isEqualToString:@"hacker"])
2709 if ([Role_ isEqualToString:@"Hacker"])
2711 if ([role_ isEqualToString:@"developer"])
2713 if ([Role_ isEqualToString:@"Developer"])
2718 - (BOOL) hasTag:(NSString *)tag {
2719 return tags_ == nil ? NO : [tags_ containsObject:tag];
2722 - (NSString *) primaryPurpose {
2723 for (NSString *tag in tags_)
2724 if ([tag hasPrefix:@"purpose::"])
2725 return [tag substringFromIndex:9];
2729 - (NSArray *) purposes {
2730 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2731 for (NSString *tag in tags_)
2732 if ([tag hasPrefix:@"purpose::"])
2733 [purposes addObject:[tag substringFromIndex:9]];
2734 return [purposes count] == 0 ? nil : purposes;
2737 - (bool) isCommercial {
2738 return [self hasTag:@"cydia::commercial"];
2741 - (CYString &) cyname {
2742 return name_.empty() ? id_ : name_;
2745 - (uint32_t) compareBySection:(NSArray *)sections {
2746 NSString *section([self section]);
2747 for (size_t i(0), e([sections count]); i != e; ++i) {
2748 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2752 return _not(uint32_t);
2755 - (uint32_t) compareForChanges {
2760 uint32_t timestamp : 30;
2761 uint32_t ignored : 1;
2762 uint32_t upgradable : 1;
2766 bool upgradable([self upgradableAndEssential:YES]);
2767 value.bits.upgradable = upgradable ? 1 : 0;
2770 value.bits.timestamp = 0;
2771 value.bits.ignored = [self ignored] ? 0 : 1;
2772 value.bits.upgradable = 1;
2774 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2775 value.bits.ignored = 0;
2776 value.bits.upgradable = 0;
2779 return _not(uint32_t) - value.key;
2783 pkgProblemResolver *resolver = [database_ resolver];
2784 resolver->Clear(iterator_);
2785 resolver->Protect(iterator_);
2789 pkgProblemResolver *resolver = [database_ resolver];
2790 resolver->Clear(iterator_);
2791 resolver->Protect(iterator_);
2792 pkgCacheFile &cache([database_ cache]);
2793 cache->MarkInstall(iterator_, false);
2794 pkgDepCache::StateCache &state((*cache)[iterator_]);
2795 if (!state.Install())
2796 cache->SetReInstall(iterator_, true);
2800 pkgProblemResolver *resolver = [database_ resolver];
2801 resolver->Clear(iterator_);
2802 resolver->Protect(iterator_);
2803 resolver->Remove(iterator_);
2804 [database_ cache]->MarkDelete(iterator_, true);
2807 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2808 _profile(Package$isUnfilteredAndSearchedForBy)
2811 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2812 value &= [self unfiltered];
2815 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2816 value &= [self matches:search];
2823 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2824 if ([search length] == 0)
2827 _profile(Package$isUnfilteredAndSelectedForBy)
2830 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2831 value &= [self unfiltered];
2834 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2835 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2842 - (bool) isInstalledAndVisible:(NSNumber *)number {
2843 return (![number boolValue] || [self visible]) && ![self uninstalled];
2846 - (bool) isVisibleInSection:(NSString *)name {
2847 NSString *section = [self section];
2852 section == nil && [name length] == 0 ||
2853 [name isEqualToString:section]
2857 - (bool) isVisibleInSource:(Source *)source {
2858 return [self source] == source && [self visible];
2863 /* Section Class {{{ */
2864 @interface Section : NSObject {
2869 NSString *localized_;
2872 - (NSComparisonResult) compareByLocalized:(Section *)section;
2873 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2874 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2875 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2876 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2877 - (NSString *) name;
2884 - (void) addToCount;
2886 - (void) setCount:(size_t)count;
2887 - (NSString *) localized;
2891 @implementation Section
2895 if (localized_ != nil)
2896 [localized_ release];
2900 - (NSComparisonResult) compareByLocalized:(Section *)section {
2901 NSString *lhs(localized_);
2902 NSString *rhs([section localized]);
2904 /*if ([lhs length] != 0 && [rhs length] != 0) {
2905 unichar lhc = [lhs characterAtIndex:0];
2906 unichar rhc = [rhs characterAtIndex:0];
2908 if (isalpha(lhc) && !isalpha(rhc))
2909 return NSOrderedAscending;
2910 else if (!isalpha(lhc) && isalpha(rhc))
2911 return NSOrderedDescending;
2914 return [lhs compare:rhs options:LaxCompareOptions_];
2917 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2918 if ((self = [self initWithName:name localize:NO]) != nil) {
2919 if (localized != nil)
2920 localized_ = [localized retain];
2924 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2925 return [self initWithName:name row:0 localize:localize];
2928 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2929 if ((self = [super init]) != nil) {
2930 name_ = [name retain];
2934 localized_ = [LocalizeSection(name_) retain];
2938 /* XXX: localize the index thingees */
2939 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2940 if ((self = [super init]) != nil) {
2941 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2947 - (NSString *) name {
2967 - (void) addToCount {
2971 - (void) setCount:(size_t)count {
2975 - (NSString *) localized {
2982 static NSString *Colon_;
2983 static NSString *Error_;
2984 static NSString *Warning_;
2986 /* Database Implementation {{{ */
2987 @implementation Database
2989 + (Database *) sharedInstance {
2990 static Database *instance;
2991 if (instance == nil)
2992 instance = [[Database alloc] init];
3002 NSRecycleZone(zone_);
3003 // XXX: malloc_destroy_zone(zone_);
3004 apr_pool_destroy(pool_);
3008 - (void) _readCydia:(NSNumber *)fd { _pooled
3009 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3010 std::istream is(&ib);
3013 static Pcre finish_r("^finish:([^:]*)$");
3015 while (std::getline(is, line)) {
3016 const char *data(line.c_str());
3017 size_t size = line.size();
3018 lprintf("C:%s\n", data);
3020 if (finish_r(data, size)) {
3021 NSString *finish = finish_r[1];
3022 int index = [Finishes_ indexOfObject:finish];
3023 if (index != INT_MAX && index > Finish_)
3031 - (void) _readStatus:(NSNumber *)fd { _pooled
3032 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3033 std::istream is(&ib);
3036 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3037 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3039 while (std::getline(is, line)) {
3040 const char *data(line.c_str());
3041 size_t size(line.size());
3042 lprintf("S:%s\n", data);
3044 if (conffile_r(data, size)) {
3045 [delegate_ setConfigurationData:conffile_r[1]];
3046 } else if (strncmp(data, "status: ", 8) == 0) {
3047 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3048 [delegate_ setProgressTitle:string];
3049 } else if (pmstatus_r(data, size)) {
3050 std::string type([pmstatus_r[1] UTF8String]);
3051 NSString *id = pmstatus_r[2];
3053 float percent([pmstatus_r[3] floatValue]);
3054 [delegate_ setProgressPercent:(percent / 100)];
3056 NSString *string = pmstatus_r[4];
3058 if (type == "pmerror")
3059 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3060 withObject:[NSArray arrayWithObjects:string, id, nil]
3063 else if (type == "pmstatus") {
3064 [delegate_ setProgressTitle:string];
3065 } else if (type == "pmconffile")
3066 [delegate_ setConfigurationData:string];
3068 lprintf("E:unknown pmstatus\n");
3070 lprintf("E:unknown status\n");
3076 - (void) _readOutput:(NSNumber *)fd { _pooled
3077 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3078 std::istream is(&ib);
3081 while (std::getline(is, line)) {
3082 lprintf("O:%s\n", line.c_str());
3083 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3093 - (Package *) packageWithName:(NSString *)name {
3094 @synchronized ([Database class]) {
3095 if (static_cast<pkgDepCache *>(cache_) == NULL)
3097 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3098 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3101 - (Database *) init {
3102 if ((self = [super init]) != nil) {
3109 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3110 apr_pool_create(&pool_, NULL);
3112 packages_ = [[NSMutableArray alloc] init];
3116 _assert(pipe(fds) != -1);
3119 _config->Set("APT::Keep-Fds::", cydiafd_);
3120 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3123 detachNewThreadSelector:@selector(_readCydia:)
3125 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3128 _assert(pipe(fds) != -1);
3132 detachNewThreadSelector:@selector(_readStatus:)
3134 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3137 _assert(pipe(fds) != -1);
3138 _assert(dup2(fds[0], 0) != -1);
3139 _assert(close(fds[0]) != -1);
3141 input_ = fdopen(fds[1], "a");
3143 _assert(pipe(fds) != -1);
3144 _assert(dup2(fds[1], 1) != -1);
3145 _assert(close(fds[1]) != -1);
3148 detachNewThreadSelector:@selector(_readOutput:)
3150 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3155 - (pkgCacheFile &) cache {
3159 - (pkgDepCache::Policy *) policy {
3163 - (pkgRecords *) records {
3167 - (pkgProblemResolver *) resolver {
3171 - (pkgAcquire &) fetcher {
3175 - (pkgSourceList &) list {
3179 - (NSArray *) packages {
3183 - (NSArray *) sources {
3184 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3185 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3186 [sources addObject:i->second];
3190 - (NSArray *) issues {
3191 if (cache_->BrokenCount() == 0)
3194 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3196 for (Package *package in packages_) {
3197 if (![package broken])
3199 pkgCache::PkgIterator pkg([package iterator]);
3201 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3202 [entry addObject:[package name]];
3203 [issues addObject:entry];
3205 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3209 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3210 pkgCache::DepIterator start;
3211 pkgCache::DepIterator end;
3212 dep.GlobOr(start, end); // ++dep
3214 if (!cache_->IsImportantDep(end))
3216 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3219 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3220 [entry addObject:failure];
3221 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3223 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3224 if (Package *package = [self packageWithName:name])
3225 name = [package name];
3226 [failure addObject:name];
3228 pkgCache::PkgIterator target(start.TargetPkg());
3229 if (target->ProvidesList != 0)
3230 [failure addObject:@"?"];
3232 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3234 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3235 else if (!cache_[target].CandidateVerIter(cache_).end())
3236 [failure addObject:@"-"];
3237 else if (target->ProvidesList == 0)
3238 [failure addObject:@"!"];
3240 [failure addObject:@"%"];
3244 if (start.TargetVer() != 0)
3245 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3256 - (bool) popErrorWithTitle:(NSString *)title {
3258 std::string message;
3260 while (!_error->empty()) {
3262 bool warning(!_error->PopMessage(error));
3266 size_t size(error.size());
3267 if (size == 0 || error[size - 1] != '\n')
3269 error.resize(size - 1);
3271 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3273 if (!message.empty())
3278 if (fatal && !message.empty())
3279 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3284 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3285 return [self popErrorWithTitle:title] || !success;
3288 - (void) reloadData { _pooled
3289 @synchronized ([Database class]) {
3290 @synchronized (self) {
3294 [packages_ removeAllObjects];
3320 apr_pool_clear(pool_);
3321 NSRecycleZone(zone_);
3323 int chk(creat("/tmp/cydia.chk", 0644));
3327 NSString *title(UCLocalize("DATABASE"));
3330 if (!cache_.Open(progress_, true)) { pop:
3332 bool warning(!_error->PopMessage(error));
3333 lprintf("cache_.Open():[%s]\n", error.c_str());
3335 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3336 [delegate_ repairWithSelector:@selector(configure)];
3337 else if (error == "The package lists or status file could not be parsed or opened.")
3338 [delegate_ repairWithSelector:@selector(update)];
3339 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3340 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3341 // else if (error == "The list of sources could not be read.")
3343 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3352 unlink("/tmp/cydia.chk");
3354 now_ = [[NSDate date] retain];
3356 policy_ = new pkgDepCache::Policy();
3357 records_ = new pkgRecords(cache_);
3358 resolver_ = new pkgProblemResolver(cache_);
3359 fetcher_ = new pkgAcquire(&status_);
3362 list_ = new pkgSourceList();
3363 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3366 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3367 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3371 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3374 if (cache_->BrokenCount() != 0) {
3375 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3378 if (cache_->BrokenCount() != 0) {
3379 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3383 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3389 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3390 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3391 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3392 // XXX: this could be more intelligent
3393 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3394 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3396 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3403 /*std::vector<Package *> packages;
3404 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3405 [packages_ release];
3410 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3411 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3412 //packages.push_back(package);
3413 [packages_ addObject:package];
3417 /*if (packages.empty())
3418 packages_ = [[NSArray alloc] init];
3420 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3423 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3424 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3425 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3433 /*if (!packages.empty())
3434 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3435 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3437 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3439 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3441 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3447 - (void) configure {
3448 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3449 system([dpkg UTF8String]);
3453 // XXX: I don't remember this condition
3458 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3460 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3462 if ([self popErrorWithTitle:title])
3466 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3469 public pkgArchiveCleaner
3472 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3477 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3484 fetcher_->Shutdown();
3486 pkgRecords records(cache_);
3488 lock_ = new FileFd();
3489 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3491 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3493 if ([self popErrorWithTitle:title])
3497 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3500 manager_ = (_system->CreatePM(cache_));
3501 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3508 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3510 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3512 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3514 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3515 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3518 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3523 bool failed = false;
3524 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3525 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3527 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3530 std::string uri = (*item)->DescURI();
3531 std::string error = (*item)->ErrorText;
3533 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3536 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3537 withObject:[NSArray arrayWithObjects:
3538 [NSString stringWithUTF8String:error.c_str()],
3550 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3552 if (_error->PendingError()) {
3557 if (result == pkgPackageManager::Failed) {
3562 if (result != pkgPackageManager::Completed) {
3567 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3569 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3571 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3572 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3575 if (![before isEqualToArray:after])
3580 NSString *title(UCLocalize("UPGRADE"));
3581 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3587 [self updateWithStatus:status_];
3590 - (void) setVisible {
3591 for (Package *package in packages_)
3592 [package setVisible];
3595 - (void) updateWithStatus:(Status &)status {
3596 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3597 NSString *title(UCLocalize("REFRESHING_DATA"));
3600 if (!list.ReadMainList())
3601 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3604 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3605 if ([self popErrorWithTitle:title])
3608 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3609 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */;
3611 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3615 - (void) setDelegate:(id)delegate {
3616 delegate_ = delegate;
3617 status_.setDelegate(delegate);
3618 progress_.setDelegate(delegate);
3621 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3622 SourceMap::const_iterator i(sources_.find(file->ID));
3623 return i == sources_.end() ? nil : i->second;
3629 /* Confirmation Controller {{{ */
3630 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3631 if (!iterator.end())
3632 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3633 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3635 pkgCache::PkgIterator package(dep.TargetPkg());
3638 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3646 /* Web Scripting {{{ */
3647 @interface CydiaObject : NSObject {
3652 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3655 @implementation CydiaObject
3658 [indirect_ release];
3662 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3663 if ((self = [super init]) != nil) {
3664 indirect_ = [indirect retain];
3668 - (void) setDelegate:(id)delegate {
3669 delegate_ = delegate;
3672 + (NSArray *) _attributeKeys {
3673 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3676 - (NSArray *) attributeKeys {
3677 return [[self class] _attributeKeys];
3680 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3681 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3684 - (NSString *) device {
3685 return [[UIDevice currentDevice] uniqueIdentifier];
3688 #if 0 // XXX: implement!
3689 - (NSString *) mac {
3690 if (![indirect_ promptForSensitive:@"Mac Address"])
3694 - (NSString *) serial {
3695 if (![indirect_ promptForSensitive:@"Serial #"])
3699 - (NSString *) firewire {
3700 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3704 - (NSString *) imei {
3705 if (![indirect_ promptForSensitive:@"IMEI"])
3710 + (NSString *) webScriptNameForSelector:(SEL)selector {
3711 if (selector == @selector(close))
3713 else if (selector == @selector(getInstalledPackages))
3714 return @"getInstalledPackages";
3715 else if (selector == @selector(getPackageById:))
3716 return @"getPackageById";
3717 else if (selector == @selector(installPackages:))
3718 return @"installPackages";
3719 else if (selector == @selector(setAutoPopup:))
3720 return @"setAutoPopup";
3721 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3722 return @"setButtonImage";
3723 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3724 return @"setButtonTitle";
3725 else if (selector == @selector(setFinishHook:))
3726 return @"setFinishHook";
3727 else if (selector == @selector(setPopupHook:))
3728 return @"setPopupHook";
3729 else if (selector == @selector(setSpecial:))
3730 return @"setSpecial";
3731 else if (selector == @selector(setToken:))
3733 else if (selector == @selector(setViewportWidth:))
3734 return @"setViewportWidth";
3735 else if (selector == @selector(supports:))
3737 else if (selector == @selector(stringWithFormat:arguments:))
3739 else if (selector == @selector(localizedStringForKey:value:table:))
3741 else if (selector == @selector(du:))
3743 else if (selector == @selector(statfs:))
3749 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3750 return [self webScriptNameForSelector:selector] == nil;
3753 - (BOOL) supports:(NSString *)feature {
3754 return [feature isEqualToString:@"window.open"];
3757 - (NSArray *) getInstalledPackages {
3758 NSArray *packages([[Database sharedInstance] packages]);
3759 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3760 for (Package *package in packages)
3761 if ([package installed] != nil)
3762 [installed addObject:package];
3766 - (Package *) getPackageById:(NSString *)id {
3767 Package *package([[Database sharedInstance] packageWithName:id]);
3772 - (NSArray *) statfs:(NSString *)path {
3775 if (path == nil || statfs([path UTF8String], &stat) == -1)
3778 return [NSArray arrayWithObjects:
3779 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3780 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3781 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3785 - (NSNumber *) du:(NSString *)path {
3786 NSNumber *value(nil);
3789 _assert(pipe(fds) != -1);
3791 pid_t pid(ExecFork());
3793 _assert(dup2(fds[1], 1) != -1);
3794 _assert(close(fds[0]) != -1);
3795 _assert(close(fds[1]) != -1);
3796 /* XXX: this should probably not use du */
3797 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3802 _assert(close(fds[1]) != -1);
3804 if (FILE *du = fdopen(fds[0], "r")) {
3806 while (fgets(line, sizeof(line), du) != NULL) {
3807 size_t length(strlen(line));
3808 while (length != 0 && line[length - 1] == '\n')
3809 line[--length] = '\0';
3810 if (char *tab = strchr(line, '\t')) {
3812 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3817 } else _assert(close(fds[0]));
3821 if (waitpid(pid, &status, 0) == -1)
3824 else _assert(false);
3833 - (void) installPackages:(NSArray *)packages {
3834 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3837 - (void) setAutoPopup:(BOOL)popup {
3838 [indirect_ setAutoPopup:popup];
3841 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3842 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3845 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3846 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3849 - (void) setSpecial:(id)function {
3850 [indirect_ setSpecial:function];
3853 - (void) setToken:(NSString *)token {
3856 Token_ = [token retain];
3858 [Metadata_ setObject:Token_ forKey:@"Token"];
3862 - (void) setFinishHook:(id)function {
3863 [indirect_ setFinishHook:function];
3866 - (void) setPopupHook:(id)function {
3867 [indirect_ setPopupHook:function];
3870 - (void) setViewportWidth:(float)width {
3871 [indirect_ setViewportWidth:width];
3874 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3875 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3876 unsigned count([arguments count]);
3878 for (unsigned i(0); i != count; ++i)
3879 values[i] = [arguments objectAtIndex:i];
3880 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3883 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3884 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3886 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3888 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3894 /* Cydia View Controller {{{ */
3895 @interface CYViewController : UCViewController { }
3898 @implementation CYViewController
3902 @interface CYBrowserController : BrowserController {
3903 CydiaObject *cydia_;
3908 @implementation CYBrowserController
3915 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3918 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3919 [super webView:sender didClearWindowObject:window forFrame:frame];
3921 WebDataSource *source([frame dataSource]);
3922 NSURLResponse *response([source response]);
3923 NSURL *url([response URL]);
3924 NSString *scheme([url scheme]);
3926 NSHTTPURLResponse *http;
3927 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3928 http = (NSHTTPURLResponse *) response;
3932 NSDictionary *headers([http allHeaderFields]);
3933 NSString *host([url host]);
3934 [self setHeaders:headers forHost:host];
3937 [host isEqualToString:@"cydia.saurik.com"] ||
3938 [host hasSuffix:@".cydia.saurik.com"] ||
3939 [scheme isEqualToString:@"file"]
3941 [window setValue:cydia_ forKey:@"cydia"];
3944 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3945 if (System_ != NULL)
3946 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3947 if (Machine_ != NULL)
3948 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3950 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3952 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3955 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3956 NSMutableURLRequest *copy = [request mutableCopy];
3957 [self _setMoreHeaders:copy];
3961 - (void) setDelegate:(id)delegate {
3962 [super setDelegate:delegate];
3963 [cydia_ setDelegate:delegate];
3967 if ((self = [super initWithWidth:[[self view] bounds].size.width ofClass:[CYBrowserController class]]) != nil) {
3968 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3970 WebView *webview([document_ webView]);
3972 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3974 NSString *application = package == nil ? @"Cydia" : [NSString
3975 stringWithFormat:@"Cydia/%@",
3980 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3982 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3983 if (Product_ != nil)
3984 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3986 [webview setApplicationNameForUserAgent:application];
3992 @protocol ConfirmationControllerDelegate
3993 - (void) cancelAndClear:(bool)clear;
3994 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3998 @interface ConfirmationController : CYBrowserController {
3999 _transient Database *database_;
4000 UIAlertView *essential_;
4007 - (id) initWithDatabase:(Database *)database;
4011 @implementation ConfirmationController
4018 if (essential_ != nil)
4019 [essential_ release];
4023 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
4024 NSString *context([sheet context]);
4026 if ([context isEqualToString:@"cancel"]) {
4029 if (button == [sheet cancelButtonIndex]) return;
4030 else if (button == [sheet destructiveButtonIndex]) clear = true;
4033 [sheet dismissWithClickedButtonIndex:0xDEADBEEF animated:YES];
4034 [self dismissModalViewControllerAnimated:YES];
4035 [delegate_ cancelAndClear:clear];
4039 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4040 NSString *context([alert context]);
4042 if ([context isEqualToString:@"remove"]) {
4043 if (button == [alert cancelButtonIndex]) {
4044 [self dismissModalViewControllerAnimated:YES];
4045 } else if (button == [alert firstOtherButtonIndex]) {
4048 [delegate_ confirmWithNavigationController:[self navigationController]];
4051 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4052 } else if ([context isEqualToString:@"unable"]) {
4053 [self dismissModalViewControllerAnimated:YES];
4054 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4056 [super alertView:alert clickedButtonAtIndex:button];
4060 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4061 [self dismissModalViewControllerAnimated:YES];
4062 [delegate_ cancelAndClear:NO];
4067 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4068 [super webView:sender didClearWindowObject:window forFrame:frame];
4069 [window setValue:changes_ forKey:@"changes"];
4070 [window setValue:issues_ forKey:@"issues"];
4071 [window setValue:sizes_ forKey:@"sizes"];
4072 [window setValue:self forKey:@"queue"];
4075 - (id) initWithDatabase:(Database *)database {
4076 if ((self = [super init]) != nil) {
4077 database_ = database;
4079 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4081 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4082 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4083 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4084 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4085 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4089 pkgDepCache::Policy *policy([database_ policy]);
4091 pkgCacheFile &cache([database_ cache]);
4092 NSArray *packages = [database_ packages];
4093 for (Package *package in packages) {
4094 pkgCache::PkgIterator iterator = [package iterator];
4095 pkgDepCache::StateCache &state(cache[iterator]);
4097 NSString *name([package name]);
4099 if (state.NewInstall())
4100 [installing addObject:name];
4101 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4102 [reinstalling addObject:name];
4103 else if (state.Upgrade())
4104 [upgrading addObject:name];
4105 else if (state.Downgrade())
4106 [downgrading addObject:name];
4107 else if (state.Delete()) {
4108 if ([package essential])
4110 [removing addObject:name];
4113 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4114 substrate_ |= DepSubstrate(iterator.CurrentVer());
4119 else if (Advanced_) {
4120 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4122 essential_ = [[UIAlertView alloc]
4123 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4124 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4126 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4127 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4130 [essential_ setContext:@"remove"];
4132 essential_ = [[UIAlertView alloc]
4133 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4134 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4136 cancelButtonTitle:UCLocalize("OKAY")
4137 otherButtonTitles:nil
4140 [essential_ setContext:@"unable"];
4143 changes_ = [[NSArray alloc] initWithObjects:
4151 issues_ = [database_ issues];
4153 issues_ = [issues_ retain];
4155 sizes_ = [[NSArray alloc] initWithObjects:
4156 SizeString([database_ fetcher].FetchNeeded()),
4157 SizeString([database_ fetcher].PartialPresent()),
4160 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4162 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
4163 initWithTitle:UCLocalize("CANCEL")//[NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4164 style:UIBarButtonItemStylePlain
4166 action:@selector(cancelButtonClicked)
4168 [[self navigationItem] setLeftBarButtonItem:leftItem];
4173 - (void) applyRightButton {
4174 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
4175 initWithTitle:UCLocalize("CONFIRM")
4176 style:UIBarButtonItemStylePlain
4178 action:@selector(confirmButtonClicked)
4180 #if !AlwaysReload && !IgnoreInstall
4181 if (issues_ == nil && ![self isLoading]) [[self navigationItem] setRightBarButtonItem:rightItem];
4182 else [super applyRightButton];
4184 [[self navigationItem] setRightBarButtonItem:nil];
4186 [rightItem release];
4189 - (void) cancelButtonClicked {
4190 /*UIActionSheet *sheet = [[UIActionSheet alloc]
4193 cancelButtonTitle:nil
4194 destructiveButtonTitle:nil
4195 otherButtonTitles:nil
4198 [sheet addButtonWithTitle:UCLocalize("CANCEL_CLEAR")];
4199 [sheet setDestructiveButtonIndex:[sheet numberOfButtons] - 1];
4200 [sheet addButtonWithTitle:UCLocalize("CONTINUE_QUEUING")];
4201 [sheet setContext:@"cancel"];
4203 [delegate_ showActionSheet:[sheet autorelease] fromItem:[[self navigationItem] leftBarButtonItem]];*/
4204 [self dismissModalViewControllerAnimated:YES];
4205 [delegate_ cancelAndClear:YES];
4209 - (void) confirmButtonClicked {
4213 if (essential_ != nil)
4218 [delegate_ confirmWithNavigationController:[self navigationController]];
4226 /* Progress Data {{{ */
4227 @interface ProgressData : NSObject {
4233 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4240 @implementation ProgressData
4242 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4243 if ((self = [super init]) != nil) {
4244 selector_ = selector;
4264 /* Progress Controller {{{ */
4265 @interface ProgressController : CYViewController <
4266 ConfigurationDelegate,
4269 _transient Database *database_;
4270 UIProgressBar *progress_;
4271 UITextView *output_;
4272 UITextLabel *status_;
4273 UIPushButton *close_;
4275 SHA1SumValue springlist_;
4276 SHA1SumValue notifyconf_;
4280 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4282 - (void) _retachThread;
4283 - (void) _detachNewThreadData:(ProgressData *)data;
4284 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4290 @protocol ProgressControllerDelegate
4291 - (void) progressControllerIsComplete:(ProgressController *)sender;
4294 @implementation ProgressController
4297 [database_ setDelegate:nil];
4298 [progress_ release];
4307 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4308 if ((self = [super init]) != nil) {
4309 database_ = database;
4310 [database_ setDelegate:self];
4311 delegate_ = delegate;
4313 [[self view] setBackgroundColor:(CGColor *)[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4315 progress_ = [[UIProgressBar alloc] init];
4316 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4317 [progress_ setStyle:0];
4319 status_ = [[UITextLabel alloc] init];
4320 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4321 [status_ setColor:[UIColor whiteColor]];
4322 [status_ setBackgroundColor:[UIColor clearColor]];
4323 [status_ setCentersHorizontally:YES];
4324 //[status_ setFont:font];
4326 output_ = [[UITextView alloc] init];
4328 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4329 //[output_ setTextFont:@"Courier New"];
4330 [output_ setFont:[[output_ font] fontWithSize:12]];
4331 [output_ setTextColor:[UIColor whiteColor]];
4332 [output_ setBackgroundColor:[UIColor clearColor]];
4333 [output_ setMarginTop:0];
4334 [output_ setAllowsRubberBanding:YES];
4335 [output_ setEditable:NO];
4336 [[self view] addSubview:output_];
4338 close_ = [[UIPushButton alloc] init];
4339 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4340 [close_ setAutosizesToFit:NO];
4341 [close_ setDrawsShadow:YES];
4342 [close_ setStretchBackground:YES];
4343 [close_ setEnabled:YES];
4344 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4345 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4346 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4347 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4351 - (void) positionViews {
4352 CGRect bounds = [[self view] bounds];
4353 CGSize prgsize = [UIProgressBar defaultSize];
4356 (bounds.size.width - prgsize.width) / 2,
4357 bounds.size.height - prgsize.height - 64
4360 float closewidth = bounds.size.width - 20;
4361 if (closewidth > 300) closewidth = 300;
4363 [progress_ setFrame:prgrect];
4364 [status_ setFrame:CGRectMake(
4366 bounds.size.height - prgsize.height - 94,
4367 bounds.size.width - 20,
4370 [output_ setFrame:CGRectMake(
4373 bounds.size.width - 20,
4374 bounds.size.height - 106
4376 [close_ setFrame:CGRectMake(
4377 (bounds.size.width - closewidth) / 2,
4378 bounds.size.height - prgsize.height - 94,
4384 - (void) viewWillAppear:(BOOL)animated {
4385 [super viewDidAppear:animated];
4386 [[self navigationItem] setHidesBackButton:YES];
4387 [[[self navigationController] navigationBar] setBarStyle:1];
4389 [self positionViews];
4392 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4393 [self positionViews];
4396 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4397 NSString *context([alert context]);
4399 if ([context isEqualToString:@"conffile"]) {
4400 FILE *input = [database_ input];
4401 if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
4402 else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
4407 - (void) closeButtonPushed {
4412 [self dismissModalViewControllerAnimated:YES];
4416 [delegate_ terminateWithSuccess];
4417 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4418 [delegate_ suspendWithAnimation:YES];
4420 [delegate_ suspend];*/
4424 system("launchctl stop com.apple.SpringBoard");
4428 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4437 - (void) _retachThread {
4438 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4440 [[self view] addSubview:close_];
4441 [progress_ removeFromSuperview];
4442 [status_ removeFromSuperview];
4444 [database_ popErrorWithTitle:title_];
4445 [delegate_ progressControllerIsComplete:self];
4449 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4452 MMap mmap(file, MMap::ReadOnly);
4454 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4455 if (!(notifyconf_ == sha1.Result()))
4462 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4465 MMap mmap(file, MMap::ReadOnly);
4467 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4468 if (!(springlist_ == sha1.Result()))
4474 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4475 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4476 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4477 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4478 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4481 system("su -c /usr/bin/uicache mobile");
4483 [delegate_ setStatusBarShowsProgress:NO];
4486 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4487 [[data target] performSelector:[data selector] withObject:[data object]];
4490 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4493 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4499 title_ = [title retain];
4501 [[self navigationItem] setTitle:title_];
4503 [status_ setText:nil];
4504 [output_ setText:@""];
4505 [progress_ setProgress:0];
4507 [close_ removeFromSuperview];
4508 [[self view] addSubview:progress_];
4509 [[self view] addSubview:status_];
4511 [delegate_ setStatusBarShowsProgress:YES];
4516 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4519 MMap mmap(file, MMap::ReadOnly);
4521 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4522 notifyconf_ = sha1.Result();
4528 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4531 MMap mmap(file, MMap::ReadOnly);
4533 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4534 springlist_ = sha1.Result();
4539 detachNewThreadSelector:@selector(_detachNewThreadData:)
4541 withObject:[[ProgressData alloc]
4542 initWithSelector:selector
4549 - (void) repairWithSelector:(SEL)selector {
4551 detachNewThreadSelector:selector
4554 title:UCLocalize("REPAIRING")
4558 - (void) setConfigurationData:(NSString *)data {
4560 performSelectorOnMainThread:@selector(_setConfigurationData:)
4566 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4567 CYActionSheet *sheet([[[CYActionSheet alloc]
4569 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4570 defaultButtonIndex:0
4573 [sheet setMessage:error];
4574 [sheet yieldToPopupAlertAnimated:YES];
4578 - (void) setProgressTitle:(NSString *)title {
4580 performSelectorOnMainThread:@selector(_setProgressTitle:)
4586 - (void) setProgressPercent:(float)percent {
4588 performSelectorOnMainThread:@selector(_setProgressPercent:)
4589 withObject:[NSNumber numberWithFloat:percent]
4594 - (void) startProgress {
4597 - (void) addProgressOutput:(NSString *)output {
4599 performSelectorOnMainThread:@selector(_addProgressOutput:)
4605 - (bool) isCancelling:(size_t)received {
4609 - (void) _setConfigurationData:(NSString *)data {
4610 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4612 if (!conffile_r(data)) {
4613 lprintf("E:invalid conffile\n");
4617 NSString *ofile = conffile_r[1];
4618 //NSString *nfile = conffile_r[2];
4620 UIAlertView *alert = [[[UIAlertView alloc]
4621 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4622 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4624 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4625 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4626 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4630 [alert setContext:@"conffile"];
4634 - (void) _setProgressTitle:(NSString *)title {
4635 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4636 for (size_t i(0), e([words count]); i != e; ++i) {
4637 NSString *word([words objectAtIndex:i]);
4638 if (Package *package = [database_ packageWithName:word])
4639 [words replaceObjectAtIndex:i withObject:[package name]];
4642 [status_ setText:[words componentsJoinedByString:@" "]];
4645 - (void) _setProgressPercent:(NSNumber *)percent {
4646 [progress_ setProgress:[percent floatValue]];
4649 - (void) _addProgressOutput:(NSString *)output {
4650 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4651 CGSize size = [output_ contentSize];
4652 CGRect rect = {{0, size.height}, {size.width, 0}};
4653 [output_ scrollRectToVisible:rect animated:YES];
4656 - (BOOL) isRunning {
4663 /* Cell Content View {{{ */
4664 @interface ContentView : UIView {
4665 _transient id delegate_;
4670 @implementation ContentView
4671 - (id) initWithFrame:(CGRect)frame {
4672 if ((self = [super initWithFrame:frame]) != nil) {
4673 /* Fix landscape stretching. */
4674 [self setNeedsDisplayOnBoundsChange:YES];
4678 - (void) setDelegate:(id)delegate {
4679 delegate_ = delegate;
4682 - (void) drawRect:(CGRect)rect {
4683 [super drawRect:rect];
4684 [delegate_ drawContentRect:rect];
4688 /* Package Cell {{{ */
4689 @interface PackageCell : UITableViewCell {
4692 NSString *description_;
4698 ContentView *content_;
4704 - (PackageCell *) init;
4705 - (void) setPackage:(Package *)package;
4707 + (int) heightForPackage:(Package *)package;
4708 - (void) drawContentRect:(CGRect)rect;
4712 @implementation PackageCell
4714 - (void) clearPackage {
4725 if (description_ != nil) {
4726 [description_ release];
4730 if (source_ != nil) {
4735 if (badge_ != nil) {
4740 if (placard_ != nil) {
4750 [self clearPackage];
4757 return faded_ ? [self selectionPercent] : fade_;
4760 - (PackageCell *) init {
4761 CGRect frame(CGRectMake(0, 0, 320, 74));
4762 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4763 UIView *content([self contentView]);
4764 CGRect bounds([content bounds]);
4766 content_ = [[ContentView alloc] initWithFrame:bounds];
4767 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4768 [content addSubview:content_];
4770 [content_ setDelegate:self];
4771 [content_ setOpaque:YES];
4772 if ([self respondsToSelector:@selector(selectionPercent)])
4777 - (void) _setBackgroundColor {
4779 if (NSString *mode = [package_ mode]) {
4780 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4781 color = remove ? RemovingColor_ : InstallingColor_;
4783 color = [UIColor whiteColor];
4785 [content_ setBackgroundColor:color];
4786 [self setNeedsDisplay];
4789 - (void) setPackage:(Package *)package {
4790 [self clearPackage];
4793 Source *source = [package source];
4795 icon_ = [[package icon] retain];
4796 name_ = [[package name] retain];
4799 description_ = [package longDescription];
4800 if (description_ == nil)
4801 description_ = [package shortDescription];
4802 if (description_ != nil)
4803 description_ = [description_ retain];
4805 commercial_ = [package isCommercial];
4807 package_ = [package retain];
4809 NSString *label = nil;
4810 bool trusted = false;
4812 if (source != nil) {
4813 label = [source label];
4814 trusted = [source trusted];
4815 } else if ([[package id] isEqualToString:@"firmware"])
4816 label = UCLocalize("APPLE");
4818 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4820 NSString *from(label);
4822 NSString *section = [package simpleSection];
4823 if (section != nil && ![section isEqualToString:label]) {
4824 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4825 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4828 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4829 source_ = [from retain];
4831 if (NSString *purpose = [package primaryPurpose])
4832 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4833 badge_ = [badge_ retain];
4835 if ([package installed] != nil)
4836 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4837 placard_ = [placard_ retain];
4839 [self _setBackgroundColor];
4840 [content_ setNeedsDisplay];
4843 - (void) drawContentRect:(CGRect)rect {
4844 bool selected([self isSelected]);
4845 float width([self bounds].size.width);
4848 CGContextRef context(UIGraphicsGetCurrentContext());
4849 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4850 CGContextFillRect(context, rect);
4855 rect.size = [icon_ size];
4857 rect.size.width /= 2;
4858 rect.size.height /= 2;
4860 rect.origin.x = 25 - rect.size.width / 2;
4861 rect.origin.y = 25 - rect.size.height / 2;
4863 [icon_ drawInRect:rect];
4866 if (badge_ != nil) {
4867 CGSize size = [badge_ size];
4869 [badge_ drawAtPoint:CGPointMake(
4870 36 - size.width / 2,
4871 36 - size.height / 2
4879 UISetColor(commercial_ ? Purple_ : Black_);
4880 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ ellipsis:2];
4881 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ ellipsis:2];
4884 UISetColor(commercial_ ? Purplish_ : Gray_);
4885 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ ellipsis:2];
4887 if (placard_ != nil)
4888 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4891 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4892 //[self _setBackgroundColor];
4893 [super setSelected:selected animated:fade];
4894 [content_ setNeedsDisplay];
4897 + (int) heightForPackage:(Package *)package {
4903 /* Section Cell {{{ */
4904 @interface SectionCell : UITableViewCell {
4910 ContentView *content_;
4916 - (void) setSection:(Section *)section editing:(BOOL)editing;
4920 @implementation SectionCell
4922 - (void) clearSection {
4923 if (basic_ != nil) {
4928 if (section_ != nil) {
4938 if (count_ != nil) {
4945 [self clearSection];
4953 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4954 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4955 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4956 switch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4957 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4959 UIView *content([self contentView]);
4960 CGRect bounds([content bounds]);
4962 content_ = [[ContentView alloc] initWithFrame:bounds];
4963 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4964 [content addSubview:content_];
4965 [content_ setBackgroundColor:[UIColor whiteColor]];
4967 [content_ setDelegate:self];
4971 - (void) onSwitch:(id)sender {
4972 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4973 if (metadata == nil) {
4974 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4975 [Sections_ setObject:metadata forKey:basic_];
4979 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4982 - (void) setSection:(Section *)section editing:(BOOL)editing {
4983 if (editing != editing_) {
4985 [switch_ removeFromSuperview];
4987 [self addSubview:switch_];
4991 [self clearSection];
4993 if (section == nil) {
4994 name_ = [UCLocalize("ALL_PACKAGES") retain];
4997 basic_ = [section name];
4999 basic_ = [basic_ retain];
5001 section_ = [section localized];
5002 if (section_ != nil)
5003 section_ = [section_ retain];
5005 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5006 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5009 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5012 [self setAccessoryType:editing ? 0 : 1 /*UITableViewCellAccessoryDisclosureIndicator*/];
5013 [content_ setNeedsDisplay];
5016 - (void) setFrame:(CGRect)frame {
5017 [super setFrame:frame];
5019 CGRect rect([switch_ frame]);
5020 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5023 - (void) drawContentRect:(CGRect)rect {
5024 BOOL selected = [self isSelected];
5026 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5034 float width(rect.size.width);
5038 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ ellipsis:2];
5040 CGSize size = [count_ sizeWithFont:Font14_];
5044 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5050 /* File Table {{{ */
5051 @interface FileTable : CYViewController {
5052 _transient Database *database_;
5055 NSMutableArray *files_;
5059 - (id) initWithDatabase:(Database *)database;
5060 - (void) setPackage:(Package *)package;
5064 @implementation FileTable
5067 if (package_ != nil)
5076 - (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
5077 return files_ == nil ? 0 : [files_ count];
5080 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5084 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5085 static NSString *reuseIdentifier = @"Cell";
5087 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5089 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5090 [cell setFont:[UIFont systemFontOfSize:16]];
5092 [cell setText:[files_ objectAtIndex:indexPath.row]];
5093 [cell setSelectionStyle:0 /*UITableViewCellSelectionStyleNone*/];
5098 - (id) initWithDatabase:(Database *)database {
5099 if ((self = [super init]) != nil) {
5100 database_ = database;
5102 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5104 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5106 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5107 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5108 [list_ setRowHeight:24.0f];
5109 [[self view] addSubview:list_];
5111 [list_ setDataSource:self];
5112 [list_ setDelegate:self];
5116 - (void) setPackage:(Package *)package {
5117 if (package_ != nil) {
5118 [package_ autorelease];
5127 [files_ removeAllObjects];
5129 if (package != nil) {
5130 package_ = [package retain];
5131 name_ = [[package id] retain];
5133 if (NSArray *files = [package files])
5134 [files_ addObjectsFromArray:files];
5136 if ([files_ count] != 0) {
5137 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5138 [files_ removeObjectAtIndex:0];
5139 [files_ sortUsingSelector:@selector(compareByPath:)];
5141 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5142 [stack addObject:@"/"];
5144 for (int i(0), e([files_ count]); i != e; ++i) {
5145 NSString *file = [files_ objectAtIndex:i];
5146 while (![file hasPrefix:[stack lastObject]])
5147 [stack removeLastObject];
5148 NSString *directory = [stack lastObject];
5149 [stack addObject:[file stringByAppendingString:@"/"]];
5150 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5151 ([stack count] - 2) * 3, "",
5152 [file substringFromIndex:[directory length]]
5161 - (void) reloadData {
5162 [self setPackage:[database_ packageWithName:name_]];
5167 /* Package Controller {{{ */
5168 @interface PackageController : CYBrowserController {
5169 _transient Database *database_;
5173 NSMutableArray *buttons_;
5176 - (id) initWithDatabase:(Database *)database;
5177 - (void) setPackage:(Package *)package;
5181 @implementation PackageController
5184 if (package_ != nil)
5193 if ([self retainCount] == 1)
5194 [delegate_ setPackageController:self];
5198 /* XXX: this is not safe at all... localization of /fail/ */
5199 - (void) _clickButtonWithName:(NSString *)name {
5200 if ([name isEqualToString:UCLocalize("CLEAR")])
5201 [delegate_ clearPackage:package_];
5202 else if ([name isEqualToString:UCLocalize("INSTALL")])
5203 [delegate_ installPackage:package_];
5204 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5205 [delegate_ installPackage:package_];
5206 else if ([name isEqualToString:UCLocalize("REMOVE")])
5207 [delegate_ removePackage:package_];
5208 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5209 [delegate_ installPackage:package_];
5210 else _assert(false);
5213 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5214 NSString *context([sheet context]);
5216 if ([context isEqualToString:@"modify"]) {
5217 if (button != [sheet cancelButtonIndex]) {
5218 NSString *buttonName = [buttons_ objectAtIndex:button];
5219 [self _clickButtonWithName:buttonName];
5222 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5224 [super alertSheet:sheet clickedButtonAtIndex:button];
5228 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
5229 return [super webView:sender didFinishLoadForFrame:frame];
5232 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5233 [super webView:sender didClearWindowObject:window forFrame:frame];
5234 [window setValue:package_ forKey:@"package"];
5237 - (bool) _allowJavaScriptPanel {
5242 - (void) _actionButtonClicked {
5243 int count([buttons_ count]);
5248 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5250 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5251 [buttons addObjectsFromArray:buttons_];
5253 UIActionSheet *sheet = [[[UIActionSheet alloc]
5256 cancelButtonTitle:nil
5257 destructiveButtonTitle:nil
5258 otherButtonTitles:nil
5261 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5263 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5264 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5266 [sheet setContext:@"modify"];
5268 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5272 - (void) actionButtonClicked {
5273 // Wait until it's done loading.
5274 if (![self isLoading])
5275 [self _actionButtonClicked];
5278 - (void) reloadButtonClicked {
5279 // Don't reload a package view by clicking the button.
5282 - (void) applyLoadingTitle {
5283 // Don't show "Loading" as the title. Ever.
5287 - (id) initWithDatabase:(Database *)database {
5288 if ((self = [super init]) != nil) {
5289 database_ = database;
5290 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5291 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5295 - (void) setPackage:(Package *)package {
5296 if (package_ != nil) {
5297 [package_ autorelease];
5306 [buttons_ removeAllObjects];
5308 if (package != nil) {
5311 package_ = [package retain];
5312 name_ = [[package id] retain];
5313 commercial_ = [package isCommercial];
5315 if ([package_ mode] != nil)
5316 [buttons_ addObject:UCLocalize("CLEAR")];
5317 if ([package_ source] == nil);
5318 else if ([package_ upgradableAndEssential:NO])
5319 [buttons_ addObject:UCLocalize("UPGRADE")];
5320 else if ([package_ uninstalled])
5321 [buttons_ addObject:UCLocalize("INSTALL")];
5323 [buttons_ addObject:UCLocalize("REINSTALL")];
5324 if (![package_ uninstalled])
5325 [buttons_ addObject:UCLocalize("REMOVE")];
5327 if (special_ != NULL) {
5328 CGRect frame([document_ frame]);
5329 frame.size.height = 0;
5330 [document_ setFrame:frame];
5332 if ([scroller_ respondsToSelector:@selector(scrollPointVisibleAtTopLeft:)])
5333 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5335 [scroller_ scrollRectToVisible:CGRectZero animated:NO];
5338 [[[document_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5340 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5342 [self setFinishHook:nil];
5343 [self setPopupHook:nil];
5346 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5347 [super callFunction:special_];
5352 - (void) applyRightButton {
5353 int count = [buttons_ count];
5354 UIBarButtonItem *actionItem = [[UIBarButtonItem alloc]
5355 initWithTitle:count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0]
5356 style:UIBarButtonItemStylePlain
5358 action:@selector(actionButtonClicked)
5360 if (![self isLoading]) [[self navigationItem] setRightBarButtonItem:actionItem];
5361 else [super applyRightButton];
5362 [actionItem release];
5365 - (bool) isLoading {
5366 return commercial_ ? [super isLoading] : false;
5369 - (void) reloadData {
5370 [self setPackage:[database_ packageWithName:name_]];
5375 /* Package Table {{{ */
5376 @interface PackageTable : UIView {
5377 _transient Database *database_;
5378 NSMutableArray *packages_;
5379 NSMutableArray *sections_;
5381 NSMutableArray *index_;
5382 NSMutableDictionary *indices_;
5388 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5390 - (void) setDelegate:(id)delegate;
5392 - (void) reloadData;
5393 - (void) resetCursor;
5395 - (UITableView *) list;
5397 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5399 - (void) deselectWithAnimation:(BOOL)animated;
5403 @implementation PackageTable
5406 [packages_ release];
5407 [sections_ release];
5415 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5416 NSInteger count([sections_ count]);
5417 return count == 0 ? 1 : count;
5420 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5421 if ([sections_ count] == 0)
5423 return [[sections_ objectAtIndex:section] name];
5426 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5427 if ([sections_ count] == 0)
5429 return [[sections_ objectAtIndex:section] count];
5432 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5433 Section *section([sections_ objectAtIndex:[path section]]);
5434 NSInteger row([path row]);
5435 Package *package([packages_ objectAtIndex:([section row] + row)]);
5439 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5440 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
5442 cell = [[[PackageCell alloc] init] autorelease];
5443 [cell setPackage:[self packageAtIndexPath:path]];
5447 - (void) deselectWithAnimation:(BOOL)animated {
5448 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5451 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5452 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5455 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5456 Package *package([self packageAtIndexPath:path]);
5457 package = [database_ packageWithName:[package id]];
5458 [target_ performSelector:action_ withObject:package];
5462 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5463 return [packages_ count] > 20 ? index_ : nil;
5466 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5470 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5471 if ((self = [super initWithFrame:frame]) != nil) {
5472 database_ = database;
5477 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5478 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5480 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5481 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5483 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5484 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5485 [list_ setRowHeight:73.0f];
5486 [self addSubview:list_];
5488 [list_ setDataSource:self];
5489 [list_ setDelegate:self];
5493 - (void) setDelegate:(id)delegate {
5494 delegate_ = delegate;
5497 - (bool) hasPackage:(Package *)package {
5501 - (void) reloadData {
5502 NSArray *packages = [database_ packages];
5504 [packages_ removeAllObjects];
5505 [sections_ removeAllObjects];
5507 _profile(PackageTable$reloadData$Filter)
5508 for (Package *package in packages)
5509 if ([self hasPackage:package])
5510 [packages_ addObject:package];
5513 [index_ removeAllObjects];
5514 [indices_ removeAllObjects];
5516 Section *section = nil;
5518 _profile(PackageTable$reloadData$Section)
5519 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5523 _profile(PackageTable$reloadData$Section$Package)
5524 package = [packages_ objectAtIndex:offset];
5525 index = [package index];
5528 if (section == nil || [section index] != index) {
5529 _profile(PackageTable$reloadData$Section$Allocate)
5530 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5533 [index_ addObject:[section name]];
5534 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5536 _profile(PackageTable$reloadData$Section$Add)
5537 [sections_ addObject:section];
5541 [section addToCount];
5545 _profile(PackageTable$reloadData$List)
5550 - (void) resetCursor {
5551 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5554 - (UITableView *) list {
5558 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5559 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5564 /* Filtered Package Table {{{ */
5565 @interface FilteredPackageTable : PackageTable {
5571 - (void) setObject:(id)object;
5572 - (void) setObject:(id)object forFilter:(SEL)filter;
5574 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5578 @implementation FilteredPackageTable
5586 - (void) setFilter:(SEL)filter {
5589 /* XXX: this is an unsafe optimization of doomy hell */
5590 Method method(class_getInstanceMethod([Package class], filter));
5591 _assert(method != NULL);
5592 imp_ = method_getImplementation(method);
5593 _assert(imp_ != NULL);
5596 - (void) setObject:(id)object {
5602 object_ = [object retain];
5605 - (void) setObject:(id)object forFilter:(SEL)filter {
5606 [self setFilter:filter];
5607 [self setObject:object];
5610 - (bool) hasPackage:(Package *)package {
5611 _profile(FilteredPackageTable$hasPackage)
5612 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5616 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5617 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5618 [self setFilter:filter];
5619 object_ = [object retain];
5627 /* Filtered Package Controller {{{ */
5628 @interface FilteredPackageController : CYViewController {
5629 _transient Database *database_;
5630 FilteredPackageTable *packages_;
5634 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5638 @implementation FilteredPackageController
5641 [packages_ release];
5647 - (void) viewDidAppear:(BOOL)animated {
5648 [super viewDidAppear:animated];
5649 [packages_ deselectWithAnimation:animated];
5652 - (void) didSelectPackage:(Package *)package {
5653 PackageController *view([delegate_ packageController]);
5654 [view setPackage:package];
5655 [view setDelegate:delegate_];
5656 [[self navigationController] pushViewController:view animated:YES];
5659 - (id) title { return title_; }
5661 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5662 if ((self = [super init]) != nil) {
5663 database_ = database;
5664 title_ = [title copy];
5665 [[self navigationItem] setTitle:title_];
5667 packages_ = [[FilteredPackageTable alloc]
5668 initWithFrame:[[self view] bounds]
5671 action:@selector(didSelectPackage:)
5676 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5677 [[self view] addSubview:packages_];
5681 - (void) reloadData {
5682 [packages_ reloadData];
5685 - (void) setDelegate:(id)delegate {
5686 [super setDelegate:delegate];
5687 [packages_ setDelegate:delegate];
5694 /* Add Source Controller {{{ */
5695 @interface AddSourceController : CYViewController {
5696 _transient Database *database_;
5699 - (id) initWithDatabase:(Database *)database;
5703 @implementation AddSourceController
5705 - (id) initWithDatabase:(Database *)database {
5706 if ((self = [super init]) != nil) {
5707 database_ = database;
5713 /* Source Cell {{{ */
5714 @interface SourceCell : UITableViewCell {
5717 NSString *description_;
5719 ContentView *content_;
5722 - (void) setSource:(Source *)source;
5726 @implementation SourceCell
5728 - (void) clearSource {
5731 [description_ release];
5740 - (void) setSource:(Source *)source {
5744 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5746 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5747 icon_ = [icon_ retain];
5749 origin_ = [[source name] retain];
5750 label_ = [[source uri] retain];
5751 description_ = [[source description] retain];
5753 [content_ setNeedsDisplay];
5762 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5763 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5764 UIView *content([self contentView]);
5765 CGRect bounds([content bounds]);
5767 content_ = [[ContentView alloc] initWithFrame:bounds];
5768 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5769 [content_ setBackgroundColor:[UIColor whiteColor]];
5770 [content addSubview:content_];
5772 [content_ setDelegate:self];
5773 [content_ setOpaque:YES];
5777 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5778 [super setSelected:selected animated:animated];
5779 [content_ setNeedsDisplay];
5782 - (void) drawContentRect:(CGRect)rect {
5783 bool selected([self isSelected]);
5784 float width(rect.size.width);
5787 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5794 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ ellipsis:2];
5798 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ ellipsis:2];
5802 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ ellipsis:2];
5807 /* Source Table {{{ */
5808 @interface SourceTable : CYViewController {
5809 _transient Database *database_;
5811 NSMutableArray *sources_;
5815 UIProgressHUD *hud_;
5818 //NSURLConnection *installer_;
5819 NSURLConnection *trivial_;
5820 NSURLConnection *trivial_bz2_;
5821 NSURLConnection *trivial_gz_;
5822 //NSURLConnection *automatic_;
5827 - (id) initWithDatabase:(Database *)database;
5831 @implementation SourceTable
5833 - (void) _deallocConnection:(NSURLConnection *)connection {
5834 if (connection != nil) {
5835 [connection cancel];
5836 //[connection setDelegate:nil];
5837 [connection release];
5849 //[self _deallocConnection:installer_];
5850 [self _deallocConnection:trivial_];
5851 [self _deallocConnection:trivial_gz_];
5852 [self _deallocConnection:trivial_bz2_];
5853 //[self _deallocConnection:automatic_];
5860 - (void) viewDidAppear:(BOOL)animated {
5861 [super viewDidAppear:animated];
5862 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5865 - (int) numberOfSectionsInTableView:(UITableView *)tableView {
5866 return offset_ == 0 ? 1 : 2;
5869 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(int)section {
5870 switch (section + (offset_ == 0 ? 1 : 0)) {
5871 case 0: return UCLocalize("ENTERED_BY_USER");
5872 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5878 - (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
5879 int count = [sources_ count];
5881 case 0: return (offset_ == 0 ? count : offset_);
5882 case 1: return count - offset_;
5888 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5890 switch (indexPath.section) {
5891 case 0: idx = indexPath.row; break;
5892 case 1: idx = indexPath.row + offset_; break;
5896 return [sources_ objectAtIndex:idx];
5899 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5900 Source *source = [self sourceAtIndexPath:indexPath];
5901 return [source description] == nil ? 56 : 73;
5904 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5905 static NSString *cellIdentifier = @"SourceCell";
5907 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5908 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5909 [cell setSource:[self sourceAtIndexPath:indexPath]];
5914 - (int) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5915 return 1; //UITableViewCellAccessoryDisclosureIndicator?
5918 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5919 Source *source = [self sourceAtIndexPath:indexPath];
5921 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5922 initWithDatabase:database_
5923 title:[source label]
5924 filter:@selector(isVisibleInSource:)
5928 [packages setDelegate:delegate_];
5930 [[self navigationController] pushViewController:packages animated:YES];
5933 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5934 Source *source = [self sourceAtIndexPath:indexPath];
5935 return [source record] != nil;
5938 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5939 Source *source = [self sourceAtIndexPath:indexPath];
5940 [Sources_ removeObjectForKey:[source key]];
5941 [delegate_ syncData];
5945 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5948 @"./", @"Distribution",
5949 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5951 [delegate_ syncData];
5954 - (NSString *) getWarning {
5955 NSString *href(href_);
5956 NSRange colon([href rangeOfString:@"://"]);
5957 if (colon.location != NSNotFound)
5958 href = [href substringFromIndex:(colon.location + 3)];
5959 href = [href stringByAddingPercentEscapes];
5960 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5961 href = [href stringByCachingURLWithCurrentCDN];
5963 NSURL *url([NSURL URLWithString:href]);
5965 NSStringEncoding encoding;
5966 NSError *error(nil);
5968 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5969 return [warning length] == 0 ? nil : warning;
5973 - (void) _endConnection:(NSURLConnection *)connection {
5974 NSURLConnection **field = NULL;
5975 if (connection == trivial_)
5977 else if (connection == trivial_bz2_)
5978 field = &trivial_bz2_;
5979 else if (connection == trivial_gz_)
5980 field = &trivial_gz_;
5981 _assert(field != NULL);
5982 [connection release];
5987 trivial_bz2_ == nil &&
5993 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5996 UIAlertView *alert = [[[UIAlertView alloc]
5997 initWithTitle:UCLocalize("SOURCE_WARNING")
6000 cancelButtonTitle:UCLocalize("CANCEL")
6001 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
6004 [alert setContext:@"warning"];
6005 [alert setNumberOfRows:1];
6009 } else if (error_ != nil) {
6010 UIAlertView *alert = [[[UIAlertView alloc]
6011 initWithTitle:UCLocalize("VERIFICATION_ERROR")
6012 message:[error_ localizedDescription]
6014 cancelButtonTitle:UCLocalize("OK")
6015 otherButtonTitles:nil
6018 [alert setContext:@"urlerror"];
6021 UIAlertView *alert = [[[UIAlertView alloc]
6022 initWithTitle:UCLocalize("NOT_REPOSITORY")
6023 message:UCLocalize("NOT_REPOSITORY_EX")
6025 cancelButtonTitle:UCLocalize("OK")
6026 otherButtonTitles:nil
6029 [alert setContext:@"trivial"];
6033 [delegate_ setStatusBarShowsProgress:NO];
6034 [delegate_ removeProgressHUD:hud_];
6044 if (error_ != nil) {
6051 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6052 switch ([response statusCode]) {
6058 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6059 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6061 error_ = [error retain];
6062 [self _endConnection:connection];
6065 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6066 [self _endConnection:connection];
6069 - (id)title { return UCLocalize("SOURCES"); }
6071 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6072 NSMutableURLRequest *request = [NSMutableURLRequest
6073 requestWithURL:[NSURL URLWithString:href]
6074 cachePolicy:NSURLRequestUseProtocolCachePolicy
6075 timeoutInterval:120.0
6078 [request setHTTPMethod:method];
6080 if (Machine_ != NULL)
6081 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6082 if (UniqueID_ != nil)
6083 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6085 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6087 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6090 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6091 NSString *context([alert context]);
6093 if ([context isEqualToString:@"source"]) {
6096 NSString *href = [[alert textField] text];
6098 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6100 if (![href hasSuffix:@"/"])
6101 href_ = [href stringByAppendingString:@"/"];
6104 href_ = [href_ retain];
6106 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6107 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6108 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6109 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6113 hud_ = [[delegate_ addProgressHUD] retain];
6114 [hud_ setText:UCLocalize("VERIFYING_URL")];
6123 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6124 } else if ([context isEqualToString:@"trivial"])
6125 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6126 else if ([context isEqualToString:@"urlerror"])
6127 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6128 else if ([context isEqualToString:@"warning"]) {
6143 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6147 - (id) initWithDatabase:(Database *)database {
6148 if ((self = [super init]) != nil) {
6149 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6150 [self updateButtonsForEditingStatus:NO animated:NO];
6152 database_ = database;
6153 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6155 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6156 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6157 [[self view] addSubview:list_];
6159 [list_ setDataSource:self];
6160 [list_ setDelegate:self];
6166 - (void) reloadData {
6168 if (!list.ReadMainList())
6171 [sources_ removeAllObjects];
6172 [sources_ addObjectsFromArray:[database_ sources]];
6174 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6177 int count([sources_ count]);
6179 for (int i = 0; i != count; i++) {
6180 if ([[sources_ objectAtIndex:i] record] == nil) break;
6184 [list_ setEditing:NO];
6185 [self updateButtonsForEditingStatus:NO animated:NO];
6189 - (void) addButtonClicked {
6190 /*[book_ pushPage:[[[AddSourceController alloc]
6195 UIAlertView *alert = [[[UIAlertView alloc]
6196 initWithTitle:UCLocalize("ENTER_APT_URL")
6199 cancelButtonTitle:UCLocalize("CANCEL")
6200 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6203 [alert setContext:@"source"];
6204 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6206 [alert setNumberOfRows:1];
6207 [alert addTextFieldWithValue:@"http://" label:@""];
6209 UITextInputTraits *traits = [[alert textField] textInputTraits];
6210 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6211 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6212 [traits setKeyboardType:UIKeyboardTypeURL];
6213 // XXX: UIReturnKeyDone
6214 [traits setReturnKeyType:UIReturnKeyNext];
6219 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6220 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
6221 initWithTitle:UCLocalize("ADD")
6222 style:UIBarButtonItemStylePlain
6224 action:@selector(addButtonClicked)
6226 [[self navigationItem] setLeftBarButtonItem:editing ? leftItem : [[self navigationItem] backBarButtonItem] animated:animated];
6229 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6230 initWithTitle:editing ? UCLocalize("DONE") : UCLocalize("EDIT")
6231 style:editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6233 action:@selector(editButtonClicked)
6235 [[self navigationItem] setRightBarButtonItem:rightItem animated:animated];
6236 [rightItem release];
6239 - (void) editButtonClicked {
6240 [list_ setEditing:![list_ isEditing] animated:YES];
6242 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6248 /* Installed Controller {{{ */
6249 @interface InstalledController : FilteredPackageController {
6253 - (id) initWithDatabase:(Database *)database;
6257 @implementation InstalledController
6263 - (id) title { return UCLocalize("INSTALLED"); }
6265 - (id) initWithDatabase:(Database *)database {
6266 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6267 [self updateRoleButton];
6268 [self queueStatusDidChange];
6273 - (void) queueButtonClicked {
6278 - (void) queueStatusDidChange {
6281 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6282 initWithTitle:UCLocalize("QUEUE")
6283 style:UIBarButtonItemStyleDone
6285 action:@selector(queueButtonClicked)
6287 if (Queuing_) [[self navigationItem] setLeftBarButtonItem:queueItem];
6288 else [[self navigationItem] setLeftBarButtonItem:nil];
6289 [queueItem release];
6294 - (void) reloadData {
6295 [packages_ reloadData];
6298 - (void) updateRoleButton {
6299 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6300 initWithTitle:expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")
6301 style:expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6303 action:@selector(roleButtonClicked)
6305 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) [[self navigationItem] setRightBarButtonItem:rightItem];
6306 [rightItem release];
6309 - (void) roleButtonClicked {
6310 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6311 [packages_ reloadData];
6314 [self updateRoleButton];
6317 - (void) setDelegate:(id)delegate {
6318 [super setDelegate:delegate];
6319 [packages_ setDelegate:delegate];
6325 /* Home Controller {{{ */
6326 @interface HomeController : CYBrowserController {
6331 @implementation HomeController
6333 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6334 [super _setMoreHeaders:request];
6336 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6337 if (UniqueID_ != nil)
6338 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6341 - (void) aboutButtonClicked {
6342 UIAlertView *alert = [[[UIAlertView alloc] init] autorelease];
6343 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6344 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6345 [alert setCancelButtonIndex:0];
6348 @"Copyright (C) 2008-2010\n"
6349 "Jay Freeman (saurik)\n"
6350 "saurik@saurik.com\n"
6351 "http://www.saurik.com/"
6357 - (void) viewWillAppear:(BOOL)animated {
6358 [super viewWillAppear:animated];
6359 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6362 - (void) viewWillDisappear:(BOOL)animated {
6363 [super viewWillDisappear:animated];
6364 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6368 if ((self = [super init]) != nil) {
6369 UIBarButtonItem *aboutItem = [[UIBarButtonItem alloc]
6370 initWithTitle:UCLocalize("ABOUT")
6371 style:UIBarButtonItemStylePlain
6373 action:@selector(aboutButtonClicked)
6375 [[self navigationItem] setLeftBarButtonItem:aboutItem];
6376 [aboutItem release];
6382 /* Manage Controller {{{ */
6383 @interface ManageController : CYBrowserController {
6388 @implementation ManageController
6391 if ((self = [super init]) != nil) {
6392 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6394 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6395 initWithTitle:UCLocalize("SETTINGS")
6396 style:UIBarButtonItemStylePlain
6398 action:@selector(settingsButtonClicked)
6400 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6401 [settingsItem release];
6403 [self queueStatusDidChange];
6407 - (void) settingsButtonClicked {
6408 [delegate_ askForSettings];
6409 [delegate_ updateData];
6413 - (void) queueButtonClicked {
6417 - (void) applyLoadingTitle {
6418 // No "Loading" title.
6421 - (void) applyRightButton {
6426 - (void) queueStatusDidChange {
6428 if (!IsWildcat_ && Queuing_) {
6429 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6430 initWithTitle:UCLocalize("QUEUE")
6431 style:UIBarButtonItemStyleDone
6433 action:@selector(queueButtonClicked)
6435 [[self navigationItem] setRightBarButtonItem:queueItem];
6437 [queueItem release];
6439 [[self navigationItem] setRightBarButtonItem:nil];
6444 - (bool) isLoading {
6451 /* Refresh Bar {{{ */
6452 @interface RefreshBar : UINavigationBar {
6453 UIProgressIndicator *indicator_;
6454 UITextLabel *prompt_;
6455 UIProgressBar *progress_;
6456 UINavigationButton *cancel_;
6461 @implementation RefreshBar
6463 - (void) positionViews {
6464 CGRect frame = [cancel_ frame];
6465 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6466 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6467 [cancel_ setFrame:frame];
6469 CGSize prgsize = {75, 100};
6471 [self frame].size.width - prgsize.width - 10,
6472 ([self frame].size.height - prgsize.height) / 2
6474 [progress_ setFrame:prgrect];
6476 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6477 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6478 CGRect indrect = {{indoffset, indoffset}, indsize};
6479 [indicator_ setFrame:indrect];
6481 CGSize prmsize = {215, indsize.height + 4};
6483 indoffset * 2 + indsize.width,
6484 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6486 [prompt_ setFrame:prmrect];
6489 - (void)setFrame:(CGRect)frame {
6490 [super setFrame:frame];
6492 [self positionViews];
6495 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6496 if ((self = [super initWithFrame:frame])) {
6497 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6499 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6500 [self setBarStyle:1];
6502 int barstyle([self _barStyle:NO]);
6503 bool ugly(barstyle == 0);
6505 UIProgressIndicatorStyle style = ugly ?
6506 UIProgressIndicatorStyleMediumBrown :
6507 UIProgressIndicatorStyleMediumWhite;
6509 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6510 [indicator_ setStyle:style];
6511 [indicator_ startAnimation];
6512 [self addSubview:indicator_];
6514 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6515 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6516 [prompt_ setBackgroundColor:[UIColor clearColor]];
6517 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6518 [self addSubview:prompt_];
6520 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6521 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6522 [progress_ setStyle:0];
6523 [self addSubview:progress_];
6525 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6526 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6527 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6528 [cancel_ setBarStyle:barstyle];
6530 [self positionViews];
6535 [cancel_ removeFromSuperview];
6539 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6540 [progress_ setProgress:0];
6541 [self addSubview:cancel_];
6545 [cancel_ removeFromSuperview];
6548 - (void) setPrompt:(NSString *)prompt {
6549 [prompt_ setText:prompt];
6552 - (void) setProgress:(float)progress {
6553 [progress_ setProgress:progress];
6559 /* Cydia Tab Bar Controller {{{ */
6560 @interface CYTabBarController : UITabBarController {
6561 Database *database_;
6566 @implementation CYTabBarController
6568 /* XXX: some logic should probably go here related to
6569 freeing the view controllers on tab change */
6571 - (void) reloadData {
6572 size_t count([[self viewControllers] count]);
6573 for (size_t i(0); i != count; ++i) {
6574 UIViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6579 - (id) initWithDatabase: (Database *)database {
6580 if ((self = [super init]) != nil) {
6581 database_ = database;
6588 /* Cydia Navigation Controller {{{ */
6589 @interface CYNavigationController : UINavigationController <
6592 _transient Database *database_;
6596 - (id) initWithDatabase:(Database *)database;
6597 - (void) reloadData;
6602 @implementation CYNavigationController
6604 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6605 // Inherit autorotation settings for modal parents.
6606 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6607 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6609 return [super shouldAutorotateToInterfaceOrientation:orientation];
6617 - (void) reloadData {
6618 size_t count([[self viewControllers] count]);
6619 for (size_t i(0); i != count; ++i) {
6620 UIViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6625 - (void) setDelegate:(id)delegate {
6626 delegate_ = delegate;
6629 - (id) initWithDatabase:(Database *)database {
6630 if ((self = [super init]) != nil) {
6631 database_ = database;
6637 /* Cydia:// Protocol {{{ */
6638 @interface CydiaURLProtocol : NSURLProtocol {
6643 @implementation CydiaURLProtocol
6645 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6646 NSURL *url([request URL]);
6649 NSString *scheme([[url scheme] lowercaseString]);
6650 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6655 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6659 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6660 id<NSURLProtocolClient> client([self client]);
6662 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6664 NSData *data(UIImagePNGRepresentation(icon));
6666 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6667 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6668 [client URLProtocol:self didLoadData:data];
6669 [client URLProtocolDidFinishLoading:self];
6673 - (void) startLoading {
6674 id<NSURLProtocolClient> client([self client]);
6675 NSURLRequest *request([self request]);
6677 NSURL *url([request URL]);
6678 NSString *href([url absoluteString]);
6680 NSString *path([href substringFromIndex:8]);
6681 NSRange slash([path rangeOfString:@"/"]);
6684 if (slash.location == NSNotFound) {
6688 command = [path substringToIndex:slash.location];
6689 path = [path substringFromIndex:(slash.location + 1)];
6692 Database *database([Database sharedInstance]);
6694 if ([command isEqualToString:@"package-icon"]) {
6697 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6698 Package *package([database packageWithName:path]);
6701 UIImage *icon([package icon]);
6702 [self _returnPNGWithImage:icon forRequest:request];
6703 } else if ([command isEqualToString:@"source-icon"]) {
6706 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6707 NSString *source(Simplify(path));
6708 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6710 icon = [UIImage applicationImageNamed:@"unknown.png"];
6711 [self _returnPNGWithImage:icon forRequest:request];
6712 } else if ([command isEqualToString:@"uikit-image"]) {
6715 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6716 UIImage *icon(_UIImageWithName(path));
6717 [self _returnPNGWithImage:icon forRequest:request];
6718 } else if ([command isEqualToString:@"section-icon"]) {
6721 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6722 NSString *section(Simplify(path));
6723 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6725 icon = [UIImage applicationImageNamed:@"unknown.png"];
6726 [self _returnPNGWithImage:icon forRequest:request];
6728 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6732 - (void) stopLoading {
6738 /* Sections Controller {{{ */
6739 @interface SectionsController : CYViewController {
6740 _transient Database *database_;
6741 NSMutableArray *sections_;
6742 NSMutableArray *filtered_;
6748 - (id) initWithDatabase:(Database *)database;
6749 - (void) reloadData;
6754 @implementation SectionsController
6757 [list_ setDataSource:nil];
6758 [list_ setDelegate:nil];
6760 [sections_ release];
6761 [filtered_ release];
6763 [accessory_ release];
6767 - (void) viewDidAppear:(BOOL)animated {
6768 [super viewDidAppear:animated];
6769 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6772 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6773 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6777 - (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
6778 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6781 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6785 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6786 static NSString *reuseIdentifier = @"SectionCell";
6788 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6789 if (cell == nil) cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6790 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6795 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6796 Section *section = [self sectionAtIndexPath:indexPath];
6797 NSString *name = [section name];
6800 if ([indexPath row] == 0) {
6803 title = UCLocalize("ALL_PACKAGES");
6806 name = [NSString stringWithString:name];
6807 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6810 title = UCLocalize("NO_SECTION");
6814 FilteredPackageController *table = [[[FilteredPackageController alloc]
6815 initWithDatabase:database_
6817 filter:@selector(isVisibleInSection:)
6821 [table setDelegate:delegate_];
6823 [[self navigationController] pushViewController:table animated:YES];
6826 - (id) title { return UCLocalize("SECTIONS"); }
6828 - (id) initWithDatabase:(Database *)database {
6829 if ((self = [super init]) != nil) {
6830 database_ = database;
6832 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6834 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6835 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6837 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6838 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6839 [list_ setRowHeight:45.0f];
6840 [[self view] addSubview:list_];
6842 [list_ setDataSource:self];
6843 [list_ setDelegate:self];
6849 - (void) reloadData {
6850 NSArray *packages = [database_ packages];
6852 [sections_ removeAllObjects];
6853 [filtered_ removeAllObjects];
6856 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6857 SectionMap sections;
6858 sections.resize(64);
6860 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6864 for (Package *package in packages) {
6865 NSString *name([package section]);
6866 NSString *key(name == nil ? @"" : name);
6871 _profile(SectionsView$reloadData$Section)
6872 section = §ions[key];
6873 if (*section == nil) {
6874 _profile(SectionsView$reloadData$Section$Allocate)
6875 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6880 [*section addToCount];
6882 _profile(SectionsView$reloadData$Filter)
6883 if (![package valid] || ![package visible])
6887 [*section addToRow];
6891 _profile(SectionsView$reloadData$Section)
6892 section = [sections objectForKey:key];
6893 if (section == nil) {
6894 _profile(SectionsView$reloadData$Section$Allocate)
6895 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6896 [sections setObject:section forKey:key];
6901 [section addToCount];
6903 _profile(SectionsView$reloadData$Filter)
6904 if (![package valid] || ![package visible])
6914 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6915 [sections_ addObject:i->second];
6917 [sections_ addObjectsFromArray:[sections allValues]];
6920 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6922 for (Section *section in sections_) {
6923 size_t count([section row]);
6927 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6928 [section setCount:count];
6929 [filtered_ addObject:section];
6932 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6933 initWithTitle:[sections_ count] == 0 ? nil : UCLocalize("EDIT")
6934 style:UIBarButtonItemStylePlain
6936 action:@selector(editButtonClicked)
6938 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] != nil];
6939 [rightItem release];
6945 - (void) resetView {
6947 [self editButtonClicked];
6950 - (void) editButtonClicked {
6951 if ((editing_ = !editing_))
6954 [delegate_ updateData];
6956 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6957 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6958 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6961 - (UIView *) accessoryView {
6967 /* Changes Controller {{{ */
6968 @interface ChangesController : CYViewController {
6969 _transient Database *database_;
6970 NSMutableArray *packages_;
6971 NSMutableArray *sections_;
6974 BOOL hasSentFirstLoad_;
6977 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6978 - (void) reloadData;
6982 @implementation ChangesController
6985 [list_ setDelegate:nil];
6986 [list_ setDataSource:nil];
6988 [packages_ release];
6989 [sections_ release];
6994 - (void) viewDidAppear:(BOOL)animated {
6995 [super viewDidAppear:animated];
6996 if (!hasSentFirstLoad_) {
6997 hasSentFirstLoad_ = YES;
6998 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7000 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7004 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7005 NSInteger count([sections_ count]);
7006 return count == 0 ? 1 : count;
7009 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7010 if ([sections_ count] == 0)
7012 return [[sections_ objectAtIndex:section] name];
7015 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7016 if ([sections_ count] == 0)
7018 return [[sections_ objectAtIndex:section] count];
7021 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7022 Section *section([sections_ objectAtIndex:[path section]]);
7023 NSInteger row([path row]);
7024 return [packages_ objectAtIndex:([section row] + row)];
7027 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7028 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
7030 cell = [[[PackageCell alloc] init] autorelease];
7031 [cell setPackage:[self packageAtIndexPath:path]];
7035 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7036 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7039 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7040 Package *package([self packageAtIndexPath:path]);
7041 PackageController *view([delegate_ packageController]);
7042 [view setDelegate:delegate_];
7043 [view setPackage:package];
7044 [[self navigationController] pushViewController:view animated:YES];
7048 - (void) refreshButtonClicked {
7049 [[UIApplication sharedApplication] beginUpdate];
7050 [[self navigationItem] setLeftBarButtonItem:nil];
7053 - (void) upgradeButtonClicked {
7054 [delegate_ distUpgrade];
7057 - (id) title { return UCLocalize("CHANGES"); }
7059 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7060 if ((self = [super init]) != nil) {
7061 database_ = database;
7062 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7064 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
7065 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7067 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7068 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7069 [list_ setRowHeight:73.0f];
7070 [[self view] addSubview:list_];
7072 [list_ setDataSource:self];
7073 [list_ setDelegate:self];
7075 delegate_ = delegate;
7079 - (void) _reloadPackages:(NSArray *)packages {
7081 for (Package *package in packages)
7083 [package uninstalled] && [package valid] && [package visible] ||
7084 [package upgradableAndEssential:YES]
7086 [packages_ addObject:package];
7089 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7093 - (void) reloadData {
7094 NSArray *packages = [database_ packages];
7096 [packages_ removeAllObjects];
7097 [sections_ removeAllObjects];
7099 UIProgressHUD *hud([delegate_ addProgressHUD]);
7101 [hud setText:@"Loading Changes"];
7102 NSLog(@"HUD:%@::%@", delegate_, hud);
7103 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7104 [delegate_ removeProgressHUD:hud];
7106 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7107 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7108 Section *section = nil;
7112 bool unseens = false;
7114 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7116 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7117 Package *package = [packages_ objectAtIndex:offset];
7119 BOOL uae = [package upgradableAndEssential:YES];
7125 _profile(ChangesController$reloadData$Remember)
7126 seen = [package seen];
7129 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7134 name = UCLocalize("UNKNOWN");
7136 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7140 _profile(ChangesController$reloadData$Allocate)
7141 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7142 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7143 [sections_ addObject:section];
7147 [section addToCount];
7148 } else if ([package ignored])
7149 [ignored addToCount];
7152 [upgradable addToCount];
7157 CFRelease(formatter);
7160 Section *last = [sections_ lastObject];
7161 size_t count = [last count];
7162 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7163 [sections_ removeLastObject];
7166 if ([ignored count] != 0)
7167 [sections_ insertObject:ignored atIndex:0];
7169 [sections_ insertObject:upgradable atIndex:0];
7173 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7174 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7175 style:UIBarButtonItemStylePlain
7177 action:@selector(upgradeButtonClicked)
7179 if (upgrades_ > 0) [[self navigationItem] setRightBarButtonItem:rightItem];
7180 [rightItem release];
7182 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
7183 initWithTitle:UCLocalize("REFRESH")
7184 style:UIBarButtonItemStylePlain
7186 action:@selector(refreshButtonClicked)
7188 if (![[UIApplication sharedApplication] updating]) [[self navigationItem] setLeftBarButtonItem:leftItem];
7194 /* Search Controller {{{ */
7195 @interface SearchController : FilteredPackageController {
7199 - (id) initWithDatabase:(Database *)database;
7200 - (void) reloadData;
7204 @implementation SearchController
7211 - (void) searchBarSearchButtonClicked:(id)searchBar {
7212 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7213 [search_ resignFirstResponder];
7217 - (void) searchBar:(id)searchBar textDidChange:(NSString *)text {
7218 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7222 - (id) title { return nil; }
7224 - (id) initWithDatabase:(Database *)database {
7225 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7228 - (void)viewDidAppear:(BOOL)animated {
7229 [super viewDidAppear:animated];
7231 search_ = [[objc_getClass("UISearchBar") alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7232 [search_ layoutSubviews];
7233 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7234 UITextField *textField = [search_ searchField];
7235 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7236 [search_ setDelegate:self];
7237 [textField setEnablesReturnKeyAutomatically:NO];
7238 [[self navigationItem] setTitleView:textField];
7242 - (void) _reloadData {
7245 - (void) reloadData {
7246 _profile(SearchController$reloadData)
7247 [packages_ reloadData];
7250 [packages_ resetCursor];
7253 - (void) didSelectPackage:(Package *)package {
7254 [search_ resignFirstResponder];
7255 [super didSelectPackage:package];
7260 /* Settings Controller {{{ */
7261 @interface SettingsController : CYViewController {
7262 _transient Database *database_;
7265 UIPreferencesTable *table_;
7266 _UISwitchSlider *subscribedSwitch_;
7267 _UISwitchSlider *ignoredSwitch_;
7268 UIPreferencesControlTableCell *subscribedCell_;
7269 UIPreferencesControlTableCell *ignoredCell_;
7272 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7276 @implementation SettingsController
7279 [table_ setDataSource:nil];
7282 if (package_ != nil)
7285 [subscribedSwitch_ release];
7286 [ignoredSwitch_ release];
7287 [subscribedCell_ release];
7288 [ignoredCell_ release];
7292 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7293 if (package_ == nil)
7299 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7300 if (package_ == nil)
7313 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7314 if (package_ == nil)
7327 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7328 if (package_ == nil)
7341 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7342 if (package_ == nil)
7345 _UISwitchSlider *slider([cell control]);
7346 BOOL value([slider value] != 0);
7347 NSMutableDictionary *metadata([package_ metadata]);
7350 if (NSNumber *number = [metadata objectForKey:key])
7351 before = [number boolValue];
7355 if (value != before) {
7356 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7358 [delegate_ updateData];
7362 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7363 [self onSomething:cell withKey:@"IsSubscribed"];
7366 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7367 [self onSomething:cell withKey:@"IsIgnored"];
7370 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7371 if (package_ == nil)
7375 case 0: switch (row) {
7377 return subscribedCell_;
7379 return ignoredCell_;
7383 case 1: switch (row) {
7385 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7386 [cell setShowSelection:NO];
7387 [cell setTitle:UCLocalize("SHOW_ALL_CHANGES_EX")];
7400 - (id) title { return UCLocalize("SETTINGS"); }
7402 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7403 if ((self = [super init])) {
7404 database_ = database;
7405 name_ = [package retain];
7407 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7409 table_ = [[UIPreferencesTable alloc] initWithFrame:[[self view] bounds]];
7410 [[self view] addSubview:table_];
7412 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7413 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventTouchUpInside];
7415 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7416 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventTouchUpInside];
7418 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7419 [subscribedCell_ setShowSelection:NO];
7420 [subscribedCell_ setTitle:UCLocalize("SHOW_ALL_CHANGES")];
7421 [subscribedCell_ setControl:subscribedSwitch_];
7423 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7424 [ignoredCell_ setShowSelection:NO];
7425 [ignoredCell_ setTitle:UCLocalize("IGNORE_UPGRADES")];
7426 [ignoredCell_ setControl:ignoredSwitch_];
7428 [table_ setDataSource:self];
7433 - (void) reloadData {
7434 if (package_ != nil)
7435 [package_ autorelease];
7436 package_ = [database_ packageWithName:name_];
7437 if (package_ != nil) {
7439 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7440 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7443 [table_ reloadData];
7449 /* Signature Controller {{{ */
7450 @interface SignatureController : CYBrowserController {
7451 _transient Database *database_;
7455 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7459 @implementation SignatureController
7466 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7468 [super webView:sender didClearWindowObject:window forFrame:frame];
7471 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7472 if ((self = [super init]) != nil) {
7473 database_ = database;
7474 package_ = [package retain];
7479 - (void) reloadData {
7480 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7486 /* Cydia Container {{{ */
7487 @interface CYContainer : UIViewController <ProgressDelegate> {
7488 _transient Database *database_;
7489 RefreshBar *refreshbar_;
7494 UIViewController *root_;
7499 @implementation CYContainer
7501 // NOTE: UIWindow only sends the top controller these messages,
7502 // So we have to forward them on.
7504 - (void) viewDidAppear:(BOOL)animated {
7505 [super viewDidAppear:animated];
7506 [root_ viewDidAppear:animated];
7509 - (void) viewWillAppear:(BOOL)animated {
7510 [super viewWillAppear:animated];
7511 [root_ viewWillAppear:animated];
7514 - (void) viewDidDisappear:(BOOL)animated {
7515 [super viewDidDisappear:animated];
7516 [root_ viewDidDisappear:animated];
7519 - (void) viewWillDisappear:(BOOL)animated {
7520 [super viewWillDisappear:animated];
7521 [root_ viewWillDisappear:animated];
7524 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7525 return YES; /* XXX: return YES; */
7528 - (void) setRootController:(UIViewController *)controller {
7530 [[self view] addSubview:[root_ view]];
7533 - (void) setUpdate:(NSDate *)date {
7537 - (void) beginUpdate {
7539 [refreshbar_ start];
7544 detachNewThreadSelector:@selector(performUpdate)
7550 - (void) performUpdate { _pooled
7552 status.setDelegate(self);
7553 [database_ updateWithStatus:status];
7556 performSelectorOnMainThread:@selector(completeUpdate)
7562 - (void) completeUpdate {
7565 [self raiseBar:YES];
7567 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7570 - (void) cancelUpdate {
7571 [refreshbar_ cancel];
7572 [self completeUpdate];
7575 - (void) cancelPressed {
7576 [self cancelUpdate];
7583 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7584 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7587 - (void) startProgress {
7590 - (void) setProgressTitle:(NSString *)title {
7592 performSelectorOnMainThread:@selector(_setProgressTitle:)
7598 - (bool) isCancelling:(size_t)received {
7602 - (void) setProgressPercent:(float)percent {
7604 performSelectorOnMainThread:@selector(_setProgressPercent:)
7605 withObject:[NSNumber numberWithFloat:percent]
7610 - (void) addProgressOutput:(NSString *)output {
7612 performSelectorOnMainThread:@selector(_addProgressOutput:)
7618 - (void) _setProgressTitle:(NSString *)title {
7619 [refreshbar_ setPrompt:title];
7622 - (void) _setProgressPercent:(NSNumber *)percent {
7623 [refreshbar_ setProgress:[percent floatValue]];
7626 - (void) _addProgressOutput:(NSString *)output {
7629 - (void) setUpdateDelegate:(id)delegate {
7630 updatedelegate_ = delegate;
7633 - (void) dropBar:(BOOL)animated {
7634 if (dropped_) return;
7637 [[self view] addSubview:refreshbar_];
7639 if (animated) [UIView beginAnimations:nil context:NULL];
7640 CGRect barframe = [refreshbar_ frame];
7641 CGRect viewframe = [[root_ view] frame];
7642 viewframe.origin.y += barframe.size.height + 20.0f;
7643 viewframe.size.height -= barframe.size.height + 20.0f;
7644 [[root_ view] setFrame:viewframe];
7645 if (animated) [UIView commitAnimations];
7647 // Ensure bar has the proper width for our view, it might have changed
7648 barframe.size.width = viewframe.size.width;
7649 [refreshbar_ setFrame:barframe];
7651 // XXX: fix Apple's layout bug
7652 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7655 - (void) raiseBar:(BOOL)animated {
7656 if (!dropped_) return;
7659 [refreshbar_ removeFromSuperview];
7661 if (animated) [UIView beginAnimations:nil context:NULL];
7662 CGRect barframe = [refreshbar_ frame];
7663 CGRect viewframe = [[root_ view] frame];
7664 viewframe.origin.y -= barframe.size.height + 20.0f;
7665 viewframe.size.height += barframe.size.height + 20.0f;
7666 [[root_ view] setFrame:viewframe];
7667 if (animated) [UIView commitAnimations];
7669 // XXX: fix Apple's layout bug
7670 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7673 - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration
7675 // XXX: fix Apple's layout bug
7676 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7679 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7685 // XXX: fix Apple's layout bug
7686 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7690 [refreshbar_ release];
7694 - (id) initWithDatabase: (Database *)database {
7695 if ((self = [super init]) != nil) {
7696 database_ = database;
7698 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7700 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7717 @interface Cydia : UIApplication <
7718 ConfirmationControllerDelegate,
7719 ProgressControllerDelegate,
7723 CYContainer *container_;
7727 NSMutableArray *essential_;
7728 NSMutableArray *broken_;
7730 Database *database_;
7734 UIKeyboard *keyboard_;
7735 UIProgressHUD *hud_;
7737 SectionsController *sections_;
7738 ChangesController *changes_;
7739 ManageController *manage_;
7740 SearchController *search_;
7741 SourceTable *sources_;
7742 InstalledController *installed_;
7745 #if RecyclePackageViews
7746 NSMutableArray *details_;
7752 - (UIViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7753 - (void) setPage:(UIViewController *)page;
7757 static _finline void _setHomePage(Cydia *self) {
7758 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7761 @implementation Cydia
7763 - (void) beginUpdate {
7764 [container_ beginUpdate];
7768 return [container_ updating];
7771 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7776 if ([broken_ count] != 0) {
7777 int count = [broken_ count];
7779 UIAlertView *alert = [[[UIAlertView alloc]
7780 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7781 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7783 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7784 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
7787 [alert setContext:@"fixhalf"];
7789 } else if (!Ignored_ && [essential_ count] != 0) {
7790 int count = [essential_ count];
7792 UIAlertView *alert = [[[UIAlertView alloc]
7793 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7794 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
7796 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
7797 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
7800 [alert setContext:@"upgrade"];
7805 - (void) _saveConfig {
7808 NSString *error(nil);
7809 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7811 NSError *error(nil);
7812 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7813 NSLog(@"failure to save metadata data: %@", error);
7816 NSLog(@"failure to serialize metadata: %@", error);
7824 - (void) _updateData {
7827 /* XXX: this is just stupid */
7828 if (tag_ != 1 && sections_ != nil)
7829 [sections_ reloadData];
7830 if (tag_ != 2 && changes_ != nil)
7831 [changes_ reloadData];
7832 if (tag_ != 4 && search_ != nil)
7833 [search_ reloadData];
7835 [[tabbar_ selectedViewController] reloadData];
7838 - (int)indexOfTabWithTag:(int)tag {
7840 for (UINavigationController *controller in [tabbar_ viewControllers]) {
7841 if ([[controller tabBarItem] tag] == tag) return i;
7848 - (void) _refreshIfPossible {
7849 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
7851 Reachability* reachability = [Reachability reachabilityWithHostName:@"cydia.saurik.com"];
7852 NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
7854 if (loaded_ || ManualRefresh || remoteHostStatus == NotReachable) loaded:
7855 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
7859 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
7861 if (update != nil) {
7862 NSTimeInterval interval([update timeIntervalSinceNow]);
7863 if (interval <= 0 && interval > -(15*60))
7867 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
7873 - (void) refreshIfPossible {
7874 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
7877 - (void) _reloadData {
7880 UIProgressHUD *hud([self addProgressHUD]);
7881 [hud setText:(loaded_ ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
7883 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7886 [self removeProgressHUD:hud];
7890 [essential_ removeAllObjects];
7891 [broken_ removeAllObjects];
7893 NSArray *packages([database_ packages]);
7894 for (Package *package in packages) {
7896 [broken_ addObject:package];
7897 if ([package upgradableAndEssential:NO]) {
7898 if ([package essential])
7899 [essential_ addObject:package];
7905 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7906 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:badge];
7907 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:YES];
7909 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7910 [self setApplicationBadge:badge];
7912 [self setApplicationBadgeString:badge];
7914 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:nil];
7915 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:NO];
7917 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7918 [self removeApplicationBadge];
7919 else // XXX: maybe use setApplicationBadgeString also?
7920 [self setApplicationIconBadgeNumber:0];
7925 [self refreshIfPossible];
7928 - (void) updateData {
7929 [database_ setVisible];
7938 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
7939 _assert(file != NULL);
7941 for (NSString *key in [Sources_ allKeys]) {
7942 NSDictionary *source([Sources_ objectForKey:key]);
7944 fprintf(file, "%s %s %s\n",
7945 [[source objectForKey:@"Type"] UTF8String],
7946 [[source objectForKey:@"URI"] UTF8String],
7947 [[source objectForKey:@"Distribution"] UTF8String]
7955 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
7956 UINavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
7957 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
7958 [container_ presentModalViewController:navigation animated:YES];
7961 detachNewThreadSelector:@selector(update_)
7964 title:UCLocalize("UPDATING_SOURCES")
7968 - (void) reloadData {
7969 @synchronized (self) {
7975 pkgProblemResolver *resolver = [database_ resolver];
7977 resolver->InstallProtect();
7978 if (!resolver->Resolve(true))
7982 - (CGRect) popUpBounds {
7983 return [[tabbar_ view] bounds];
7987 if (![database_ prepare])
7990 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
7991 [page setDelegate:self];
7992 id confirm_ = [[CYNavigationController alloc] initWithRootViewController:page];
7993 [confirm_ setDelegate:self];
7995 if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
7996 [container_ presentModalViewController:confirm_ animated:YES];
8002 @synchronized (self) {
8007 - (void) clearPackage:(Package *)package {
8008 @synchronized (self) {
8015 - (void) installPackages:(NSArray *)packages {
8016 @synchronized (self) {
8017 for (Package *package in packages)
8024 - (void) installPackage:(Package *)package {
8025 @synchronized (self) {
8032 - (void) removePackage:(Package *)package {
8033 @synchronized (self) {
8040 - (void) distUpgrade {
8041 @synchronized (self) {
8042 if (![database_ upgrade])
8049 @synchronized (self) {
8054 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8055 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8057 if (navigation != nil) {
8058 [navigation pushViewController:progress animated:YES];
8060 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8061 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8062 [container_ presentModalViewController:navigation animated:YES];
8066 detachNewThreadSelector:@selector(perform)
8069 title:UCLocalize("RUNNING")
8073 - (void) progressControllerIsComplete:(ProgressController *)progress {
8077 - (void) setPage:(UIViewController *)page {
8078 [page setDelegate:self];
8080 UINavigationController *navController = [tabbar_ selectedViewController];
8081 [navController setViewControllers:[NSArray arrayWithObject:page] animated:NO];
8082 for (UIViewController *page in [tabbar_ viewControllers]) {
8083 if (page != navController) [page setViewControllers:nil];
8087 - (UIViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8088 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8089 [browser loadURL:url];
8093 - (SectionsController *) sectionsController {
8094 if (sections_ == nil)
8095 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8099 - (ChangesController *) changesController {
8100 if (changes_ == nil)
8101 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8105 - (ManageController *) manageController {
8106 if (manage_ == nil) {
8107 manage_ = (ManageController *) [[self
8108 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8109 withClass:[ManageController class]
8111 if (!IsWildcat_) queueDelegate_ = manage_;
8116 - (SearchController *) searchController {
8118 search_ = [[SearchController alloc] initWithDatabase:database_];
8122 - (SourceTable *) sourcesController {
8123 if (sources_ == nil)
8124 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8128 - (InstalledController *) installedController {
8129 if (installed_ == nil) {
8130 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8131 if (IsWildcat_) queueDelegate_ = installed_;
8136 - (void) tabBarController:(id)tabBarController didSelectViewController:(UIViewController *)viewController {
8137 int tag = [[viewController tabBarItem] tag];
8139 [[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8141 } else if (tag_ == 1) {
8142 [[self sectionsController] resetView];
8146 case kCydiaTag: _setHomePage(self); break;
8148 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8149 case kChangesTag: [self setPage:[self changesController]]; break;
8150 case kManageTag: [self setPage:[self manageController]]; break;
8151 case kInstalledTag: [self setPage:[self installedController]]; break;
8152 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8153 case kSearchTag: [self setPage:[self searchController]]; break;
8161 - (void) askForSettings {
8162 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
8164 CYActionSheet *role([[[CYActionSheet alloc]
8165 initWithTitle:UCLocalize("WHO_ARE_YOU")
8166 buttons:[NSArray arrayWithObjects:
8167 [NSString stringWithFormat:parenthetical, UCLocalize("USER"), UCLocalize("USER_EX")],
8168 [NSString stringWithFormat:parenthetical, UCLocalize("HACKER"), UCLocalize("HACKER_EX")],
8169 [NSString stringWithFormat:parenthetical, UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")],
8171 defaultButtonIndex:-1
8174 [role setMessage:UCLocalize("ROLE_EX")];
8176 int button([role yieldToPopupAlertAnimated:YES]);
8179 case 1: Role_ = @"User"; break;
8180 case 2: Role_ = @"Hacker"; break;
8181 case 3: Role_ = @"Developer"; break;
8186 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8190 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8197 - (void) setPackageController:(PackageController *)view {
8199 [view setPackage:nil];
8200 #if RecyclePackageViews
8201 if ([details_ count] < 3)
8202 [details_ addObject:view];
8207 - (PackageController *) _packageController {
8208 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8211 - (PackageController *) packageController {
8212 #if RecyclePackageViews
8213 PackageController *view;
8214 size_t count([details_ count]);
8217 view = [self _packageController];
8219 [details_ addObject:[self _packageController]];
8221 view = [[[details_ lastObject] retain] autorelease];
8222 [details_ removeLastObject];
8229 return [self _packageController];
8233 - (void) cancelAndClear:(bool)clear {
8234 @synchronized (self) {
8236 /* XXX: clear marks instead of reloading data */
8237 /*pkgCacheFile &cache([database_ cache]);
8238 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
8239 if (!cache[iterator].Keep()) cache->MarkKeep(iterator, false, false);
8245 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kManageTag] != -1 ? [self indexOfTabWithTag:kManageTag] : [self indexOfTabWithTag:kInstalledTag]] tabBarItem] setBadgeValue:nil];
8246 [queueDelegate_ queueStatusDidChange];*/
8251 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kManageTag] != -1 ? [self indexOfTabWithTag:kManageTag] : [self indexOfTabWithTag:kInstalledTag]] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8252 [[tabbar_ selectedViewController] reloadData];
8254 [queueDelegate_ queueStatusDidChange];
8259 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8260 NSString *context([alert context]);
8262 if ([context isEqualToString:@"fixhalf"]) {
8263 if (button == [alert firstOtherButtonIndex]) {
8264 @synchronized (self) {
8265 for (Package *broken in broken_) {
8268 NSString *id = [broken id];
8269 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8270 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8271 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8272 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8278 } else if (button == [alert cancelButtonIndex]) {
8279 [broken_ removeAllObjects];
8283 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8284 } else if ([context isEqualToString:@"upgrade"]) {
8285 if (button == [alert firstOtherButtonIndex]) {
8286 @synchronized (self) {
8287 for (Package *essential in essential_)
8288 [essential install];
8293 } else if (button == [alert firstOtherButtonIndex] + 1) {
8295 } else if (button == [alert cancelButtonIndex]) {
8299 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8303 - (void) system:(NSString *)command { _pooled
8304 system([command UTF8String]);
8307 - (void) applicationWillSuspend {
8309 [super applicationWillSuspend];
8312 - (void) applicationSuspend:(__GSEvent *)event {
8313 // FIXME: This needs to be fixed, but we no longer have a progress_.
8314 // What's the best solution?
8315 if (hud_ == nil)// && ![progress_ isRunning])
8316 [super applicationSuspend:event];
8319 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8321 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8324 - (void) _setSuspended:(BOOL)value {
8326 [super _setSuspended:value];
8329 - (UIProgressHUD *) addProgressHUD {
8330 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8331 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8333 [window_ setUserInteractionEnabled:NO];
8335 [[container_ view] addSubview:hud];
8339 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8341 [hud removeFromSuperview];
8342 [window_ setUserInteractionEnabled:YES];
8345 - (UIViewController *) pageForPackage:(NSString *)name {
8346 if (Package *package = [database_ packageWithName:name]) {
8347 PackageController *view([self packageController]);
8348 [view setPackage:package];
8351 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8352 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8353 return [self _pageForURL:url withClass:[CYBrowserController class]];
8357 - (UIViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8361 NSString *href([url absoluteString]);
8362 if ([href hasPrefix:@"apptapp://package/"])
8363 return [self pageForPackage:[href substringFromIndex:18]];
8365 NSString *scheme([[url scheme] lowercaseString]);
8366 if (![scheme isEqualToString:@"cydia"])
8368 NSString *path([url absoluteString]);
8369 if ([path length] < 8)
8371 path = [path substringFromIndex:8];
8372 if (![path hasPrefix:@"/"])
8373 path = [@"/" stringByAppendingString:path];
8375 if ([path isEqualToString:@"/add-source"])
8376 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8377 else if ([path isEqualToString:@"/storage"])
8378 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8379 else if ([path isEqualToString:@"/sources"])
8380 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8381 else if ([path isEqualToString:@"/packages"])
8382 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8383 else if ([path hasPrefix:@"/url/"])
8384 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8385 else if ([path hasPrefix:@"/launch/"])
8386 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8387 else if ([path hasPrefix:@"/package-settings/"])
8388 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8389 else if ([path hasPrefix:@"/package-signature/"])
8390 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8391 else if ([path hasPrefix:@"/package/"])
8392 return [self pageForPackage:[path substringFromIndex:9]];
8393 else if ([path hasPrefix:@"/files/"]) {
8394 NSString *name = [path substringFromIndex:7];
8396 if (Package *package = [database_ packageWithName:name]) {
8397 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8398 [files setPackage:package];
8406 - (void) applicationOpenURL:(NSURL *)url {
8407 [super applicationOpenURL:url];
8409 if (UIViewController *page = [self pageForURL:url hasTag:&tag]) {
8410 [self setPage:page];
8412 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8416 - (void) applicationDidFinishLaunching:(id)unused {
8417 [CYBrowserController _initialize];
8419 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8421 Font12_ = [[UIFont systemFontOfSize:12] retain];
8422 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8423 Font14_ = [[UIFont systemFontOfSize:14] retain];
8424 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8425 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8429 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8430 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8432 UIScreen *screen([UIScreen mainScreen]);
8434 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8435 [window_ orderFront:self];
8436 [window_ makeKey:self];
8437 [window_ setHidden:NO];
8439 database_ = [Database sharedInstance];
8442 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8443 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8444 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8445 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8446 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8447 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8448 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8449 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8450 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8453 [self setIdleTimerDisabled:YES];
8455 hud_ = [self addProgressHUD];
8456 [hud_ setText:@"Reorganizing:\n\nWill Automatically\nClose When Done"];
8457 [self setStatusBarShowsProgress:YES];
8459 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8461 [self setStatusBarShowsProgress:NO];
8462 [self removeProgressHUD:hud_];
8465 if (ExecFork() == 0) {
8466 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8467 perror("launchctl stop");
8474 [self askForSettings];
8478 NSMutableArray *controllers = [NSMutableArray array];
8479 [controllers addObject:[[CYNavigationController alloc] initWithDatabase:database_]];
8480 [controllers addObject:[[CYNavigationController alloc] initWithDatabase:database_]];
8481 [controllers addObject:[[CYNavigationController alloc] initWithDatabase:database_]];
8482 if (IsWildcat_) [controllers addObject:[[CYNavigationController alloc] initWithDatabase:database_]];
8483 [controllers addObject:[[CYNavigationController alloc] initWithDatabase:database_]];
8484 [controllers addObject:[[CYNavigationController alloc] initWithDatabase:database_]];
8486 NSMutableArray *items = [NSMutableArray arrayWithObjects:
8487 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8488 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8489 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8490 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8495 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8496 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8498 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8501 for (int i = 0; i < [items count]; i++) {
8502 [[controllers objectAtIndex:i] setTabBarItem:[items objectAtIndex:i]];
8505 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8506 [tabbar_ setViewControllers:controllers];
8507 [tabbar_ setDelegate:self];
8508 [tabbar_ setSelectedIndex:0];
8510 container_ = [[CYContainer alloc] initWithDatabase:database_];
8511 [container_ setUpdateDelegate:self];
8512 [container_ setRootController:tabbar_];
8513 [window_ addSubview:[container_ view]];
8514 [[tabbar_ view] setFrame:CGRectMake(0, -20.0f, [window_ bounds].size.width, [window_ bounds].size.height)];
8516 [UIKeyboard initImplementationNow];
8520 #if RecyclePackageViews
8521 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8522 [details_ addObject:[self _packageController]];
8523 [details_ addObject:[self _packageController]];
8531 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8532 if (item != nil && IsWildcat_) {
8533 [sheet showFromBarButtonItem:item animated:YES];
8535 [sheet showInView:window_];
8542 id Alloc_(id self, SEL selector) {
8543 id object = alloc_(self, selector);
8544 lprintf("[%s]A-%p\n", self->isa->name, object);
8549 id Dealloc_(id self, SEL selector) {
8550 id object = dealloc_(self, selector);
8551 lprintf("[%s]D-%p\n", self->isa->name, object);
8555 Class $WebDefaultUIKitDelegate;
8557 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8558 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8559 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8560 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8563 static NSNumber *shouldPlayKeyboardSounds;
8567 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int soundIndex) {
8568 switch (soundIndex) {
8569 case 1104: // Keyboard Button Clicked
8570 case 1105: // Keyboard Delete Repeated
8571 if (!shouldPlayKeyboardSounds) {
8572 NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"];
8573 shouldPlayKeyboardSounds = [[dict objectForKey:@"keyboard"] ?: (id)kCFBooleanTrue retain];
8576 if (![shouldPlayKeyboardSounds boolValue])
8579 _UIHardware$_playSystemSound$(self, _cmd, soundIndex);
8583 int main(int argc, char *argv[]) { _pooled
8586 if (Class $UIDevice = objc_getClass("UIDevice")) {
8587 UIDevice *device([$UIDevice currentDevice]);
8588 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8592 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8594 /* Library Hacks {{{ */
8595 class_addMethod(objc_getClass("WebScriptObject"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &WebScriptObject$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8596 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8598 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8599 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8600 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8601 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8602 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8605 $UIHardware = objc_getClass("UIHardware");
8606 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8607 if (UIHardware$_playSystemSound$ != NULL) {
8608 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8609 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8612 /* Set Locale {{{ */
8613 Locale_ = CFLocaleCopyCurrent();
8614 Languages_ = [NSLocale preferredLanguages];
8615 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8616 //NSLog(@"%@", [Languages_ description]);
8619 if (Languages_ == nil || [Languages_ count] == 0)
8620 // XXX: consider just setting to C and then falling through?
8623 lang = [[Languages_ objectAtIndex:0] UTF8String];
8624 setenv("LANG", lang, true);
8627 //std::setlocale(LC_ALL, lang);
8628 NSLog(@"Setting Language: %s", lang);
8631 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8633 /* Parse Arguments {{{ */
8634 bool substrate(false);
8640 for (int argi(1); argi != argc; ++argi)
8641 if (strcmp(argv[argi], "--") == 0) {
8643 argv[argi] = argv[0];
8649 for (int argi(1); argi != arge; ++argi)
8650 if (strcmp(args[argi], "--substrate") == 0)
8653 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8657 App_ = [[NSBundle mainBundle] bundlePath];
8658 Home_ = NSHomeDirectory();
8664 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8665 alloc_ = alloc->method_imp;
8666 alloc->method_imp = (IMP) &Alloc_;*/
8668 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8669 dealloc_ = dealloc->method_imp;
8670 dealloc->method_imp = (IMP) &Dealloc_;*/
8672 /* System Information {{{ */
8676 size = sizeof(maxproc);
8677 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8678 perror("sysctlbyname(\"kern.maxproc\", ?)");
8679 else if (maxproc < 64) {
8681 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8682 perror("sysctlbyname(\"kern.maxproc\", #)");
8685 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8686 char *osversion = new char[size];
8687 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8688 perror("sysctlbyname(\"kern.osversion\", ?)");
8690 System_ = [NSString stringWithUTF8String:osversion];
8692 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8693 char *machine = new char[size];
8694 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8695 perror("sysctlbyname(\"hw.machine\", ?)");
8699 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8700 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8701 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8702 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8706 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8707 NSData *data((NSData *) ecid);
8708 size_t length([data length]);
8709 uint8_t bytes[length];
8710 [data getBytes:bytes];
8711 char string[length * 2 + 1];
8712 for (size_t i(0); i != length; ++i)
8713 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8714 ChipID_ = [NSString stringWithUTF8String:string];
8718 IOObjectRelease(service);
8722 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8724 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8725 Build_ = [system objectForKey:@"ProductBuildVersion"];
8726 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8727 Product_ = [info objectForKey:@"SafariProductVersion"];
8728 Safari_ = [info objectForKey:@"CFBundleVersion"];
8731 /* Load Database {{{ */
8733 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8735 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8738 if (Metadata_ == NULL)
8739 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8741 Settings_ = [Metadata_ objectForKey:@"Settings"];
8743 Packages_ = [Metadata_ objectForKey:@"Packages"];
8744 Sections_ = [Metadata_ objectForKey:@"Sections"];
8745 Sources_ = [Metadata_ objectForKey:@"Sources"];
8747 Token_ = [Metadata_ objectForKey:@"Token"];
8750 if (Settings_ != nil)
8751 Role_ = [Settings_ objectForKey:@"Role"];
8753 if (Packages_ == nil) {
8754 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8755 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8758 if (Sections_ == nil) {
8759 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8760 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8763 if (Sources_ == nil) {
8764 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8765 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8770 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8773 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8775 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
8776 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
8777 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8778 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8779 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8780 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8782 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
8784 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8785 unlink("/tmp/.cydia.fw");
8787 } else if (access("/User", F_OK) != 0 || version < 2) {
8790 system("/usr/libexec/cydia/firmware.sh");
8794 _assert([[NSFileManager defaultManager]
8795 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8796 withIntermediateDirectories:YES
8801 if (access("/tmp/cydia.chk", F_OK) == 0) {
8802 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8803 _assert(errno == ENOENT);
8804 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8805 _assert(errno == ENOENT);
8808 /* APT Initialization {{{ */
8809 _assert(pkgInitConfig(*_config));
8810 _assert(pkgInitSystem(*_config, _system));
8813 _config->Set("APT::Acquire::Translation", lang);
8814 _config->Set("Acquire::http::Timeout", 15);
8815 _config->Set("Acquire::http::MaxParallel", 3);
8817 /* Color Choices {{{ */
8818 space_ = CGColorSpaceCreateDeviceRGB();
8820 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8821 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8822 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8823 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8824 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8825 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8826 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8827 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8828 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8830 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8831 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8833 /* UIKit Configuration {{{ */
8834 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8835 if ($GSFontSetUseLegacyFontMetrics != NULL)
8836 $GSFontSetUseLegacyFontMetrics(YES);
8838 // XXX: I have a feeling this was important
8839 //UIKeyboardDisableAutomaticAppearance();
8842 Colon_ = UCLocalize("COLON_DELIMITED");
8843 Error_ = UCLocalize("ERROR");
8844 Warning_ = UCLocalize("WARNING");
8847 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8849 CGColorSpaceRelease(space_);