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>
121 #import "UICaboodle/BrowserView.h"
122 #import "UICaboodle/ResetView.h"
124 #import "substrate.h"
126 // Apple's sample Reachability code, ASPL licensed.
127 #import "Reachability.h"
130 /* Header Fixes and Updates {{{ */
132 UIModalPresentationFullScreen = 0,
133 UIModalPresentationPageSheet,
134 UIModalPresentationFormSheet,
135 UIModalPresentationCurrentContext,
136 } UIModalPresentationStyle;
138 @interface UIAlertView (Private)
139 - (void)setNumberOfRows:(int)rows;
140 - (void)setContext:(id)context;
144 @interface UIViewController (UIKit)
145 - (id)navigationItem;
146 - (id)navigationController;
150 @interface UITabBarController : UIViewController {
153 id _viewControllerTransitionView;
155 id _tabBarItemsToViewControllers;
156 id _selectedViewController;
157 id _moreNavigationController;
158 id _customizableViewControllers;
160 id _selectedViewControllerDuringWillAppear;
161 id _transientViewController;
162 unsigned int isShowingMoreItem:1;
163 unsigned int needsToRebuildItems:1;
164 unsigned int isBarHidden:1;
165 unsigned int editButtonOnLeft:1;
174 #define _timestamp ({ \
176 gettimeofday(&tv, NULL); \
177 tv.tv_sec * 1000000 + tv.tv_usec; \
180 typedef std::vector<class ProfileTime *> TimeList;
190 ProfileTime(const char *name) :
194 times_.push_back(this);
197 void AddTime(uint64_t time) {
204 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
216 ProfileTimer(ProfileTime &time) :
223 time_.AddTime(_timestamp - start_);
228 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
230 std::cerr << "========" << std::endl;
233 #define _profile(name) { \
234 static ProfileTime name(#name); \
235 ProfileTimer _ ## name(name);
240 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
242 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
244 void NSLogPoint(const char *fix, const CGPoint &point) {
245 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
248 void NSLogRect(const char *fix, const CGRect &rect) {
249 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
252 static _finline NSString *CydiaURL(NSString *path) {
254 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
255 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
256 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
257 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
258 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
259 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
262 static _finline void UpdateExternalStatus(uint64_t newStatus) {
264 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
265 notify_set_state(notify_token, newStatus);
266 notify_cancel(notify_token);
268 notify_post("com.saurik.Cydia.status");
271 /* [NSObject yieldToSelector:(withObject:)] {{{*/
272 @interface NSObject (Cydia)
273 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
274 - (id) yieldToSelector:(SEL)selector;
277 @implementation NSObject (Cydia)
282 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
283 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
284 id object([[context objectAtIndex:1] nonretainedObjectValue]);
285 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
287 /* XXX: deal with exceptions */
288 id value([self performSelector:selector withObject:object]);
290 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
291 [context removeAllObjects];
292 if ([signature methodReturnLength] != 0 && value != nil)
293 [context addObject:value];
298 performSelectorOnMainThread:@selector(doNothing)
304 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
305 /*return [self performSelector:selector withObject:object];*/
307 volatile bool stopped(false);
309 NSMutableArray *context([NSMutableArray arrayWithObjects:
310 [NSValue valueWithPointer:selector],
311 [NSValue valueWithNonretainedObject:object],
312 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
315 NSThread *thread([[[NSThread alloc]
317 selector:@selector(_yieldToContext:)
323 NSRunLoop *loop([NSRunLoop currentRunLoop]);
324 NSDate *future([NSDate distantFuture]);
326 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
328 return [context count] == 0 ? nil : [context objectAtIndex:0];
331 - (id) yieldToSelector:(SEL)selector {
332 return [self yieldToSelector:selector withObject:nil];
338 @interface CYActionSheet : UIAlertView {
342 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
345 @implementation CYActionSheet
347 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
348 if ((self = [super init])) {
349 [self setTitle:title];
350 [self setDelegate:self];
351 for (NSString *button in buttons) [self addButtonWithTitle:button];
352 [self setCancelButtonIndex:index];
356 - (void)_updateFrameForDisplay {
357 [super _updateFrameForDisplay];
358 if ([self cancelButtonIndex] == -1) {
359 NSArray *buttons = [self buttons];
360 if ([buttons count]) {
361 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
362 for (UIThreePartButton *button in buttons)
363 [button setBackground:background forState:0];
368 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
369 button_ = buttonIndex + 1;
373 [self dismissWithClickedButtonIndex:-1 animated:YES];
376 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
377 [self setRunsModal:YES];
385 /* NSForcedOrderingSearch doesn't work on the iPhone */
386 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
387 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
388 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
390 /* Information Dictionaries {{{ */
391 @interface NSMutableArray (Cydia)
392 - (void) addInfoDictionary:(NSDictionary *)info;
395 @implementation NSMutableArray (Cydia)
397 - (void) addInfoDictionary:(NSDictionary *)info {
398 [self addObject:info];
403 @interface NSMutableDictionary (Cydia)
404 - (void) addInfoDictionary:(NSDictionary *)info;
407 @implementation NSMutableDictionary (Cydia)
409 - (void) addInfoDictionary:(NSDictionary *)info {
410 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
416 #define lprintf(args...) fprintf(stderr, args)
419 #define TraceLogging (1 && !ForRelease)
420 #define HistogramInsertionSort (0 && !ForRelease)
421 #define ProfileTimes (0 && !ForRelease)
422 #define ForSaurik (0 && !ForRelease)
423 #define LogBrowser (0 && !ForRelease)
424 #define TrackResize (0 && !ForRelease)
425 #define ManualRefresh (0 && !ForRelease)
426 #define ShowInternals (0 && !ForRelease)
427 #define IgnoreInstall (0 && !ForRelease)
428 #define RecycleWebViews 0
429 #define RecyclePackageViews (1 && ForRelease)
430 #define AlwaysReload (1 && !ForRelease)
434 #define _trace(args...)
439 #define _profile(name) {
442 #define PrintTimes() do {} while (false)
446 typedef uint32_t (*SKRadixFunction)(id, void *);
448 @interface NSMutableArray (Radix)
449 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
450 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
458 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
459 struct RadixItem_ *lhs(swap), *rhs(swap + count);
461 static const size_t width = 32;
462 static const size_t bits = 11;
463 static const size_t slots = 1 << bits;
464 static const size_t passes = (width + (bits - 1)) / bits;
466 size_t *hist(new size_t[slots]);
468 for (size_t pass(0); pass != passes; ++pass) {
469 memset(hist, 0, sizeof(size_t) * slots);
471 for (size_t i(0); i != count; ++i) {
472 uint32_t key(lhs[i].key);
474 key &= _not(uint32_t) >> width - bits;
479 for (size_t i(0); i != slots; ++i) {
480 size_t local(offset);
485 for (size_t i(0); i != count; ++i) {
486 uint32_t key(lhs[i].key);
488 key &= _not(uint32_t) >> width - bits;
489 rhs[hist[key]++] = lhs[i];
492 RadixItem_ *tmp(lhs);
499 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
500 for (size_t i(0); i != count; ++i)
501 [values addObject:[self objectAtIndex:lhs[i].index]];
502 [self setArray:values];
507 @implementation NSMutableArray (Radix)
509 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
510 size_t count([self count]);
515 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
516 [invocation setSelector:selector];
517 [invocation setArgument:&object atIndex:2];
519 /* XXX: this is an unsafe optimization of doomy hell */
520 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
521 _assert(method != NULL);
522 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
523 _assert(imp != NULL);
526 struct RadixItem_ *swap(new RadixItem_[count * 2]);
528 for (size_t i(0); i != count; ++i) {
529 RadixItem_ &item(swap[i]);
532 id object([self objectAtIndex:i]);
535 [invocation setTarget:object];
537 [invocation getReturnValue:&item.key];
539 item.key = imp(object, selector, object);
543 RadixSort_(self, count, swap);
546 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
547 size_t count([self count]);
548 struct RadixItem_ *swap(new RadixItem_[count * 2]);
550 for (size_t i(0); i != count; ++i) {
551 RadixItem_ &item(swap[i]);
554 id object([self objectAtIndex:i]);
555 item.key = function(object, argument);
558 RadixSort_(self, count, swap);
563 /* Insertion Sort {{{ */
565 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
566 const char *ptr = (const char *)list;
568 CFIndex half = count / 2;
569 const char *probe = ptr + elementSize * half;
570 CFComparisonResult cr = comparator(element, probe, context);
571 if (0 == cr) return (probe - (const char *)list) / elementSize;
572 ptr = (cr < 0) ? ptr : probe + elementSize;
573 count = (cr < 0) ? half : (half + (count & 1) - 1);
575 return (ptr - (const char *)list) / elementSize;
578 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
579 const char *ptr = (const char *)list;
581 CFIndex half = count / 2;
582 const char *probe = ptr + elementSize * half;
583 CFComparisonResult cr = comparator(element, probe, context);
584 if (0 == cr) return (probe - (const char *)list) / elementSize;
585 ptr = (cr < 0) ? ptr : probe + elementSize;
586 count = (cr < 0) ? half : (half + (count & 1) - 1);
588 return (ptr - (const char *)list) / elementSize;
591 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
592 if (range.length == 0)
594 const void **values(new const void *[range.length]);
595 CFArrayGetValues(array, range, values);
597 #if HistogramInsertionSort
598 uint32_t total(0), *offsets(new uint32_t[range.length]);
601 for (CFIndex index(1); index != range.length; ++index) {
602 const void *value(values[index]);
603 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
604 CFIndex correct(index);
605 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
608 if (correct != index) {
609 size_t offset(index - correct);
610 #if HistogramInsertionSort
614 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
616 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
617 values[correct] = value;
621 CFArrayReplaceValues(array, range, values, range.length);
624 #if HistogramInsertionSort
625 for (CFIndex index(0); index != range.length; ++index)
626 if (offsets[index] != 0)
627 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
628 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
635 /* Apple Bug Fixes {{{ */
636 @implementation UIWebDocumentView (Cydia)
638 - (void) _setScrollerOffset:(CGPoint)offset {
639 UIScroller *scroller([self _scroller]);
641 CGSize size([scroller contentSize]);
642 CGSize bounds([scroller bounds].size);
645 max.x = size.width - bounds.width;
646 max.y = size.height - bounds.height;
654 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
655 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
657 [scroller setOffset:offset];
663 NSUInteger WebScriptObject$countByEnumeratingWithState$objects$count$(WebScriptObject *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
664 size_t length([self count] - state->state);
667 else if (length > count)
669 for (size_t i(0); i != length; ++i)
670 objects[i] = [self objectAtIndex:state->state++];
671 state->itemsPtr = objects;
672 state->mutationsPtr = (unsigned long *) self;
676 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
677 size_t length([self length] - state->state);
680 else if (length > count)
682 for (size_t i(0); i != length; ++i)
683 objects[i] = [self item:state->state++];
684 state->itemsPtr = objects;
685 state->mutationsPtr = (unsigned long *) self;
689 @interface NSString (UIKit)
690 - (NSString *) stringByAddingPercentEscapes;
693 /* Cydia NSString Additions {{{ */
694 @interface NSString (Cydia)
695 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
696 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
697 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
698 - (NSComparisonResult) compareByPath:(NSString *)other;
699 - (NSString *) stringByCachingURLWithCurrentCDN;
700 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
703 @implementation NSString (Cydia)
705 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
706 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
709 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
710 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
711 memcpy(data, bytes, length);
712 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
715 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
716 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
719 - (NSComparisonResult) compareByPath:(NSString *)other {
720 NSString *prefix = [self commonPrefixWithString:other options:0];
721 size_t length = [prefix length];
723 NSRange lrange = NSMakeRange(length, [self length] - length);
724 NSRange rrange = NSMakeRange(length, [other length] - length);
726 lrange = [self rangeOfString:@"/" options:0 range:lrange];
727 rrange = [other rangeOfString:@"/" options:0 range:rrange];
729 NSComparisonResult value;
731 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
732 value = NSOrderedSame;
733 else if (lrange.location == NSNotFound)
734 value = NSOrderedAscending;
735 else if (rrange.location == NSNotFound)
736 value = NSOrderedDescending;
738 value = NSOrderedSame;
740 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
741 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
742 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
743 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
745 NSComparisonResult result = [lpath compare:rpath];
746 return result == NSOrderedSame ? value : result;
749 - (NSString *) stringByCachingURLWithCurrentCDN {
751 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
752 withString:@"://cache.cydia.saurik.com/"
756 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
757 return [(id)CFURLCreateStringByAddingPercentEscapes(
762 kCFStringEncodingUTF8
769 /* C++ NSString Wrapper Cache {{{ */
776 _finline void clear_() {
777 if (cache_ != NULL) {
784 _finline bool empty() const {
788 _finline size_t size() const {
792 _finline char *data() const {
796 _finline void clear() {
801 _finline CYString() :
808 _finline ~CYString() {
812 void operator =(const CYString &rhs) {
816 if (rhs.cache_ == nil)
819 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
822 void set(apr_pool_t *pool, const char *data, size_t size) {
828 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
829 memcpy(temp, data, size);
836 _finline void set(apr_pool_t *pool, const char *data) {
837 set(pool, data, data == NULL ? 0 : strlen(data));
840 _finline void set(apr_pool_t *pool, const std::string &rhs) {
841 set(pool, rhs.data(), rhs.size());
844 bool operator ==(const CYString &rhs) const {
845 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
848 operator CFStringRef() {
849 if (cache_ == NULL) {
852 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
854 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
858 _finline operator id() {
859 return (NSString *) static_cast<CFStringRef>(*this);
863 /* C++ NSString Algorithm Adapters {{{ */
865 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
868 struct NSStringMapHash :
869 std::unary_function<NSString *, size_t>
871 _finline size_t operator ()(NSString *value) const {
872 return CFStringHashNSString((CFStringRef) value);
876 struct NSStringMapLess :
877 std::binary_function<NSString *, NSString *, bool>
879 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
880 return [lhs compare:rhs] == NSOrderedAscending;
884 struct NSStringMapEqual :
885 std::binary_function<NSString *, NSString *, bool>
887 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
888 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
889 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
890 //[lhs isEqualToString:rhs];
895 /* Perl-Compatible RegEx {{{ */
905 Pcre(const char *regex) :
910 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
913 lprintf("%d:%s\n", offset, error);
917 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
918 matches_ = new int[(capture_ + 1) * 3];
926 NSString *operator [](size_t match) {
927 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
930 bool operator ()(NSString *data) {
931 // XXX: length is for characters, not for bytes
932 return operator ()([data UTF8String], [data length]);
935 bool operator ()(const char *data, size_t size) {
937 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
941 /* Mime Addresses {{{ */
942 @interface Address : NSObject {
948 - (NSString *) address;
950 - (void) setAddress:(NSString *)address;
952 + (Address *) addressWithString:(NSString *)string;
953 - (Address *) initWithString:(NSString *)string;
956 @implementation Address
965 - (NSString *) name {
969 - (NSString *) address {
973 - (void) setAddress:(NSString *)address {
975 [address_ autorelease];
979 address_ = [address retain];
982 + (Address *) addressWithString:(NSString *)string {
983 return [[[Address alloc] initWithString:string] autorelease];
986 + (NSArray *) _attributeKeys {
987 return [NSArray arrayWithObjects:@"address", @"name", nil];
990 - (NSArray *) attributeKeys {
991 return [[self class] _attributeKeys];
994 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
995 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
998 - (Address *) initWithString:(NSString *)string {
999 if ((self = [super init]) != nil) {
1000 const char *data = [string UTF8String];
1001 size_t size = [string length];
1003 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
1005 if (address_r(data, size)) {
1006 name_ = [address_r[1] retain];
1007 address_ = [address_r[2] retain];
1009 name_ = [string retain];
1017 /* CoreGraphics Primitives {{{ */
1028 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
1031 Set(space, red, green, blue, alpha);
1036 CGColorRelease(color_);
1043 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1045 float color[] = {red, green, blue, alpha};
1046 color_ = CGColorCreate(space, color);
1049 operator CGColorRef() {
1055 /* Random Global Variables {{{ */
1056 static const int PulseInterval_ = 50000;
1057 static const int ButtonBarWidth_ = 60;
1058 static const int ButtonBarHeight_ = 48;
1059 static const float KeyboardTime_ = 0.3f;
1062 static NSArray *Finishes_;
1064 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1065 #define NotifyConfig_ "/etc/notify.conf"
1067 static bool Queuing_;
1069 static CGColor Blue_;
1070 static CGColor Blueish_;
1071 static CGColor Black_;
1072 static CGColor Off_;
1073 static CGColor White_;
1074 static CGColor Gray_;
1075 static CGColor Green_;
1076 static CGColor Purple_;
1077 static CGColor Purplish_;
1079 static UIColor *InstallingColor_;
1080 static UIColor *RemovingColor_;
1082 static NSString *App_;
1083 static NSString *Home_;
1085 static BOOL Advanced_;
1086 static BOOL Ignored_;
1088 static UIFont *Font12_;
1089 static UIFont *Font12Bold_;
1090 static UIFont *Font14_;
1091 static UIFont *Font18Bold_;
1092 static UIFont *Font22Bold_;
1094 static const char *Machine_ = NULL;
1095 static const NSString *System_ = NULL;
1096 static const NSString *SerialNumber_ = nil;
1097 static const NSString *ChipID_ = nil;
1098 static const NSString *Token_ = nil;
1099 static const NSString *UniqueID_ = nil;
1100 static const NSString *Build_ = nil;
1101 static const NSString *Product_ = nil;
1102 static const NSString *Safari_ = nil;
1104 static CFLocaleRef Locale_;
1105 static NSArray *Languages_;
1106 static CGColorSpaceRef space_;
1108 static NSDictionary *SectionMap_;
1109 static NSMutableDictionary *Metadata_;
1110 static _transient NSMutableDictionary *Settings_;
1111 static _transient NSString *Role_;
1112 static _transient NSMutableDictionary *Packages_;
1113 static _transient NSMutableDictionary *Sections_;
1114 static _transient NSMutableDictionary *Sources_;
1115 static bool Changed_;
1116 static NSDate *now_;
1118 static bool IsWildcat_;
1121 static NSMutableArray *Documents_;
1125 /* Display Helpers {{{ */
1126 inline float Interpolate(float begin, float end, float fraction) {
1127 return (end - begin) * fraction + begin;
1130 /* XXX: localize this! */
1131 NSString *SizeString(double size) {
1132 bool negative = size < 0;
1137 while (size > 1024) {
1142 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1144 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1147 static _finline CFStringRef CFCString(const char *value) {
1148 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1151 const char *StripVersion_(const char *version) {
1152 const char *colon(strchr(version, ':'));
1154 version = colon + 1;
1158 CFStringRef StripVersion(const char *version) {
1159 const char *colon(strchr(version, ':'));
1161 version = colon + 1;
1162 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1164 return CFCString(version);
1167 NSString *LocalizeSection(NSString *section) {
1168 static Pcre title_r("^(.*?) \\((.*)\\)$");
1169 if (title_r(section)) {
1170 NSString *parent(title_r[1]);
1171 NSString *child(title_r[2]);
1173 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1174 LocalizeSection(parent),
1175 LocalizeSection(child)
1179 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1182 NSString *Simplify(NSString *title) {
1183 const char *data = [title UTF8String];
1184 size_t size = [title length];
1186 static Pcre square_r("^\\[(.*)\\]$");
1187 if (square_r(data, size))
1188 return Simplify(square_r[1]);
1190 static Pcre paren_r("^\\((.*)\\)$");
1191 if (paren_r(data, size))
1192 return Simplify(paren_r[1]);
1194 static Pcre title_r("^(.*?) \\((.*)\\)$");
1195 if (title_r(data, size))
1196 return Simplify(title_r[1]);
1202 NSString *GetLastUpdate() {
1203 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1206 return UCLocalize("NEVER_OR_UNKNOWN");
1208 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1209 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1211 CFRelease(formatter);
1213 return [(NSString *) formatted autorelease];
1216 bool isSectionVisible(NSString *section) {
1217 NSDictionary *metadata([Sections_ objectForKey:section]);
1218 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1219 return hidden == nil || ![hidden boolValue];
1224 /* Delegate Prototypes {{{ */
1228 @interface NSObject (ProgressDelegate)
1231 @protocol ProgressDelegate
1232 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1233 - (void) setProgressTitle:(NSString *)title;
1234 - (void) setProgressPercent:(float)percent;
1235 - (void) startProgress;
1236 - (void) addProgressOutput:(NSString *)output;
1237 - (bool) isCancelling:(size_t)received;
1240 @protocol ConfigurationDelegate
1241 - (void) repairWithSelector:(SEL)selector;
1242 - (void) setConfigurationData:(NSString *)data;
1245 @class PackageController;
1247 @protocol CydiaDelegate
1248 - (void) setPackageController:(PackageController *)view;
1249 - (void) clearPackage:(Package *)package;
1250 - (void) installPackage:(Package *)package;
1251 - (void) installPackages:(NSArray *)packages;
1252 - (void) removePackage:(Package *)package;
1253 - (void) distUpgrade;
1254 - (void) updateData;
1256 - (void) showSettings;
1257 - (UIProgressHUD *) addProgressHUD;
1258 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1259 - (UIViewController *) pageForPackage:(NSString *)name;
1260 - (PackageController *) packageController;
1264 /* Status Delegation {{{ */
1266 public pkgAcquireStatus
1269 _transient NSObject<ProgressDelegate> *delegate_;
1277 void setDelegate(id delegate) {
1278 delegate_ = delegate;
1281 NSObject<ProgressDelegate> *getDelegate() const {
1285 virtual bool MediaChange(std::string media, std::string drive) {
1289 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1292 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1293 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1294 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1297 virtual void Done(pkgAcquire::ItemDesc &item) {
1300 virtual void Fail(pkgAcquire::ItemDesc &item) {
1302 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1303 item.Owner->Status == pkgAcquire::Item::StatDone
1307 std::string &error(item.Owner->ErrorText);
1311 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1312 NSArray *fields([description componentsSeparatedByString:@" "]);
1313 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1315 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1316 withObject:[NSArray arrayWithObjects:
1317 [NSString stringWithUTF8String:error.c_str()],
1324 virtual bool Pulse(pkgAcquire *Owner) {
1325 bool value = pkgAcquireStatus::Pulse(Owner);
1328 double(CurrentBytes + CurrentItems) /
1329 double(TotalBytes + TotalItems)
1332 [delegate_ setProgressPercent:percent];
1333 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1336 virtual void Start() {
1337 [delegate_ startProgress];
1340 virtual void Stop() {
1344 /* Progress Delegation {{{ */
1349 _transient id<ProgressDelegate> delegate_;
1353 virtual void Update() {
1354 /*if (abs(Percent - percent_) > 2)
1355 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1359 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1360 [delegate_ setProgressPercent:(Percent / 100)];*/
1370 void setDelegate(id delegate) {
1371 delegate_ = delegate;
1374 id getDelegate() const {
1378 virtual void Done() {
1380 //[delegate_ setProgressPercent:1];
1385 /* Database Interface {{{ */
1386 typedef std::map< unsigned long, _H<Source> > SourceMap;
1388 @interface Database : NSObject {
1394 pkgCacheFile cache_;
1395 pkgDepCache::Policy *policy_;
1396 pkgRecords *records_;
1397 pkgProblemResolver *resolver_;
1398 pkgAcquire *fetcher_;
1400 SPtr<pkgPackageManager> manager_;
1401 pkgSourceList *list_;
1404 NSMutableArray *packages_;
1406 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1415 + (Database *) sharedInstance;
1418 - (void) _readCydia:(NSNumber *)fd;
1419 - (void) _readStatus:(NSNumber *)fd;
1420 - (void) _readOutput:(NSNumber *)fd;
1424 - (Package *) packageWithName:(NSString *)name;
1426 - (pkgCacheFile &) cache;
1427 - (pkgDepCache::Policy *) policy;
1428 - (pkgRecords *) records;
1429 - (pkgProblemResolver *) resolver;
1430 - (pkgAcquire &) fetcher;
1431 - (pkgSourceList &) list;
1432 - (NSArray *) packages;
1433 - (NSArray *) sources;
1434 - (void) reloadData;
1442 - (void) setVisible;
1444 - (void) updateWithStatus:(Status &)status;
1446 - (void) setDelegate:(id)delegate;
1447 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1450 /* Delegate Helpers {{{ */
1451 @implementation NSObject(ProgressDelegate)
1453 - (void) _setProgressErrorPackage:(NSArray *)args {
1454 [self performSelector:@selector(setProgressError:forPackage:)
1455 withObject:[args objectAtIndex:0]
1456 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1460 - (void) _setProgressErrorTitle:(NSArray *)args {
1461 [self performSelector:@selector(setProgressError:withTitle:)
1462 withObject:[args objectAtIndex:0]
1463 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1467 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1468 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1469 withObject:[NSArray arrayWithObjects:error, title, nil]
1474 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1475 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1476 // XXX: holy typecast batman!
1477 [self setProgressError:error withTitle:(package == nil ? id : [package name])];
1483 /* Source Class {{{ */
1484 @interface Source : NSObject {
1485 CYString depiction_;
1486 CYString description_;
1492 CYString distribution_;
1497 NSString *authority_;
1499 CYString defaultIcon_;
1501 NSDictionary *record_;
1505 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1507 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1509 - (NSString *) depictionForPackage:(NSString *)package;
1510 - (NSString *) supportForPackage:(NSString *)package;
1512 - (NSDictionary *) record;
1516 - (NSString *) distribution;
1517 - (NSString *) type;
1519 - (NSString *) host;
1521 - (NSString *) name;
1522 - (NSString *) description;
1523 - (NSString *) label;
1524 - (NSString *) origin;
1525 - (NSString *) version;
1527 - (NSString *) defaultIcon;
1531 @implementation Source
1535 distribution_.clear();
1538 description_.clear();
1544 defaultIcon_.clear();
1546 if (record_ != nil) {
1556 if (authority_ != nil) {
1557 [authority_ release];
1567 + (NSArray *) _attributeKeys {
1568 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1571 - (NSArray *) attributeKeys {
1572 return [[self class] _attributeKeys];
1575 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1576 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1579 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1582 trusted_ = index->IsTrusted();
1584 uri_.set(pool, index->GetURI());
1585 distribution_.set(pool, index->GetDist());
1586 type_.set(pool, index->GetType());
1588 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1589 if (dindex != NULL) {
1591 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1594 pkgTagFile tags(&fd);
1596 pkgTagSection section;
1603 {"default-icon", &defaultIcon_},
1604 {"depiction", &depiction_},
1605 {"description", &description_},
1607 {"origin", &origin_},
1608 {"support", &support_},
1609 {"version", &version_},
1612 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1613 const char *start, *end;
1615 if (section.Find(names[i].name_, start, end)) {
1616 CYString &value(*names[i].value_);
1617 value.set(pool, start, end - start);
1623 record_ = [Sources_ objectForKey:[self key]];
1625 record_ = [record_ retain];
1627 NSURL *url([NSURL URLWithString:uri_]);
1631 host_ = [[host_ lowercaseString] retain];
1636 authority_ = [url path];
1638 if (authority_ != nil)
1639 authority_ = [authority_ retain];
1642 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1643 if ((self = [super init]) != nil) {
1644 [self setMetaIndex:index inPool:pool];
1648 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1649 NSDictionary *lhr = [self record];
1650 NSDictionary *rhr = [source record];
1653 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1655 NSString *lhs = [self name];
1656 NSString *rhs = [source name];
1658 if ([lhs length] != 0 && [rhs length] != 0) {
1659 unichar lhc = [lhs characterAtIndex:0];
1660 unichar rhc = [rhs characterAtIndex:0];
1662 if (isalpha(lhc) && !isalpha(rhc))
1663 return NSOrderedAscending;
1664 else if (!isalpha(lhc) && isalpha(rhc))
1665 return NSOrderedDescending;
1668 return [lhs compare:rhs options:LaxCompareOptions_];
1671 - (NSString *) depictionForPackage:(NSString *)package {
1672 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1675 - (NSString *) supportForPackage:(NSString *)package {
1676 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1679 - (NSDictionary *) record {
1687 - (NSString *) uri {
1691 - (NSString *) distribution {
1692 return distribution_;
1695 - (NSString *) type {
1699 - (NSString *) key {
1700 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1703 - (NSString *) host {
1707 - (NSString *) name {
1708 return origin_.empty() ? authority_ : origin_;
1711 - (NSString *) description {
1712 return description_;
1715 - (NSString *) label {
1716 return label_.empty() ? authority_ : label_;
1719 - (NSString *) origin {
1723 - (NSString *) version {
1727 - (NSString *) defaultIcon {
1728 return defaultIcon_;
1733 /* Relationship Class {{{ */
1734 @interface Relationship : NSObject {
1739 - (NSString *) type;
1741 - (NSString *) name;
1745 @implementation Relationship
1753 - (NSString *) type {
1761 - (NSString *) name {
1768 /* Package Class {{{ */
1769 @interface Package : NSObject {
1773 pkgCache::VerIterator version_;
1774 pkgCache::PkgIterator iterator_;
1775 _transient Database *database_;
1776 pkgCache::VerFileIterator file_;
1783 NSString *section$_;
1790 CYString installed_;
1796 CYString depiction_;
1807 NSMutableArray *tags_;
1810 NSArray *relationships_;
1812 NSMutableDictionary *metadata_;
1813 _transient NSDate *firstSeen_;
1814 _transient NSDate *lastSeen_;
1818 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1819 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1821 - (pkgCache::PkgIterator) iterator;
1824 - (NSString *) section;
1825 - (NSString *) simpleSection;
1827 - (NSString *) longSection;
1828 - (NSString *) shortSection;
1832 - (Address *) maintainer;
1834 - (NSString *) longDescription;
1835 - (NSString *) shortDescription;
1838 - (NSMutableDictionary *) metadata;
1840 - (BOOL) subscribed;
1843 - (NSString *) latest;
1844 - (NSString *) installed;
1845 - (BOOL) uninstalled;
1848 - (BOOL) upgradableAndEssential:(BOOL)essential;
1851 - (BOOL) unfiltered;
1855 - (BOOL) halfConfigured;
1856 - (BOOL) halfInstalled;
1858 - (NSString *) mode;
1860 - (void) setVisible;
1863 - (NSString *) name;
1865 - (NSString *) homepage;
1866 - (NSString *) depiction;
1867 - (Address *) author;
1869 - (NSString *) support;
1871 - (NSArray *) files;
1872 - (NSArray *) relationships;
1873 - (NSArray *) warnings;
1874 - (NSArray *) applications;
1876 - (Source *) source;
1877 - (NSString *) role;
1879 - (BOOL) matches:(NSString *)text;
1881 - (bool) hasSupportingRole;
1882 - (BOOL) hasTag:(NSString *)tag;
1883 - (NSString *) primaryPurpose;
1884 - (NSArray *) purposes;
1885 - (bool) isCommercial;
1887 - (CYString &) cyname;
1889 - (uint32_t) compareBySection:(NSArray *)sections;
1891 - (uint32_t) compareForChanges;
1896 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1897 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1898 - (bool) isInstalledAndVisible:(NSNumber *)number;
1899 - (bool) isVisibleInSection:(NSString *)section;
1900 - (bool) isVisibleInSource:(Source *)source;
1904 uint32_t PackageChangesRadix(Package *self, void *) {
1909 uint32_t timestamp : 30;
1910 uint32_t ignored : 1;
1911 uint32_t upgradable : 1;
1915 bool upgradable([self upgradableAndEssential:YES]);
1916 value.bits.upgradable = upgradable ? 1 : 0;
1919 value.bits.timestamp = 0;
1920 value.bits.ignored = [self ignored] ? 0 : 1;
1921 value.bits.upgradable = 1;
1923 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1924 value.bits.ignored = 0;
1925 value.bits.upgradable = 0;
1928 return _not(uint32_t) - value.key;
1931 _finline static void Stifle(uint8_t &value) {
1934 uint32_t PackagePrefixRadix(Package *self, void *context) {
1935 size_t offset(reinterpret_cast<size_t>(context));
1936 CYString &name([self cyname]);
1938 size_t size(name.size());
1941 char *text(name.data());
1944 if (!isdigit(text[0]))
1948 while (size != digits && isdigit(text[digits]))
1958 if (offset == 0 && zeros != 0) {
1959 memset(data, '0', zeros);
1960 memcpy(data + zeros, text, 4 - zeros);
1962 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1963 if (size <= offset - zeros)
1966 text += offset - zeros;
1967 size -= offset - zeros;
1970 memcpy(data, text, 4);
1972 memcpy(data, text, size);
1973 memset(data + size, 0, 4 - size);
1976 for (size_t i(0); i != 4; ++i)
1977 if (isalpha(data[i]))
1982 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1984 /* XXX: ntohl may be more honest */
1985 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1988 CYString &(*PackageName)(Package *self, SEL sel);
1990 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1991 _profile(PackageNameCompare)
1992 CYString &lhi(PackageName(lhs, @selector(cyname)));
1993 CYString &rhi(PackageName(rhs, @selector(cyname)));
1994 CFStringRef lhn(lhi), rhn(rhi);
1997 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1998 else if (rhn == NULL)
1999 return NSOrderedDescending;
2001 _profile(PackageNameCompare$NumbersLast)
2002 if (!lhi.empty() && !rhi.empty()) {
2003 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2004 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2005 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2006 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2007 return lha ? NSOrderedAscending : NSOrderedDescending;
2011 CFIndex length = CFStringGetLength(lhn);
2013 _profile(PackageNameCompare$Compare)
2014 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2019 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2020 return PackageNameCompare(*lhs, *rhs, context);
2023 struct PackageNameOrdering :
2024 std::binary_function<Package *, Package *, bool>
2026 _finline bool operator ()(Package *lhs, Package *rhs) const {
2027 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2031 @implementation Package
2033 - (NSString *) description {
2034 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2040 if (section$_ != nil)
2041 [section$_ release];
2046 if (sponsor$_ != nil)
2047 [sponsor$_ release];
2048 if (author$_ != nil)
2055 if (relationships_ != nil)
2056 [relationships_ release];
2057 if (metadata_ != nil)
2058 [metadata_ release];
2063 + (NSString *) webScriptNameForSelector:(SEL)selector {
2064 if (selector == @selector(hasTag:))
2070 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2071 return [self webScriptNameForSelector:selector] == nil;
2074 + (NSArray *) _attributeKeys {
2075 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];
2078 - (NSArray *) attributeKeys {
2079 return [[self class] _attributeKeys];
2082 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2083 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2093 _profile(Package$parse)
2094 pkgRecords::Parser *parser;
2096 _profile(Package$parse$Lookup)
2097 parser = &[database_ records]->Lookup(file_);
2102 _profile(Package$parse$Find)
2108 {"depiction", &depiction_},
2109 {"homepage", &homepage_},
2110 {"website", &website},
2112 {"support", &support_},
2113 {"sponsor", &sponsor_},
2114 {"author", &author_},
2117 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2118 const char *start, *end;
2120 if (parser->Find(names[i].name_, start, end)) {
2121 CYString &value(*names[i].value_);
2122 _profile(Package$parse$Value)
2123 value.set(pool_, start, end - start);
2129 _profile(Package$parse$Tagline)
2130 const char *start, *end;
2131 if (parser->ShortDesc(start, end)) {
2132 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2135 while (stop != start && stop[-1] == '\r')
2137 tagline_.set(pool_, start, stop - start);
2141 _profile(Package$parse$Retain)
2142 if (homepage_.empty())
2143 homepage_ = website;
2144 if (homepage_ == depiction_)
2150 - (void) setVisible {
2151 visible_ = required_ && [self unfiltered];
2154 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2155 if ((self = [super init]) != nil) {
2156 _profile(Package$initWithVersion)
2157 @synchronized (database) {
2158 era_ = [database era];
2162 iterator_ = version.ParentPkg();
2163 database_ = database;
2165 _profile(Package$initWithVersion$Latest)
2166 latest_ = (NSString *) StripVersion(version_.VerStr());
2169 pkgCache::VerIterator current;
2170 _profile(Package$initWithVersion$Versions)
2171 current = iterator_.CurrentVer();
2173 installed_.set(pool_, StripVersion_(current.VerStr()));
2175 if (!version_.end())
2176 file_ = version_.FileList();
2178 pkgCache &cache([database_ cache]);
2179 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2183 _profile(Package$initWithVersion$Name)
2184 id_.set(pool_, iterator_.Name());
2185 name_.set(pool, iterator_.Display());
2189 _profile(Package$initWithVersion$Source)
2190 source_ = [database_ getSource:file_.File()];
2199 _profile(Package$initWithVersion$Tags)
2200 pkgCache::TagIterator tag(iterator_.TagList());
2202 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2204 const char *name(tag.Name());
2205 [tags_ addObject:(NSString *)CFCString(name)];
2206 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2207 role_ = (NSString *) CFCString(name + 6);
2208 if (required_ && strncmp(name, "require::", 9) == 0 && (
2213 } while (!tag.end());
2217 bool changed(false);
2218 NSString *key([id_ lowercaseString]);
2220 _profile(Package$initWithVersion$Metadata)
2221 metadata_ = [Packages_ objectForKey:key];
2223 if (metadata_ == nil) {
2226 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2227 firstSeen_, @"FirstSeen",
2228 latest_, @"LastVersion",
2233 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2234 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2236 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2237 subscribed_ = [subscribed boolValue];
2239 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2241 if (firstSeen_ == nil) {
2242 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2243 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2247 if (version == nil) {
2248 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2250 } else if (![version isEqualToString:latest_]) {
2251 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2253 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2258 metadata_ = [metadata_ retain];
2261 [Packages_ setObject:metadata_ forKey:key];
2266 _profile(Package$initWithVersion$Section)
2267 section_.set(pool_, iterator_.Section());
2270 obsolete_ = [self hasTag:@"cydia::obsolete"];
2271 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2273 } _end } return self;
2276 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2277 @synchronized ([Database class]) {
2278 pkgCache::VerIterator version;
2280 _profile(Package$packageWithIterator$GetCandidateVer)
2281 version = [database policy]->GetCandidateVer(iterator);
2287 return [[[Package alloc]
2288 initWithVersion:version
2295 - (pkgCache::PkgIterator) iterator {
2299 - (NSString *) section {
2300 if (section$_ == nil) {
2301 if (section_.empty())
2304 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2305 NSString *name(section_);
2308 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2309 if (NSString *rename = [value objectForKey:@"Rename"]) {
2314 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2318 - (NSString *) simpleSection {
2319 if (NSString *section = [self section])
2320 return Simplify(section);
2325 - (NSString *) longSection {
2326 return LocalizeSection([self section]);
2329 - (NSString *) shortSection {
2330 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2333 - (NSString *) uri {
2336 pkgIndexFile *index;
2337 pkgCache::PkgFileIterator file(file_.File());
2338 if (![database_ list].FindIndex(file, index))
2340 return [NSString stringWithUTF8String:iterator_->Path];
2341 //return [NSString stringWithUTF8String:file.Site()];
2342 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2346 - (Address *) maintainer {
2349 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2350 const std::string &maintainer(parser->Maintainer());
2351 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2355 return version_.end() ? 0 : version_->InstalledSize;
2358 - (NSString *) longDescription {
2361 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2362 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2364 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2365 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2366 if ([lines count] < 2)
2369 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2370 for (size_t i(1), e([lines count]); i != e; ++i) {
2371 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2372 [trimmed addObject:trim];
2375 return [trimmed componentsJoinedByString:@"\n"];
2378 - (NSString *) shortDescription {
2383 _profile(Package$index)
2384 CFStringRef name((CFStringRef) [self name]);
2385 if (CFStringGetLength(name) == 0)
2387 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2388 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2390 return toupper(character);
2394 - (NSMutableDictionary *) metadata {
2399 if (subscribed_ && lastSeen_ != nil)
2404 - (BOOL) subscribed {
2409 NSDictionary *metadata([self metadata]);
2410 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2411 return [ignored boolValue];
2416 - (NSString *) latest {
2420 - (NSString *) installed {
2424 - (BOOL) uninstalled {
2425 return installed_.empty();
2429 return !version_.end();
2432 - (BOOL) upgradableAndEssential:(BOOL)essential {
2433 _profile(Package$upgradableAndEssential)
2434 pkgCache::VerIterator current(iterator_.CurrentVer());
2436 return essential && essential_ && visible_;
2438 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2442 - (BOOL) essential {
2447 return [database_ cache][iterator_].InstBroken();
2450 - (BOOL) unfiltered {
2451 NSString *section([self section]);
2452 return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
2460 unsigned char current(iterator_->CurrentState);
2461 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2464 - (BOOL) halfConfigured {
2465 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2468 - (BOOL) halfInstalled {
2469 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2473 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2474 return state.Mode != pkgDepCache::ModeKeep;
2477 - (NSString *) mode {
2478 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2480 switch (state.Mode) {
2481 case pkgDepCache::ModeDelete:
2482 if ((state.iFlags & pkgDepCache::Purge) != 0)
2486 case pkgDepCache::ModeKeep:
2487 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2488 return @"REINSTALL";
2489 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2493 case pkgDepCache::ModeInstall:
2494 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2495 return @"REINSTALL";
2496 else*/ switch (state.Status) {
2498 return @"DOWNGRADE";
2504 return @"NEW_INSTALL";
2515 - (NSString *) name {
2516 return name_.empty() ? id_ : name_;
2519 - (UIImage *) icon {
2520 NSString *section = [self simpleSection];
2524 if ([icon_ hasPrefix:@"file:///"])
2525 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2526 if (icon == nil) if (section != nil)
2527 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2528 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2529 if ([dicon hasPrefix:@"file:///"])
2530 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2532 icon = [UIImage applicationImageNamed:@"unknown.png"];
2536 - (NSString *) homepage {
2540 - (NSString *) depiction {
2541 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2544 - (Address *) sponsor {
2545 if (sponsor$_ == nil) {
2546 if (sponsor_.empty())
2548 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2552 - (Address *) author {
2553 if (author$_ == nil) {
2554 if (author_.empty())
2556 author$_ = [[Address addressWithString:author_] retain];
2560 - (NSString *) support {
2561 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2564 - (NSArray *) files {
2565 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2566 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2569 fin.open([path UTF8String]);
2574 while (std::getline(fin, line))
2575 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2580 - (NSArray *) relationships {
2581 return relationships_;
2584 - (NSArray *) warnings {
2585 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2586 const char *name(iterator_.Name());
2588 size_t length(strlen(name));
2589 if (length < 2) invalid:
2590 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2591 else for (size_t i(0); i != length; ++i)
2593 /* XXX: technically this is not allowed */
2594 (name[i] < 'A' || name[i] > 'Z') &&
2595 (name[i] < 'a' || name[i] > 'z') &&
2596 (name[i] < '0' || name[i] > '9') &&
2597 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2600 if (strcmp(name, "cydia") != 0) {
2603 bool _private = false;
2606 bool repository = [[self section] isEqualToString:@"Repositories"];
2608 if (NSArray *files = [self files])
2609 for (NSString *file in files)
2610 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2612 else if (!user && [file isEqualToString:@"/User"])
2614 else if (!_private && [file isEqualToString:@"/private"])
2616 else if (!stash && [file isEqualToString:@"/var/stash"])
2619 /* XXX: this is not sensitive enough. only some folders are valid. */
2620 if (cydia && !repository)
2621 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2623 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2625 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2627 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2630 return [warnings count] == 0 ? nil : warnings;
2633 - (NSArray *) applications {
2634 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2636 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2638 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2639 if (NSArray *files = [self files])
2640 for (NSString *file in files)
2641 if (application_r(file)) {
2642 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2643 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2644 if ([id isEqualToString:me])
2647 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2649 display = application_r[1];
2651 NSString *bundle([file stringByDeletingLastPathComponent]);
2652 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2653 if (icon == nil || [icon length] == 0)
2655 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2657 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2658 [applications addObject:application];
2660 [application addObject:id];
2661 [application addObject:display];
2662 [application addObject:url];
2665 return [applications count] == 0 ? nil : applications;
2668 - (Source *) source {
2670 @synchronized (database_) {
2671 if ([database_ era] != era_ || file_.end())
2674 source_ = [database_ getSource:file_.File()];
2686 - (NSString *) role {
2690 - (BOOL) matches:(NSString *)text {
2696 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2697 if (range.location != NSNotFound)
2700 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2701 if (range.location != NSNotFound)
2704 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2705 if (range.location != NSNotFound)
2711 - (bool) hasSupportingRole {
2714 if ([role_ isEqualToString:@"enduser"])
2716 if ([Role_ isEqualToString:@"User"])
2718 if ([role_ isEqualToString:@"hacker"])
2720 if ([Role_ isEqualToString:@"Hacker"])
2722 if ([role_ isEqualToString:@"developer"])
2724 if ([Role_ isEqualToString:@"Developer"])
2729 - (BOOL) hasTag:(NSString *)tag {
2730 return tags_ == nil ? NO : [tags_ containsObject:tag];
2733 - (NSString *) primaryPurpose {
2734 for (NSString *tag in tags_)
2735 if ([tag hasPrefix:@"purpose::"])
2736 return [tag substringFromIndex:9];
2740 - (NSArray *) purposes {
2741 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2742 for (NSString *tag in tags_)
2743 if ([tag hasPrefix:@"purpose::"])
2744 [purposes addObject:[tag substringFromIndex:9]];
2745 return [purposes count] == 0 ? nil : purposes;
2748 - (bool) isCommercial {
2749 return [self hasTag:@"cydia::commercial"];
2752 - (CYString &) cyname {
2753 return name_.empty() ? id_ : name_;
2756 - (uint32_t) compareBySection:(NSArray *)sections {
2757 NSString *section([self section]);
2758 for (size_t i(0), e([sections count]); i != e; ++i) {
2759 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2763 return _not(uint32_t);
2766 - (uint32_t) compareForChanges {
2771 uint32_t timestamp : 30;
2772 uint32_t ignored : 1;
2773 uint32_t upgradable : 1;
2777 bool upgradable([self upgradableAndEssential:YES]);
2778 value.bits.upgradable = upgradable ? 1 : 0;
2781 value.bits.timestamp = 0;
2782 value.bits.ignored = [self ignored] ? 0 : 1;
2783 value.bits.upgradable = 1;
2785 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2786 value.bits.ignored = 0;
2787 value.bits.upgradable = 0;
2790 return _not(uint32_t) - value.key;
2794 pkgProblemResolver *resolver = [database_ resolver];
2795 resolver->Clear(iterator_);
2796 resolver->Protect(iterator_);
2800 pkgProblemResolver *resolver = [database_ resolver];
2801 resolver->Clear(iterator_);
2802 resolver->Protect(iterator_);
2803 pkgCacheFile &cache([database_ cache]);
2804 cache->MarkInstall(iterator_, false);
2805 pkgDepCache::StateCache &state((*cache)[iterator_]);
2806 if (!state.Install())
2807 cache->SetReInstall(iterator_, true);
2811 pkgProblemResolver *resolver = [database_ resolver];
2812 resolver->Clear(iterator_);
2813 resolver->Protect(iterator_);
2814 resolver->Remove(iterator_);
2815 [database_ cache]->MarkDelete(iterator_, true);
2818 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2819 _profile(Package$isUnfilteredAndSearchedForBy)
2822 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2823 value &= [self unfiltered];
2826 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2827 value &= [self matches:search];
2834 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2835 if ([search length] == 0)
2838 _profile(Package$isUnfilteredAndSelectedForBy)
2841 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2842 value &= [self unfiltered];
2845 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2846 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2853 - (bool) isInstalledAndVisible:(NSNumber *)number {
2854 return (![number boolValue] || [self visible]) && ![self uninstalled];
2857 - (bool) isVisibleInSection:(NSString *)name {
2858 NSString *section = [self section];
2863 section == nil && [name length] == 0 ||
2864 [name isEqualToString:section]
2868 - (bool) isVisibleInSource:(Source *)source {
2869 return [self source] == source && [self visible];
2874 /* Section Class {{{ */
2875 @interface Section : NSObject {
2880 NSString *localized_;
2883 - (NSComparisonResult) compareByLocalized:(Section *)section;
2884 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2885 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2886 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2887 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2888 - (NSString *) name;
2895 - (void) addToCount;
2897 - (void) setCount:(size_t)count;
2898 - (NSString *) localized;
2902 @implementation Section
2906 if (localized_ != nil)
2907 [localized_ release];
2911 - (NSComparisonResult) compareByLocalized:(Section *)section {
2912 NSString *lhs(localized_);
2913 NSString *rhs([section localized]);
2915 /*if ([lhs length] != 0 && [rhs length] != 0) {
2916 unichar lhc = [lhs characterAtIndex:0];
2917 unichar rhc = [rhs characterAtIndex:0];
2919 if (isalpha(lhc) && !isalpha(rhc))
2920 return NSOrderedAscending;
2921 else if (!isalpha(lhc) && isalpha(rhc))
2922 return NSOrderedDescending;
2925 return [lhs compare:rhs options:LaxCompareOptions_];
2928 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2929 if ((self = [self initWithName:name localize:NO]) != nil) {
2930 if (localized != nil)
2931 localized_ = [localized retain];
2935 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2936 return [self initWithName:name row:0 localize:localize];
2939 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2940 if ((self = [super init]) != nil) {
2941 name_ = [name retain];
2945 localized_ = [LocalizeSection(name_) retain];
2949 /* XXX: localize the index thingees */
2950 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2951 if ((self = [super init]) != nil) {
2952 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2958 - (NSString *) name {
2978 - (void) addToCount {
2982 - (void) setCount:(size_t)count {
2986 - (NSString *) localized {
2993 static NSString *Colon_;
2994 static NSString *Error_;
2995 static NSString *Warning_;
2997 /* Database Implementation {{{ */
2998 @implementation Database
3000 + (Database *) sharedInstance {
3001 static Database *instance;
3002 if (instance == nil)
3003 instance = [[Database alloc] init];
3013 NSRecycleZone(zone_);
3014 // XXX: malloc_destroy_zone(zone_);
3015 apr_pool_destroy(pool_);
3019 - (void) _readCydia:(NSNumber *)fd { _pooled
3020 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3021 std::istream is(&ib);
3024 static Pcre finish_r("^finish:([^:]*)$");
3026 while (std::getline(is, line)) {
3027 const char *data(line.c_str());
3028 size_t size = line.size();
3029 lprintf("C:%s\n", data);
3031 if (finish_r(data, size)) {
3032 NSString *finish = finish_r[1];
3033 int index = [Finishes_ indexOfObject:finish];
3034 if (index != INT_MAX && index > Finish_)
3042 - (void) _readStatus:(NSNumber *)fd { _pooled
3043 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3044 std::istream is(&ib);
3047 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3048 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3050 while (std::getline(is, line)) {
3051 const char *data(line.c_str());
3052 size_t size(line.size());
3053 lprintf("S:%s\n", data);
3055 if (conffile_r(data, size)) {
3056 [delegate_ setConfigurationData:conffile_r[1]];
3057 } else if (strncmp(data, "status: ", 8) == 0) {
3058 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3059 [delegate_ setProgressTitle:string];
3060 } else if (pmstatus_r(data, size)) {
3061 std::string type([pmstatus_r[1] UTF8String]);
3062 NSString *id = pmstatus_r[2];
3064 float percent([pmstatus_r[3] floatValue]);
3065 [delegate_ setProgressPercent:(percent / 100)];
3067 NSString *string = pmstatus_r[4];
3069 if (type == "pmerror")
3070 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3071 withObject:[NSArray arrayWithObjects:string, id, nil]
3074 else if (type == "pmstatus") {
3075 [delegate_ setProgressTitle:string];
3076 } else if (type == "pmconffile")
3077 [delegate_ setConfigurationData:string];
3079 lprintf("E:unknown pmstatus\n");
3081 lprintf("E:unknown status\n");
3087 - (void) _readOutput:(NSNumber *)fd { _pooled
3088 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3089 std::istream is(&ib);
3092 while (std::getline(is, line)) {
3093 lprintf("O:%s\n", line.c_str());
3094 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3104 - (Package *) packageWithName:(NSString *)name {
3105 @synchronized ([Database class]) {
3106 if (static_cast<pkgDepCache *>(cache_) == NULL)
3108 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3109 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3112 - (Database *) init {
3113 if ((self = [super init]) != nil) {
3120 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3121 apr_pool_create(&pool_, NULL);
3123 packages_ = [[NSMutableArray alloc] init];
3127 _assert(pipe(fds) != -1);
3130 _config->Set("APT::Keep-Fds::", cydiafd_);
3131 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3134 detachNewThreadSelector:@selector(_readCydia:)
3136 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3139 _assert(pipe(fds) != -1);
3143 detachNewThreadSelector:@selector(_readStatus:)
3145 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3148 _assert(pipe(fds) != -1);
3149 _assert(dup2(fds[0], 0) != -1);
3150 _assert(close(fds[0]) != -1);
3152 input_ = fdopen(fds[1], "a");
3154 _assert(pipe(fds) != -1);
3155 _assert(dup2(fds[1], 1) != -1);
3156 _assert(close(fds[1]) != -1);
3159 detachNewThreadSelector:@selector(_readOutput:)
3161 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3166 - (pkgCacheFile &) cache {
3170 - (pkgDepCache::Policy *) policy {
3174 - (pkgRecords *) records {
3178 - (pkgProblemResolver *) resolver {
3182 - (pkgAcquire &) fetcher {
3186 - (pkgSourceList &) list {
3190 - (NSArray *) packages {
3194 - (NSArray *) sources {
3195 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3196 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3197 [sources addObject:i->second];
3201 - (NSArray *) issues {
3202 if (cache_->BrokenCount() == 0)
3205 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3207 for (Package *package in packages_) {
3208 if (![package broken])
3210 pkgCache::PkgIterator pkg([package iterator]);
3212 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3213 [entry addObject:[package name]];
3214 [issues addObject:entry];
3216 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3220 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3221 pkgCache::DepIterator start;
3222 pkgCache::DepIterator end;
3223 dep.GlobOr(start, end); // ++dep
3225 if (!cache_->IsImportantDep(end))
3227 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3230 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3231 [entry addObject:failure];
3232 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3234 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3235 if (Package *package = [self packageWithName:name])
3236 name = [package name];
3237 [failure addObject:name];
3239 pkgCache::PkgIterator target(start.TargetPkg());
3240 if (target->ProvidesList != 0)
3241 [failure addObject:@"?"];
3243 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3245 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3246 else if (!cache_[target].CandidateVerIter(cache_).end())
3247 [failure addObject:@"-"];
3248 else if (target->ProvidesList == 0)
3249 [failure addObject:@"!"];
3251 [failure addObject:@"%"];
3255 if (start.TargetVer() != 0)
3256 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3267 - (bool) popErrorWithTitle:(NSString *)title {
3269 std::string message;
3271 while (!_error->empty()) {
3273 bool warning(!_error->PopMessage(error));
3277 size_t size(error.size());
3278 if (size == 0 || error[size - 1] != '\n')
3280 error.resize(size - 1);
3282 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3284 if (!message.empty())
3289 if (fatal && !message.empty())
3290 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3295 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3296 return [self popErrorWithTitle:title] || !success;
3299 - (void) reloadData { _pooled
3300 @synchronized ([Database class]) {
3301 @synchronized (self) {
3305 [packages_ removeAllObjects];
3331 apr_pool_clear(pool_);
3332 NSRecycleZone(zone_);
3334 int chk(creat("/tmp/cydia.chk", 0644));
3338 NSString *title(UCLocalize("DATABASE"));
3341 if (!cache_.Open(progress_, true)) { pop:
3343 bool warning(!_error->PopMessage(error));
3344 lprintf("cache_.Open():[%s]\n", error.c_str());
3346 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3347 [delegate_ repairWithSelector:@selector(configure)];
3348 else if (error == "The package lists or status file could not be parsed or opened.")
3349 [delegate_ repairWithSelector:@selector(update)];
3350 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3351 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3352 // else if (error == "The list of sources could not be read.")
3354 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3363 unlink("/tmp/cydia.chk");
3365 now_ = [[NSDate date] retain];
3367 policy_ = new pkgDepCache::Policy();
3368 records_ = new pkgRecords(cache_);
3369 resolver_ = new pkgProblemResolver(cache_);
3370 fetcher_ = new pkgAcquire(&status_);
3373 list_ = new pkgSourceList();
3374 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3377 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3378 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3382 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3385 if (cache_->BrokenCount() != 0) {
3386 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3389 if (cache_->BrokenCount() != 0) {
3390 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3394 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3400 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3401 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3402 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3403 // XXX: this could be more intelligent
3404 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3405 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3407 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3414 /*std::vector<Package *> packages;
3415 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3416 [packages_ release];
3421 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3422 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3423 //packages.push_back(package);
3424 [packages_ addObject:package];
3428 /*if (packages.empty())
3429 packages_ = [[NSArray alloc] init];
3431 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3434 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3435 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3436 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3444 /*if (!packages.empty())
3445 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3446 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3448 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3450 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3452 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3458 - (void) configure {
3459 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3460 system([dpkg UTF8String]);
3464 // XXX: I don't remember this condition
3469 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3471 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3473 if ([self popErrorWithTitle:title])
3477 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3480 public pkgArchiveCleaner
3483 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3488 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3495 fetcher_->Shutdown();
3497 pkgRecords records(cache_);
3499 lock_ = new FileFd();
3500 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3502 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3504 if ([self popErrorWithTitle:title])
3508 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3511 manager_ = (_system->CreatePM(cache_));
3512 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3519 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3521 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3523 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3525 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3526 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3529 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3534 bool failed = false;
3535 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3536 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3538 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3541 std::string uri = (*item)->DescURI();
3542 std::string error = (*item)->ErrorText;
3544 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3547 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3548 withObject:[NSArray arrayWithObjects:
3549 [NSString stringWithUTF8String:error.c_str()],
3561 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3563 if (_error->PendingError()) {
3568 if (result == pkgPackageManager::Failed) {
3573 if (result != pkgPackageManager::Completed) {
3578 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3580 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3582 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3583 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3586 if (![before isEqualToArray:after])
3591 NSString *title(UCLocalize("UPGRADE"));
3592 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3598 [self updateWithStatus:status_];
3601 - (void) setVisible {
3602 for (Package *package in packages_)
3603 [package setVisible];
3606 - (void) updateWithStatus:(Status &)status {
3607 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3608 NSString *title(UCLocalize("REFRESHING_DATA"));
3611 if (!list.ReadMainList())
3612 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3615 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3616 if ([self popErrorWithTitle:title])
3619 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3620 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */;
3622 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3626 - (void) setDelegate:(id)delegate {
3627 delegate_ = delegate;
3628 status_.setDelegate(delegate);
3629 progress_.setDelegate(delegate);
3632 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3633 SourceMap::const_iterator i(sources_.find(file->ID));
3634 return i == sources_.end() ? nil : i->second;
3640 /* Confirmation Controller {{{ */
3641 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3642 if (!iterator.end())
3643 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3644 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3646 pkgCache::PkgIterator package(dep.TargetPkg());
3649 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3657 /* Web Scripting {{{ */
3658 @interface CydiaObject : NSObject {
3663 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3666 @implementation CydiaObject
3669 [indirect_ release];
3673 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3674 if ((self = [super init]) != nil) {
3675 indirect_ = [indirect retain];
3679 - (void) setDelegate:(id)delegate {
3680 delegate_ = delegate;
3683 + (NSArray *) _attributeKeys {
3684 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3687 - (NSArray *) attributeKeys {
3688 return [[self class] _attributeKeys];
3691 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3692 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3695 - (NSString *) device {
3696 return [[UIDevice currentDevice] uniqueIdentifier];
3699 #if 0 // XXX: implement!
3700 - (NSString *) mac {
3701 if (![indirect_ promptForSensitive:@"Mac Address"])
3705 - (NSString *) serial {
3706 if (![indirect_ promptForSensitive:@"Serial #"])
3710 - (NSString *) firewire {
3711 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3715 - (NSString *) imei {
3716 if (![indirect_ promptForSensitive:@"IMEI"])
3721 + (NSString *) webScriptNameForSelector:(SEL)selector {
3722 if (selector == @selector(close))
3724 else if (selector == @selector(getInstalledPackages))
3725 return @"getInstalledPackages";
3726 else if (selector == @selector(getPackageById:))
3727 return @"getPackageById";
3728 else if (selector == @selector(installPackages:))
3729 return @"installPackages";
3730 else if (selector == @selector(setAutoPopup:))
3731 return @"setAutoPopup";
3732 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3733 return @"setButtonImage";
3734 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3735 return @"setButtonTitle";
3736 else if (selector == @selector(setFinishHook:))
3737 return @"setFinishHook";
3738 else if (selector == @selector(setPopupHook:))
3739 return @"setPopupHook";
3740 else if (selector == @selector(setSpecial:))
3741 return @"setSpecial";
3742 else if (selector == @selector(setToken:))
3744 else if (selector == @selector(setViewportWidth:))
3745 return @"setViewportWidth";
3746 else if (selector == @selector(supports:))
3748 else if (selector == @selector(stringWithFormat:arguments:))
3750 else if (selector == @selector(localizedStringForKey:value:table:))
3752 else if (selector == @selector(du:))
3754 else if (selector == @selector(statfs:))
3760 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3761 return [self webScriptNameForSelector:selector] == nil;
3764 - (BOOL) supports:(NSString *)feature {
3765 return [feature isEqualToString:@"window.open"];
3768 - (NSArray *) getInstalledPackages {
3769 NSArray *packages([[Database sharedInstance] packages]);
3770 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3771 for (Package *package in packages)
3772 if ([package installed] != nil)
3773 [installed addObject:package];
3777 - (Package *) getPackageById:(NSString *)id {
3778 Package *package([[Database sharedInstance] packageWithName:id]);
3783 - (NSArray *) statfs:(NSString *)path {
3786 if (path == nil || statfs([path UTF8String], &stat) == -1)
3789 return [NSArray arrayWithObjects:
3790 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3791 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3792 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3796 - (NSNumber *) du:(NSString *)path {
3797 NSNumber *value(nil);
3800 _assert(pipe(fds) != -1);
3802 pid_t pid(ExecFork());
3804 _assert(dup2(fds[1], 1) != -1);
3805 _assert(close(fds[0]) != -1);
3806 _assert(close(fds[1]) != -1);
3807 /* XXX: this should probably not use du */
3808 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3813 _assert(close(fds[1]) != -1);
3815 if (FILE *du = fdopen(fds[0], "r")) {
3817 while (fgets(line, sizeof(line), du) != NULL) {
3818 size_t length(strlen(line));
3819 while (length != 0 && line[length - 1] == '\n')
3820 line[--length] = '\0';
3821 if (char *tab = strchr(line, '\t')) {
3823 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3828 } else _assert(close(fds[0]));
3832 if (waitpid(pid, &status, 0) == -1)
3835 else _assert(false);
3844 - (void) installPackages:(NSArray *)packages {
3845 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3848 - (void) setAutoPopup:(BOOL)popup {
3849 [indirect_ setAutoPopup:popup];
3852 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3853 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3856 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3857 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3860 - (void) setSpecial:(id)function {
3861 [indirect_ setSpecial:function];
3864 - (void) setToken:(NSString *)token {
3867 Token_ = [token retain];
3869 [Metadata_ setObject:Token_ forKey:@"Token"];
3873 - (void) setFinishHook:(id)function {
3874 [indirect_ setFinishHook:function];
3877 - (void) setPopupHook:(id)function {
3878 [indirect_ setPopupHook:function];
3881 - (void) setViewportWidth:(float)width {
3882 [indirect_ setViewportWidth:width];
3885 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3886 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3887 unsigned count([arguments count]);
3889 for (unsigned i(0); i != count; ++i)
3890 values[i] = [arguments objectAtIndex:i];
3891 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3894 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3895 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3897 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3899 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3905 /* Cydia View Controller {{{ */
3906 @interface CYViewController : UCViewController { }
3909 @implementation CYViewController
3913 @interface CYBrowserController : BrowserController {
3914 CydiaObject *cydia_;
3919 @implementation CYBrowserController
3926 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3929 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3930 [super webView:sender didClearWindowObject:window forFrame:frame];
3932 WebDataSource *source([frame dataSource]);
3933 NSURLResponse *response([source response]);
3934 NSURL *url([response URL]);
3935 NSString *scheme([url scheme]);
3937 NSHTTPURLResponse *http;
3938 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3939 http = (NSHTTPURLResponse *) response;
3943 NSDictionary *headers([http allHeaderFields]);
3944 NSString *host([url host]);
3945 [self setHeaders:headers forHost:host];
3948 [host isEqualToString:@"cydia.saurik.com"] ||
3949 [host hasSuffix:@".cydia.saurik.com"] ||
3950 [scheme isEqualToString:@"file"]
3952 [window setValue:cydia_ forKey:@"cydia"];
3955 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3956 if (System_ != NULL)
3957 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3958 if (Machine_ != NULL)
3959 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3961 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3963 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3966 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3967 NSMutableURLRequest *copy = [request mutableCopy];
3968 [self _setMoreHeaders:copy];
3972 - (void) setDelegate:(id)delegate {
3973 [super setDelegate:delegate];
3974 [cydia_ setDelegate:delegate];
3978 if ((self = [super initWithWidth:[[self view] bounds].size.width ofClass:[CYBrowserController class]]) != nil) {
3979 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3981 WebView *webview([document_ webView]);
3983 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3985 NSString *application = package == nil ? @"Cydia" : [NSString
3986 stringWithFormat:@"Cydia/%@",
3991 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3993 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3994 if (Product_ != nil)
3995 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3997 [webview setApplicationNameForUserAgent:application];
4003 @protocol ConfirmationControllerDelegate
4004 - (void) cancelAndClear:(bool)clear;
4005 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4009 @interface ConfirmationController : CYBrowserController {
4010 _transient Database *database_;
4011 UIAlertView *essential_;
4018 - (id) initWithDatabase:(Database *)database;
4022 @implementation ConfirmationController
4029 if (essential_ != nil)
4030 [essential_ release];
4034 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4035 NSString *context([alert context]);
4037 if ([context isEqualToString:@"remove"]) {
4038 if (button == [alert cancelButtonIndex]) {
4039 [self dismissModalViewControllerAnimated:YES];
4040 } else if (button == [alert firstOtherButtonIndex]) {
4043 [delegate_ confirmWithNavigationController:[self navigationController]];
4046 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4047 } else if ([context isEqualToString:@"unable"]) {
4048 [self dismissModalViewControllerAnimated:YES];
4049 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4051 [super alertView:alert clickedButtonAtIndex:button];
4055 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4056 [self dismissModalViewControllerAnimated:YES];
4057 [delegate_ cancelAndClear:NO];
4062 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4063 [super webView:sender didClearWindowObject:window forFrame:frame];
4064 [window setValue:changes_ forKey:@"changes"];
4065 [window setValue:issues_ forKey:@"issues"];
4066 [window setValue:sizes_ forKey:@"sizes"];
4067 [window setValue:self forKey:@"queue"];
4070 - (id) initWithDatabase:(Database *)database {
4071 if ((self = [super init]) != nil) {
4072 database_ = database;
4074 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4076 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4077 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4078 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4079 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4080 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4084 pkgDepCache::Policy *policy([database_ policy]);
4086 pkgCacheFile &cache([database_ cache]);
4087 NSArray *packages = [database_ packages];
4088 for (Package *package in packages) {
4089 pkgCache::PkgIterator iterator = [package iterator];
4090 pkgDepCache::StateCache &state(cache[iterator]);
4092 NSString *name([package name]);
4094 if (state.NewInstall())
4095 [installing addObject:name];
4096 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4097 [reinstalling addObject:name];
4098 else if (state.Upgrade())
4099 [upgrading addObject:name];
4100 else if (state.Downgrade())
4101 [downgrading addObject:name];
4102 else if (state.Delete()) {
4103 if ([package essential])
4105 [removing addObject:name];
4108 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4109 substrate_ |= DepSubstrate(iterator.CurrentVer());
4114 else if (Advanced_) {
4115 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4117 essential_ = [[UIAlertView alloc]
4118 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4119 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4121 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4122 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4125 [essential_ setContext:@"remove"];
4127 essential_ = [[UIAlertView alloc]
4128 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4129 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4131 cancelButtonTitle:UCLocalize("OKAY")
4132 otherButtonTitles:nil
4135 [essential_ setContext:@"unable"];
4138 changes_ = [[NSArray alloc] initWithObjects:
4146 issues_ = [database_ issues];
4148 issues_ = [issues_ retain];
4150 sizes_ = [[NSArray alloc] initWithObjects:
4151 SizeString([database_ fetcher].FetchNeeded()),
4152 SizeString([database_ fetcher].PartialPresent()),
4155 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4157 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
4158 initWithTitle:UCLocalize("CANCEL")
4159 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4160 style:UIBarButtonItemStylePlain
4162 action:@selector(cancelButtonClicked)
4164 [[self navigationItem] setLeftBarButtonItem:leftItem];
4169 - (void) applyRightButton {
4170 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
4171 initWithTitle:UCLocalize("CONFIRM")
4172 style:UIBarButtonItemStylePlain
4174 action:@selector(confirmButtonClicked)
4176 #if !AlwaysReload && !IgnoreInstall
4177 if (issues_ == nil && ![self isLoading]) [[self navigationItem] setRightBarButtonItem:rightItem];
4178 else [super applyRightButton];
4180 [[self navigationItem] setRightBarButtonItem:nil];
4182 [rightItem release];
4185 - (void) cancelButtonClicked {
4186 [self dismissModalViewControllerAnimated:YES];
4187 [delegate_ cancelAndClear:YES];
4191 - (void) confirmButtonClicked {
4195 if (essential_ != nil)
4200 [delegate_ confirmWithNavigationController:[self navigationController]];
4208 /* Progress Data {{{ */
4209 @interface ProgressData : NSObject {
4215 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4222 @implementation ProgressData
4224 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4225 if ((self = [super init]) != nil) {
4226 selector_ = selector;
4246 /* Progress Controller {{{ */
4247 @interface ProgressController : CYViewController <
4248 ConfigurationDelegate,
4251 _transient Database *database_;
4252 UIProgressBar *progress_;
4253 UITextView *output_;
4254 UITextLabel *status_;
4255 UIPushButton *close_;
4257 SHA1SumValue springlist_;
4258 SHA1SumValue notifyconf_;
4262 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4264 - (void) _retachThread;
4265 - (void) _detachNewThreadData:(ProgressData *)data;
4266 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4272 @protocol ProgressControllerDelegate
4273 - (void) progressControllerIsComplete:(ProgressController *)sender;
4276 @implementation ProgressController
4279 [database_ setDelegate:nil];
4280 [progress_ release];
4289 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4290 if ((self = [super init]) != nil) {
4291 database_ = database;
4292 [database_ setDelegate:self];
4293 delegate_ = delegate;
4295 [[self view] setBackgroundColor:(CGColor *)[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4297 progress_ = [[UIProgressBar alloc] init];
4298 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4299 [progress_ setStyle:0];
4301 status_ = [[UITextLabel alloc] init];
4302 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4303 [status_ setColor:[UIColor whiteColor]];
4304 [status_ setBackgroundColor:[UIColor clearColor]];
4305 [status_ setCentersHorizontally:YES];
4306 //[status_ setFont:font];
4308 output_ = [[UITextView alloc] init];
4310 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4311 //[output_ setTextFont:@"Courier New"];
4312 [output_ setFont:[[output_ font] fontWithSize:12]];
4313 [output_ setTextColor:[UIColor whiteColor]];
4314 [output_ setBackgroundColor:[UIColor clearColor]];
4315 [output_ setMarginTop:0];
4316 [output_ setAllowsRubberBanding:YES];
4317 [output_ setEditable:NO];
4318 [[self view] addSubview:output_];
4320 close_ = [[UIPushButton alloc] init];
4321 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4322 [close_ setAutosizesToFit:NO];
4323 [close_ setDrawsShadow:YES];
4324 [close_ setStretchBackground:YES];
4325 [close_ setEnabled:YES];
4326 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4327 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4328 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4329 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4333 - (void) positionViews {
4334 CGRect bounds = [[self view] bounds];
4335 CGSize prgsize = [UIProgressBar defaultSize];
4338 (bounds.size.width - prgsize.width) / 2,
4339 bounds.size.height - prgsize.height - 64
4342 float closewidth = bounds.size.width - 20;
4343 if (closewidth > 300) closewidth = 300;
4345 [progress_ setFrame:prgrect];
4346 [status_ setFrame:CGRectMake(
4348 bounds.size.height - prgsize.height - 94,
4349 bounds.size.width - 20,
4352 [output_ setFrame:CGRectMake(
4355 bounds.size.width - 20,
4356 bounds.size.height - 106
4358 [close_ setFrame:CGRectMake(
4359 (bounds.size.width - closewidth) / 2,
4360 bounds.size.height - prgsize.height - 94,
4366 - (void) viewWillAppear:(BOOL)animated {
4367 [super viewDidAppear:animated];
4368 [[self navigationItem] setHidesBackButton:YES];
4369 [[[self navigationController] navigationBar] setBarStyle:1];
4371 [self positionViews];
4374 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4375 [self positionViews];
4378 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4379 NSString *context([alert context]);
4381 if ([context isEqualToString:@"conffile"]) {
4382 FILE *input = [database_ input];
4383 if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
4384 else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
4389 - (void) closeButtonPushed {
4392 UpdateExternalStatus(0);
4396 [self dismissModalViewControllerAnimated:YES];
4400 [delegate_ terminateWithSuccess];
4401 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4402 [delegate_ suspendWithAnimation:YES];
4404 [delegate_ suspend];*/
4408 system("launchctl stop com.apple.SpringBoard");
4412 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4421 - (void) _retachThread {
4422 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4424 [[self view] addSubview:close_];
4425 [progress_ removeFromSuperview];
4426 [status_ removeFromSuperview];
4428 [database_ popErrorWithTitle:title_];
4429 [delegate_ progressControllerIsComplete:self];
4433 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4436 MMap mmap(file, MMap::ReadOnly);
4438 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4439 if (!(notifyconf_ == sha1.Result()))
4446 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4449 MMap mmap(file, MMap::ReadOnly);
4451 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4452 if (!(springlist_ == sha1.Result()))
4458 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4459 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4460 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4461 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4462 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4465 system("su -c /usr/bin/uicache mobile");
4467 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4469 [delegate_ setStatusBarShowsProgress:NO];
4472 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4473 [[data target] performSelector:[data selector] withObject:[data object]];
4476 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4479 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4480 UpdateExternalStatus(1);
4487 title_ = [title retain];
4489 [[self navigationItem] setTitle:title_];
4491 [status_ setText:nil];
4492 [output_ setText:@""];
4493 [progress_ setProgress:0];
4495 [close_ removeFromSuperview];
4496 [[self view] addSubview:progress_];
4497 [[self view] addSubview:status_];
4499 [delegate_ setStatusBarShowsProgress:YES];
4504 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4507 MMap mmap(file, MMap::ReadOnly);
4509 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4510 notifyconf_ = sha1.Result();
4516 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4519 MMap mmap(file, MMap::ReadOnly);
4521 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4522 springlist_ = sha1.Result();
4527 detachNewThreadSelector:@selector(_detachNewThreadData:)
4529 withObject:[[ProgressData alloc]
4530 initWithSelector:selector
4537 - (void) repairWithSelector:(SEL)selector {
4539 detachNewThreadSelector:selector
4542 title:UCLocalize("REPAIRING")
4546 - (void) setConfigurationData:(NSString *)data {
4548 performSelectorOnMainThread:@selector(_setConfigurationData:)
4554 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4555 CYActionSheet *sheet([[[CYActionSheet alloc]
4557 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4558 defaultButtonIndex:0
4561 [sheet setMessage:error];
4562 [sheet yieldToPopupAlertAnimated:YES];
4566 - (void) setProgressTitle:(NSString *)title {
4568 performSelectorOnMainThread:@selector(_setProgressTitle:)
4574 - (void) setProgressPercent:(float)percent {
4576 performSelectorOnMainThread:@selector(_setProgressPercent:)
4577 withObject:[NSNumber numberWithFloat:percent]
4582 - (void) startProgress {
4585 - (void) addProgressOutput:(NSString *)output {
4587 performSelectorOnMainThread:@selector(_addProgressOutput:)
4593 - (bool) isCancelling:(size_t)received {
4597 - (void) _setConfigurationData:(NSString *)data {
4598 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4600 if (!conffile_r(data)) {
4601 lprintf("E:invalid conffile\n");
4605 NSString *ofile = conffile_r[1];
4606 //NSString *nfile = conffile_r[2];
4608 UIAlertView *alert = [[[UIAlertView alloc]
4609 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4610 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4612 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4613 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4614 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4618 [alert setContext:@"conffile"];
4622 - (void) _setProgressTitle:(NSString *)title {
4623 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4624 for (size_t i(0), e([words count]); i != e; ++i) {
4625 NSString *word([words objectAtIndex:i]);
4626 if (Package *package = [database_ packageWithName:word])
4627 [words replaceObjectAtIndex:i withObject:[package name]];
4630 [status_ setText:[words componentsJoinedByString:@" "]];
4633 - (void) _setProgressPercent:(NSNumber *)percent {
4634 [progress_ setProgress:[percent floatValue]];
4637 - (void) _addProgressOutput:(NSString *)output {
4638 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4639 CGSize size = [output_ contentSize];
4640 CGRect rect = {{0, size.height}, {size.width, 0}};
4641 [output_ scrollRectToVisible:rect animated:YES];
4644 - (BOOL) isRunning {
4651 /* Cell Content View {{{ */
4652 @interface ContentView : UIView {
4653 _transient id delegate_;
4658 @implementation ContentView
4659 - (id) initWithFrame:(CGRect)frame {
4660 if ((self = [super initWithFrame:frame]) != nil) {
4661 /* Fix landscape stretching. */
4662 [self setNeedsDisplayOnBoundsChange:YES];
4666 - (void) setDelegate:(id)delegate {
4667 delegate_ = delegate;
4670 - (void) drawRect:(CGRect)rect {
4671 [super drawRect:rect];
4672 [delegate_ drawContentRect:rect];
4676 /* Package Cell {{{ */
4677 @interface PackageCell : UITableViewCell {
4680 NSString *description_;
4686 ContentView *content_;
4692 - (PackageCell *) init;
4693 - (void) setPackage:(Package *)package;
4695 + (int) heightForPackage:(Package *)package;
4696 - (void) drawContentRect:(CGRect)rect;
4700 @implementation PackageCell
4702 - (void) clearPackage {
4713 if (description_ != nil) {
4714 [description_ release];
4718 if (source_ != nil) {
4723 if (badge_ != nil) {
4728 if (placard_ != nil) {
4738 [self clearPackage];
4745 return faded_ ? [self selectionPercent] : fade_;
4748 - (PackageCell *) init {
4749 CGRect frame(CGRectMake(0, 0, 320, 74));
4750 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4751 UIView *content([self contentView]);
4752 CGRect bounds([content bounds]);
4754 content_ = [[ContentView alloc] initWithFrame:bounds];
4755 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4756 [content addSubview:content_];
4758 [content_ setDelegate:self];
4759 [content_ setOpaque:YES];
4760 if ([self respondsToSelector:@selector(selectionPercent)])
4765 - (void) _setBackgroundColor {
4767 if (NSString *mode = [package_ mode]) {
4768 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4769 color = remove ? RemovingColor_ : InstallingColor_;
4771 color = [UIColor whiteColor];
4773 [content_ setBackgroundColor:color];
4774 [self setNeedsDisplay];
4777 - (void) setPackage:(Package *)package {
4778 [self clearPackage];
4781 Source *source = [package source];
4783 icon_ = [[package icon] retain];
4784 name_ = [[package name] retain];
4787 description_ = [package longDescription];
4788 if (description_ == nil)
4789 description_ = [package shortDescription];
4790 if (description_ != nil)
4791 description_ = [description_ retain];
4793 commercial_ = [package isCommercial];
4795 package_ = [package retain];
4797 NSString *label = nil;
4798 bool trusted = false;
4800 if (source != nil) {
4801 label = [source label];
4802 trusted = [source trusted];
4803 } else if ([[package id] isEqualToString:@"firmware"])
4804 label = UCLocalize("APPLE");
4806 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4808 NSString *from(label);
4810 NSString *section = [package simpleSection];
4811 if (section != nil && ![section isEqualToString:label]) {
4812 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4813 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4816 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4817 source_ = [from retain];
4819 if (NSString *purpose = [package primaryPurpose])
4820 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4821 badge_ = [badge_ retain];
4823 if ([package installed] != nil)
4824 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4825 placard_ = [placard_ retain];
4827 [self _setBackgroundColor];
4828 [content_ setNeedsDisplay];
4831 - (void) drawContentRect:(CGRect)rect {
4832 bool selected([self isSelected]);
4833 float width([self bounds].size.width);
4836 CGContextRef context(UIGraphicsGetCurrentContext());
4837 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4838 CGContextFillRect(context, rect);
4843 rect.size = [icon_ size];
4845 rect.size.width /= 2;
4846 rect.size.height /= 2;
4848 rect.origin.x = 25 - rect.size.width / 2;
4849 rect.origin.y = 25 - rect.size.height / 2;
4851 [icon_ drawInRect:rect];
4854 if (badge_ != nil) {
4855 CGSize size = [badge_ size];
4857 [badge_ drawAtPoint:CGPointMake(
4858 36 - size.width / 2,
4859 36 - size.height / 2
4867 UISetColor(commercial_ ? Purple_ : Black_);
4868 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ ellipsis:2];
4869 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ ellipsis:2];
4872 UISetColor(commercial_ ? Purplish_ : Gray_);
4873 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ ellipsis:2];
4875 if (placard_ != nil)
4876 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4879 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4880 //[self _setBackgroundColor];
4881 [super setSelected:selected animated:fade];
4882 [content_ setNeedsDisplay];
4885 + (int) heightForPackage:(Package *)package {
4891 /* Section Cell {{{ */
4892 @interface SectionCell : UITableViewCell {
4898 ContentView *content_;
4904 - (void) setSection:(Section *)section editing:(BOOL)editing;
4908 @implementation SectionCell
4910 - (void) clearSection {
4911 if (basic_ != nil) {
4916 if (section_ != nil) {
4926 if (count_ != nil) {
4933 [self clearSection];
4941 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4942 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4943 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4944 switch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4945 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4947 UIView *content([self contentView]);
4948 CGRect bounds([content bounds]);
4950 content_ = [[ContentView alloc] initWithFrame:bounds];
4951 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4952 [content addSubview:content_];
4953 [content_ setBackgroundColor:[UIColor whiteColor]];
4955 [content_ setDelegate:self];
4959 - (void) onSwitch:(id)sender {
4960 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4961 if (metadata == nil) {
4962 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4963 [Sections_ setObject:metadata forKey:basic_];
4967 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4970 - (void) setSection:(Section *)section editing:(BOOL)editing {
4971 if (editing != editing_) {
4973 [switch_ removeFromSuperview];
4975 [self addSubview:switch_];
4979 [self clearSection];
4981 if (section == nil) {
4982 name_ = [UCLocalize("ALL_PACKAGES") retain];
4985 basic_ = [section name];
4987 basic_ = [basic_ retain];
4989 section_ = [section localized];
4990 if (section_ != nil)
4991 section_ = [section_ retain];
4993 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4994 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4997 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5000 [self setAccessoryType:editing ? 0 : 1 /*UITableViewCellAccessoryDisclosureIndicator*/];
5001 [content_ setNeedsDisplay];
5004 - (void) setFrame:(CGRect)frame {
5005 [super setFrame:frame];
5007 CGRect rect([switch_ frame]);
5008 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5011 - (void) drawContentRect:(CGRect)rect {
5012 BOOL selected = [self isSelected];
5014 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5022 float width(rect.size.width);
5026 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ ellipsis:2];
5028 CGSize size = [count_ sizeWithFont:Font14_];
5032 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5038 /* File Table {{{ */
5039 @interface FileTable : CYViewController {
5040 _transient Database *database_;
5043 NSMutableArray *files_;
5047 - (id) initWithDatabase:(Database *)database;
5048 - (void) setPackage:(Package *)package;
5052 @implementation FileTable
5055 if (package_ != nil)
5064 - (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
5065 return files_ == nil ? 0 : [files_ count];
5068 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5072 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5073 static NSString *reuseIdentifier = @"Cell";
5075 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5077 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5078 [cell setFont:[UIFont systemFontOfSize:16]];
5080 [cell setText:[files_ objectAtIndex:indexPath.row]];
5081 [cell setSelectionStyle:0 /*UITableViewCellSelectionStyleNone*/];
5086 - (id) initWithDatabase:(Database *)database {
5087 if ((self = [super init]) != nil) {
5088 database_ = database;
5090 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5092 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5094 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5095 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5096 [list_ setRowHeight:24.0f];
5097 [[self view] addSubview:list_];
5099 [list_ setDataSource:self];
5100 [list_ setDelegate:self];
5104 - (void) setPackage:(Package *)package {
5105 if (package_ != nil) {
5106 [package_ autorelease];
5115 [files_ removeAllObjects];
5117 if (package != nil) {
5118 package_ = [package retain];
5119 name_ = [[package id] retain];
5121 if (NSArray *files = [package files])
5122 [files_ addObjectsFromArray:files];
5124 if ([files_ count] != 0) {
5125 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5126 [files_ removeObjectAtIndex:0];
5127 [files_ sortUsingSelector:@selector(compareByPath:)];
5129 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5130 [stack addObject:@"/"];
5132 for (int i(0), e([files_ count]); i != e; ++i) {
5133 NSString *file = [files_ objectAtIndex:i];
5134 while (![file hasPrefix:[stack lastObject]])
5135 [stack removeLastObject];
5136 NSString *directory = [stack lastObject];
5137 [stack addObject:[file stringByAppendingString:@"/"]];
5138 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5139 ([stack count] - 2) * 3, "",
5140 [file substringFromIndex:[directory length]]
5149 - (void) reloadData {
5150 [self setPackage:[database_ packageWithName:name_]];
5155 /* Package Controller {{{ */
5156 @interface PackageController : CYBrowserController {
5157 _transient Database *database_;
5161 NSMutableArray *buttons_;
5164 - (id) initWithDatabase:(Database *)database;
5165 - (void) setPackage:(Package *)package;
5169 @implementation PackageController
5172 if (package_ != nil)
5181 if ([self retainCount] == 1)
5182 [delegate_ setPackageController:self];
5186 /* XXX: this is not safe at all... localization of /fail/ */
5187 - (void) _clickButtonWithName:(NSString *)name {
5188 if ([name isEqualToString:UCLocalize("CLEAR")])
5189 [delegate_ clearPackage:package_];
5190 else if ([name isEqualToString:UCLocalize("INSTALL")])
5191 [delegate_ installPackage:package_];
5192 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5193 [delegate_ installPackage:package_];
5194 else if ([name isEqualToString:UCLocalize("REMOVE")])
5195 [delegate_ removePackage:package_];
5196 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5197 [delegate_ installPackage:package_];
5198 else _assert(false);
5201 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5202 NSString *context([sheet context]);
5204 if ([context isEqualToString:@"modify"]) {
5205 if (button != [sheet cancelButtonIndex]) {
5206 NSString *buttonName = [buttons_ objectAtIndex:button];
5207 [self _clickButtonWithName:buttonName];
5210 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5212 [super alertSheet:sheet clickedButtonAtIndex:button];
5216 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
5217 return [super webView:sender didFinishLoadForFrame:frame];
5220 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5221 [super webView:sender didClearWindowObject:window forFrame:frame];
5222 [window setValue:package_ forKey:@"package"];
5225 - (bool) _allowJavaScriptPanel {
5230 - (void) _actionButtonClicked {
5231 int count([buttons_ count]);
5236 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5238 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5239 [buttons addObjectsFromArray:buttons_];
5241 UIActionSheet *sheet = [[[UIActionSheet alloc]
5244 cancelButtonTitle:nil
5245 destructiveButtonTitle:nil
5246 otherButtonTitles:nil
5249 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5251 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5252 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5254 [sheet setContext:@"modify"];
5256 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5260 - (void) actionButtonClicked {
5261 // Wait until it's done loading.
5262 if (![self isLoading])
5263 [self _actionButtonClicked];
5266 - (void) reloadButtonClicked {
5267 // Don't reload a package view by clicking the button.
5270 - (void) applyLoadingTitle {
5271 // Don't show "Loading" as the title. Ever.
5275 - (id) initWithDatabase:(Database *)database {
5276 if ((self = [super init]) != nil) {
5277 database_ = database;
5278 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5279 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5283 - (void) setPackage:(Package *)package {
5284 if (package_ != nil) {
5285 [package_ autorelease];
5294 [buttons_ removeAllObjects];
5296 if (package != nil) {
5299 package_ = [package retain];
5300 name_ = [[package id] retain];
5301 commercial_ = [package isCommercial];
5303 if ([package_ mode] != nil)
5304 [buttons_ addObject:UCLocalize("CLEAR")];
5305 if ([package_ source] == nil);
5306 else if ([package_ upgradableAndEssential:NO])
5307 [buttons_ addObject:UCLocalize("UPGRADE")];
5308 else if ([package_ uninstalled])
5309 [buttons_ addObject:UCLocalize("INSTALL")];
5311 [buttons_ addObject:UCLocalize("REINSTALL")];
5312 if (![package_ uninstalled])
5313 [buttons_ addObject:UCLocalize("REMOVE")];
5315 if (special_ != NULL) {
5316 CGRect frame([document_ frame]);
5317 frame.size.height = 0;
5318 [document_ setFrame:frame];
5320 if ([scroller_ respondsToSelector:@selector(scrollPointVisibleAtTopLeft:)])
5321 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5323 [scroller_ scrollRectToVisible:CGRectZero animated:NO];
5326 [[[document_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5328 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5330 [self setFinishHook:nil];
5331 [self setPopupHook:nil];
5334 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5335 [super callFunction:special_];
5340 - (void) applyRightButton {
5341 int count = [buttons_ count];
5342 UIBarButtonItem *actionItem = [[UIBarButtonItem alloc]
5343 initWithTitle:count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0]
5344 style:UIBarButtonItemStylePlain
5346 action:@selector(actionButtonClicked)
5348 if (![self isLoading]) [[self navigationItem] setRightBarButtonItem:actionItem];
5349 else [super applyRightButton];
5350 [actionItem release];
5353 - (bool) isLoading {
5354 return commercial_ ? [super isLoading] : false;
5357 - (void) reloadData {
5358 [self setPackage:[database_ packageWithName:name_]];
5363 /* Package Table {{{ */
5364 @interface PackageTable : UIView {
5365 _transient Database *database_;
5366 NSMutableArray *packages_;
5367 NSMutableArray *sections_;
5369 NSMutableArray *index_;
5370 NSMutableDictionary *indices_;
5376 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5378 - (void) setDelegate:(id)delegate;
5380 - (void) reloadData;
5381 - (void) resetCursor;
5383 - (UITableView *) list;
5385 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5387 - (void) deselectWithAnimation:(BOOL)animated;
5391 @implementation PackageTable
5394 [packages_ release];
5395 [sections_ release];
5403 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5404 NSInteger count([sections_ count]);
5405 return count == 0 ? 1 : count;
5408 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5409 if ([sections_ count] == 0)
5411 return [[sections_ objectAtIndex:section] name];
5414 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5415 if ([sections_ count] == 0)
5417 return [[sections_ objectAtIndex:section] count];
5420 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5421 Section *section([sections_ objectAtIndex:[path section]]);
5422 NSInteger row([path row]);
5423 Package *package([packages_ objectAtIndex:([section row] + row)]);
5427 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5428 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
5430 cell = [[[PackageCell alloc] init] autorelease];
5431 [cell setPackage:[self packageAtIndexPath:path]];
5435 - (void) deselectWithAnimation:(BOOL)animated {
5436 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5439 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5440 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5443 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5444 Package *package([self packageAtIndexPath:path]);
5445 package = [database_ packageWithName:[package id]];
5446 [target_ performSelector:action_ withObject:package];
5450 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5451 return [packages_ count] > 20 ? index_ : nil;
5454 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5458 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5459 if ((self = [super initWithFrame:frame]) != nil) {
5460 database_ = database;
5465 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5466 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5468 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5469 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5471 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5472 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5473 [list_ setRowHeight:73.0f];
5474 [self addSubview:list_];
5476 [list_ setDataSource:self];
5477 [list_ setDelegate:self];
5481 - (void) setDelegate:(id)delegate {
5482 delegate_ = delegate;
5485 - (bool) hasPackage:(Package *)package {
5489 - (void) reloadData {
5490 NSArray *packages = [database_ packages];
5492 [packages_ removeAllObjects];
5493 [sections_ removeAllObjects];
5495 _profile(PackageTable$reloadData$Filter)
5496 for (Package *package in packages)
5497 if ([self hasPackage:package])
5498 [packages_ addObject:package];
5501 [index_ removeAllObjects];
5502 [indices_ removeAllObjects];
5504 Section *section = nil;
5506 _profile(PackageTable$reloadData$Section)
5507 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5511 _profile(PackageTable$reloadData$Section$Package)
5512 package = [packages_ objectAtIndex:offset];
5513 index = [package index];
5516 if (section == nil || [section index] != index) {
5517 _profile(PackageTable$reloadData$Section$Allocate)
5518 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5521 [index_ addObject:[section name]];
5522 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5524 _profile(PackageTable$reloadData$Section$Add)
5525 [sections_ addObject:section];
5529 [section addToCount];
5533 _profile(PackageTable$reloadData$List)
5538 - (void) resetCursor {
5539 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5542 - (UITableView *) list {
5546 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5547 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5552 /* Filtered Package Table {{{ */
5553 @interface FilteredPackageTable : PackageTable {
5559 - (void) setObject:(id)object;
5560 - (void) setObject:(id)object forFilter:(SEL)filter;
5562 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5566 @implementation FilteredPackageTable
5574 - (void) setFilter:(SEL)filter {
5577 /* XXX: this is an unsafe optimization of doomy hell */
5578 Method method(class_getInstanceMethod([Package class], filter));
5579 _assert(method != NULL);
5580 imp_ = method_getImplementation(method);
5581 _assert(imp_ != NULL);
5584 - (void) setObject:(id)object {
5590 object_ = [object retain];
5593 - (void) setObject:(id)object forFilter:(SEL)filter {
5594 [self setFilter:filter];
5595 [self setObject:object];
5598 - (bool) hasPackage:(Package *)package {
5599 _profile(FilteredPackageTable$hasPackage)
5600 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5604 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5605 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5606 [self setFilter:filter];
5607 object_ = [object retain];
5615 /* Filtered Package Controller {{{ */
5616 @interface FilteredPackageController : CYViewController {
5617 _transient Database *database_;
5618 FilteredPackageTable *packages_;
5622 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5626 @implementation FilteredPackageController
5629 [packages_ release];
5635 - (void) viewDidAppear:(BOOL)animated {
5636 [super viewDidAppear:animated];
5637 [packages_ deselectWithAnimation:animated];
5640 - (void) didSelectPackage:(Package *)package {
5641 PackageController *view([delegate_ packageController]);
5642 [view setPackage:package];
5643 [view setDelegate:delegate_];
5644 [[self navigationController] pushViewController:view animated:YES];
5647 - (id) title { return title_; }
5649 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5650 if ((self = [super init]) != nil) {
5651 database_ = database;
5652 title_ = [title copy];
5653 [[self navigationItem] setTitle:title_];
5655 packages_ = [[FilteredPackageTable alloc]
5656 initWithFrame:[[self view] bounds]
5659 action:@selector(didSelectPackage:)
5664 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5665 [[self view] addSubview:packages_];
5669 - (void) reloadData {
5670 [packages_ reloadData];
5673 - (void) setDelegate:(id)delegate {
5674 [super setDelegate:delegate];
5675 [packages_ setDelegate:delegate];
5682 /* Add Source Controller {{{ */
5683 @interface AddSourceController : CYViewController {
5684 _transient Database *database_;
5687 - (id) initWithDatabase:(Database *)database;
5691 @implementation AddSourceController
5693 - (id) initWithDatabase:(Database *)database {
5694 if ((self = [super init]) != nil) {
5695 database_ = database;
5701 /* Source Cell {{{ */
5702 @interface SourceCell : UITableViewCell {
5705 NSString *description_;
5707 ContentView *content_;
5710 - (void) setSource:(Source *)source;
5714 @implementation SourceCell
5716 - (void) clearSource {
5719 [description_ release];
5728 - (void) setSource:(Source *)source {
5732 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5734 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5735 icon_ = [icon_ retain];
5737 origin_ = [[source name] retain];
5738 label_ = [[source uri] retain];
5739 description_ = [[source description] retain];
5741 [content_ setNeedsDisplay];
5750 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5751 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5752 UIView *content([self contentView]);
5753 CGRect bounds([content bounds]);
5755 content_ = [[ContentView alloc] initWithFrame:bounds];
5756 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5757 [content_ setBackgroundColor:[UIColor whiteColor]];
5758 [content addSubview:content_];
5760 [content_ setDelegate:self];
5761 [content_ setOpaque:YES];
5765 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5766 [super setSelected:selected animated:animated];
5767 [content_ setNeedsDisplay];
5770 - (void) drawContentRect:(CGRect)rect {
5771 bool selected([self isSelected]);
5772 float width(rect.size.width);
5775 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5782 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ ellipsis:2];
5786 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ ellipsis:2];
5790 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ ellipsis:2];
5795 /* Source Table {{{ */
5796 @interface SourceTable : CYViewController {
5797 _transient Database *database_;
5799 NSMutableArray *sources_;
5803 UIProgressHUD *hud_;
5806 //NSURLConnection *installer_;
5807 NSURLConnection *trivial_;
5808 NSURLConnection *trivial_bz2_;
5809 NSURLConnection *trivial_gz_;
5810 //NSURLConnection *automatic_;
5815 - (id) initWithDatabase:(Database *)database;
5819 @implementation SourceTable
5821 - (void) _deallocConnection:(NSURLConnection *)connection {
5822 if (connection != nil) {
5823 [connection cancel];
5824 //[connection setDelegate:nil];
5825 [connection release];
5837 //[self _deallocConnection:installer_];
5838 [self _deallocConnection:trivial_];
5839 [self _deallocConnection:trivial_gz_];
5840 [self _deallocConnection:trivial_bz2_];
5841 //[self _deallocConnection:automatic_];
5848 - (void) viewDidAppear:(BOOL)animated {
5849 [super viewDidAppear:animated];
5850 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5853 - (int) numberOfSectionsInTableView:(UITableView *)tableView {
5854 return offset_ == 0 ? 1 : 2;
5857 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(int)section {
5858 switch (section + (offset_ == 0 ? 1 : 0)) {
5859 case 0: return UCLocalize("ENTERED_BY_USER");
5860 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5866 - (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
5867 int count = [sources_ count];
5869 case 0: return (offset_ == 0 ? count : offset_);
5870 case 1: return count - offset_;
5876 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5878 switch (indexPath.section) {
5879 case 0: idx = indexPath.row; break;
5880 case 1: idx = indexPath.row + offset_; break;
5884 return [sources_ objectAtIndex:idx];
5887 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5888 Source *source = [self sourceAtIndexPath:indexPath];
5889 return [source description] == nil ? 56 : 73;
5892 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5893 static NSString *cellIdentifier = @"SourceCell";
5895 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5896 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5897 [cell setSource:[self sourceAtIndexPath:indexPath]];
5902 - (int) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5903 return 1; //UITableViewCellAccessoryDisclosureIndicator?
5906 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5907 Source *source = [self sourceAtIndexPath:indexPath];
5909 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5910 initWithDatabase:database_
5911 title:[source label]
5912 filter:@selector(isVisibleInSource:)
5916 [packages setDelegate:delegate_];
5918 [[self navigationController] pushViewController:packages animated:YES];
5921 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5922 Source *source = [self sourceAtIndexPath:indexPath];
5923 return [source record] != nil;
5926 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5927 Source *source = [self sourceAtIndexPath:indexPath];
5928 [Sources_ removeObjectForKey:[source key]];
5929 [delegate_ syncData];
5933 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5936 @"./", @"Distribution",
5937 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5939 [delegate_ syncData];
5942 - (NSString *) getWarning {
5943 NSString *href(href_);
5944 NSRange colon([href rangeOfString:@"://"]);
5945 if (colon.location != NSNotFound)
5946 href = [href substringFromIndex:(colon.location + 3)];
5947 href = [href stringByAddingPercentEscapes];
5948 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5949 href = [href stringByCachingURLWithCurrentCDN];
5951 NSURL *url([NSURL URLWithString:href]);
5953 NSStringEncoding encoding;
5954 NSError *error(nil);
5956 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5957 return [warning length] == 0 ? nil : warning;
5961 - (void) _endConnection:(NSURLConnection *)connection {
5962 NSURLConnection **field = NULL;
5963 if (connection == trivial_)
5965 else if (connection == trivial_bz2_)
5966 field = &trivial_bz2_;
5967 else if (connection == trivial_gz_)
5968 field = &trivial_gz_;
5969 _assert(field != NULL);
5970 [connection release];
5975 trivial_bz2_ == nil &&
5981 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5984 UIAlertView *alert = [[[UIAlertView alloc]
5985 initWithTitle:UCLocalize("SOURCE_WARNING")
5988 cancelButtonTitle:UCLocalize("CANCEL")
5989 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5992 [alert setContext:@"warning"];
5993 [alert setNumberOfRows:1];
5997 } else if (error_ != nil) {
5998 UIAlertView *alert = [[[UIAlertView alloc]
5999 initWithTitle:UCLocalize("VERIFICATION_ERROR")
6000 message:[error_ localizedDescription]
6002 cancelButtonTitle:UCLocalize("OK")
6003 otherButtonTitles:nil
6006 [alert setContext:@"urlerror"];
6009 UIAlertView *alert = [[[UIAlertView alloc]
6010 initWithTitle:UCLocalize("NOT_REPOSITORY")
6011 message:UCLocalize("NOT_REPOSITORY_EX")
6013 cancelButtonTitle:UCLocalize("OK")
6014 otherButtonTitles:nil
6017 [alert setContext:@"trivial"];
6021 [delegate_ setStatusBarShowsProgress:NO];
6022 [delegate_ removeProgressHUD:hud_];
6032 if (error_ != nil) {
6039 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6040 switch ([response statusCode]) {
6046 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6047 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6049 error_ = [error retain];
6050 [self _endConnection:connection];
6053 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6054 [self _endConnection:connection];
6057 - (id)title { return UCLocalize("SOURCES"); }
6059 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6060 NSMutableURLRequest *request = [NSMutableURLRequest
6061 requestWithURL:[NSURL URLWithString:href]
6062 cachePolicy:NSURLRequestUseProtocolCachePolicy
6063 timeoutInterval:120.0
6066 [request setHTTPMethod:method];
6068 if (Machine_ != NULL)
6069 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6070 if (UniqueID_ != nil)
6071 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6073 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6075 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6078 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6079 NSString *context([alert context]);
6081 if ([context isEqualToString:@"source"]) {
6084 NSString *href = [[alert textField] text];
6086 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6088 if (![href hasSuffix:@"/"])
6089 href_ = [href stringByAppendingString:@"/"];
6092 href_ = [href_ retain];
6094 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6095 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6096 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6097 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6101 hud_ = [[delegate_ addProgressHUD] retain];
6102 [hud_ setText:UCLocalize("VERIFYING_URL")];
6111 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6112 } else if ([context isEqualToString:@"trivial"])
6113 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6114 else if ([context isEqualToString:@"urlerror"])
6115 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6116 else if ([context isEqualToString:@"warning"]) {
6131 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6135 - (id) initWithDatabase:(Database *)database {
6136 if ((self = [super init]) != nil) {
6137 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6138 [self updateButtonsForEditingStatus:NO animated:NO];
6140 database_ = database;
6141 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6143 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6144 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6145 [[self view] addSubview:list_];
6147 [list_ setDataSource:self];
6148 [list_ setDelegate:self];
6154 - (void) reloadData {
6156 if (!list.ReadMainList())
6159 [sources_ removeAllObjects];
6160 [sources_ addObjectsFromArray:[database_ sources]];
6162 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6165 int count([sources_ count]);
6167 for (int i = 0; i != count; i++) {
6168 if ([[sources_ objectAtIndex:i] record] == nil) break;
6172 [list_ setEditing:NO];
6173 [self updateButtonsForEditingStatus:NO animated:NO];
6177 - (void) addButtonClicked {
6178 /*[book_ pushPage:[[[AddSourceController alloc]
6183 UIAlertView *alert = [[[UIAlertView alloc]
6184 initWithTitle:UCLocalize("ENTER_APT_URL")
6187 cancelButtonTitle:UCLocalize("CANCEL")
6188 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6191 [alert setContext:@"source"];
6192 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6194 [alert setNumberOfRows:1];
6195 [alert addTextFieldWithValue:@"http://" label:@""];
6197 UITextInputTraits *traits = [[alert textField] textInputTraits];
6198 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6199 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6200 [traits setKeyboardType:UIKeyboardTypeURL];
6201 // XXX: UIReturnKeyDone
6202 [traits setReturnKeyType:UIReturnKeyNext];
6207 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6208 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
6209 initWithTitle:UCLocalize("ADD")
6210 style:UIBarButtonItemStylePlain
6212 action:@selector(addButtonClicked)
6214 [[self navigationItem] setLeftBarButtonItem:editing ? leftItem : [[self navigationItem] backBarButtonItem] animated:animated];
6217 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6218 initWithTitle:editing ? UCLocalize("DONE") : UCLocalize("EDIT")
6219 style:editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6221 action:@selector(editButtonClicked)
6223 [[self navigationItem] setRightBarButtonItem:rightItem animated:animated];
6224 [rightItem release];
6227 - (void) editButtonClicked {
6228 [list_ setEditing:![list_ isEditing] animated:YES];
6230 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6236 /* Installed Controller {{{ */
6237 @interface InstalledController : FilteredPackageController {
6241 - (id) initWithDatabase:(Database *)database;
6245 @implementation InstalledController
6251 - (id) title { return UCLocalize("INSTALLED"); }
6253 - (id) initWithDatabase:(Database *)database {
6254 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6255 [self updateRoleButton];
6256 [self queueStatusDidChange];
6261 - (void) queueButtonClicked {
6266 - (void) queueStatusDidChange {
6269 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6270 initWithTitle:UCLocalize("QUEUE")
6271 style:UIBarButtonItemStyleDone
6273 action:@selector(queueButtonClicked)
6275 if (Queuing_) [[self navigationItem] setLeftBarButtonItem:queueItem];
6276 else [[self navigationItem] setLeftBarButtonItem:nil];
6277 [queueItem release];
6282 - (void) reloadData {
6283 [packages_ reloadData];
6286 - (void) updateRoleButton {
6287 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6288 initWithTitle:expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")
6289 style:expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6291 action:@selector(roleButtonClicked)
6293 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) [[self navigationItem] setRightBarButtonItem:rightItem];
6294 [rightItem release];
6297 - (void) roleButtonClicked {
6298 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6299 [packages_ reloadData];
6302 [self updateRoleButton];
6305 - (void) setDelegate:(id)delegate {
6306 [super setDelegate:delegate];
6307 [packages_ setDelegate:delegate];
6313 /* Home Controller {{{ */
6314 @interface HomeController : CYBrowserController {
6319 @implementation HomeController
6321 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6322 [super _setMoreHeaders:request];
6324 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6325 if (UniqueID_ != nil)
6326 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6329 - (void) aboutButtonClicked {
6330 UIAlertView *alert = [[[UIAlertView alloc] init] autorelease];
6331 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6332 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6333 [alert setCancelButtonIndex:0];
6336 @"Copyright (C) 2008-2010\n"
6337 "Jay Freeman (saurik)\n"
6338 "saurik@saurik.com\n"
6339 "http://www.saurik.com/"
6345 - (void) viewWillAppear:(BOOL)animated {
6346 [super viewWillAppear:animated];
6347 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6350 - (void) viewWillDisappear:(BOOL)animated {
6351 [super viewWillDisappear:animated];
6352 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6356 if ((self = [super init]) != nil) {
6357 UIBarButtonItem *aboutItem = [[UIBarButtonItem alloc]
6358 initWithTitle:UCLocalize("ABOUT")
6359 style:UIBarButtonItemStylePlain
6361 action:@selector(aboutButtonClicked)
6363 [[self navigationItem] setLeftBarButtonItem:aboutItem];
6364 [aboutItem release];
6370 /* Manage Controller {{{ */
6371 @interface ManageController : CYBrowserController {
6376 @implementation ManageController
6379 if ((self = [super init]) != nil) {
6380 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6382 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6383 initWithTitle:UCLocalize("SETTINGS")
6384 style:UIBarButtonItemStylePlain
6386 action:@selector(settingsButtonClicked)
6388 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6389 [settingsItem release];
6391 [self queueStatusDidChange];
6395 - (void) settingsButtonClicked {
6396 [delegate_ showSettings];
6400 - (void) queueButtonClicked {
6404 - (void) applyLoadingTitle {
6405 // No "Loading" title.
6408 - (void) applyRightButton {
6413 - (void) queueStatusDidChange {
6415 if (!IsWildcat_ && Queuing_) {
6416 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6417 initWithTitle:UCLocalize("QUEUE")
6418 style:UIBarButtonItemStyleDone
6420 action:@selector(queueButtonClicked)
6422 [[self navigationItem] setRightBarButtonItem:queueItem];
6424 [queueItem release];
6426 [[self navigationItem] setRightBarButtonItem:nil];
6431 - (bool) isLoading {
6438 /* Refresh Bar {{{ */
6439 @interface RefreshBar : UINavigationBar {
6440 UIProgressIndicator *indicator_;
6441 UITextLabel *prompt_;
6442 UIProgressBar *progress_;
6443 UINavigationButton *cancel_;
6448 @implementation RefreshBar
6450 - (void) positionViews {
6451 CGRect frame = [cancel_ frame];
6452 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6453 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6454 [cancel_ setFrame:frame];
6456 CGSize prgsize = {75, 100};
6458 [self frame].size.width - prgsize.width - 10,
6459 ([self frame].size.height - prgsize.height) / 2
6461 [progress_ setFrame:prgrect];
6463 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6464 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6465 CGRect indrect = {{indoffset, indoffset}, indsize};
6466 [indicator_ setFrame:indrect];
6468 CGSize prmsize = {215, indsize.height + 4};
6470 indoffset * 2 + indsize.width,
6471 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6473 [prompt_ setFrame:prmrect];
6476 - (void)setFrame:(CGRect)frame {
6477 [super setFrame:frame];
6479 [self positionViews];
6482 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6483 if ((self = [super initWithFrame:frame])) {
6484 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6486 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6487 [self setBarStyle:1];
6489 int barstyle([self _barStyle:NO]);
6490 bool ugly(barstyle == 0);
6492 UIProgressIndicatorStyle style = ugly ?
6493 UIProgressIndicatorStyleMediumBrown :
6494 UIProgressIndicatorStyleMediumWhite;
6496 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6497 [indicator_ setStyle:style];
6498 [indicator_ startAnimation];
6499 [self addSubview:indicator_];
6501 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6502 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6503 [prompt_ setBackgroundColor:[UIColor clearColor]];
6504 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6505 [self addSubview:prompt_];
6507 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6508 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6509 [progress_ setStyle:0];
6510 [self addSubview:progress_];
6512 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6513 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6514 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6515 [cancel_ setBarStyle:barstyle];
6517 [self positionViews];
6522 [cancel_ removeFromSuperview];
6526 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6527 [progress_ setProgress:0];
6528 [self addSubview:cancel_];
6532 [cancel_ removeFromSuperview];
6535 - (void) setPrompt:(NSString *)prompt {
6536 [prompt_ setText:prompt];
6539 - (void) setProgress:(float)progress {
6540 [progress_ setProgress:progress];
6546 /* Cydia Tab Bar Controller {{{ */
6547 @interface CYTabBarController : UITabBarController {
6548 Database *database_;
6553 @implementation CYTabBarController
6555 /* XXX: some logic should probably go here related to
6556 freeing the view controllers on tab change */
6558 - (void) reloadData {
6559 size_t count([[self viewControllers] count]);
6560 for (size_t i(0); i != count; ++i) {
6561 UIViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6566 - (id) initWithDatabase: (Database *)database {
6567 if ((self = [super init]) != nil) {
6568 database_ = database;
6575 /* Cydia Navigation Controller {{{ */
6576 @interface CYNavigationController : UINavigationController <
6579 _transient Database *database_;
6583 - (id) initWithDatabase:(Database *)database;
6584 - (void) reloadData;
6589 @implementation CYNavigationController
6591 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6592 // Inherit autorotation settings for modal parents.
6593 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6594 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6596 return [super shouldAutorotateToInterfaceOrientation:orientation];
6604 - (void) reloadData {
6605 size_t count([[self viewControllers] count]);
6606 for (size_t i(0); i != count; ++i) {
6607 UIViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6612 - (void) setDelegate:(id)delegate {
6613 delegate_ = delegate;
6616 - (id) initWithDatabase:(Database *)database {
6617 if ((self = [super init]) != nil) {
6618 database_ = database;
6624 /* Cydia:// Protocol {{{ */
6625 @interface CydiaURLProtocol : NSURLProtocol {
6630 @implementation CydiaURLProtocol
6632 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6633 NSURL *url([request URL]);
6636 NSString *scheme([[url scheme] lowercaseString]);
6637 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6642 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6646 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6647 id<NSURLProtocolClient> client([self client]);
6649 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6651 NSData *data(UIImagePNGRepresentation(icon));
6653 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6654 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6655 [client URLProtocol:self didLoadData:data];
6656 [client URLProtocolDidFinishLoading:self];
6660 - (void) startLoading {
6661 id<NSURLProtocolClient> client([self client]);
6662 NSURLRequest *request([self request]);
6664 NSURL *url([request URL]);
6665 NSString *href([url absoluteString]);
6667 NSString *path([href substringFromIndex:8]);
6668 NSRange slash([path rangeOfString:@"/"]);
6671 if (slash.location == NSNotFound) {
6675 command = [path substringToIndex:slash.location];
6676 path = [path substringFromIndex:(slash.location + 1)];
6679 Database *database([Database sharedInstance]);
6681 if ([command isEqualToString:@"package-icon"]) {
6684 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6685 Package *package([database packageWithName:path]);
6688 UIImage *icon([package icon]);
6689 [self _returnPNGWithImage:icon forRequest:request];
6690 } else if ([command isEqualToString:@"source-icon"]) {
6693 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6694 NSString *source(Simplify(path));
6695 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6697 icon = [UIImage applicationImageNamed:@"unknown.png"];
6698 [self _returnPNGWithImage:icon forRequest:request];
6699 } else if ([command isEqualToString:@"uikit-image"]) {
6702 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6703 UIImage *icon(_UIImageWithName(path));
6704 [self _returnPNGWithImage:icon forRequest:request];
6705 } else if ([command isEqualToString:@"section-icon"]) {
6708 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6709 NSString *section(Simplify(path));
6710 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6712 icon = [UIImage applicationImageNamed:@"unknown.png"];
6713 [self _returnPNGWithImage:icon forRequest:request];
6715 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6719 - (void) stopLoading {
6725 /* Sections Controller {{{ */
6726 @interface SectionsController : CYViewController {
6727 _transient Database *database_;
6728 NSMutableArray *sections_;
6729 NSMutableArray *filtered_;
6735 - (id) initWithDatabase:(Database *)database;
6736 - (void) reloadData;
6741 @implementation SectionsController
6744 [list_ setDataSource:nil];
6745 [list_ setDelegate:nil];
6747 [sections_ release];
6748 [filtered_ release];
6750 [accessory_ release];
6754 - (void) viewDidAppear:(BOOL)animated {
6755 [super viewDidAppear:animated];
6756 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6759 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6760 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6764 - (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
6765 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6768 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6772 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6773 static NSString *reuseIdentifier = @"SectionCell";
6775 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6776 if (cell == nil) cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6777 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6782 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6783 Section *section = [self sectionAtIndexPath:indexPath];
6784 NSString *name = [section name];
6787 if ([indexPath row] == 0) {
6790 title = UCLocalize("ALL_PACKAGES");
6793 name = [NSString stringWithString:name];
6794 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6797 title = UCLocalize("NO_SECTION");
6801 FilteredPackageController *table = [[[FilteredPackageController alloc]
6802 initWithDatabase:database_
6804 filter:@selector(isVisibleInSection:)
6808 [table setDelegate:delegate_];
6810 [[self navigationController] pushViewController:table animated:YES];
6813 - (id) title { return UCLocalize("SECTIONS"); }
6815 - (id) initWithDatabase:(Database *)database {
6816 if ((self = [super init]) != nil) {
6817 database_ = database;
6819 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6821 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6822 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6824 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6825 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6826 [list_ setRowHeight:45.0f];
6827 [[self view] addSubview:list_];
6829 [list_ setDataSource:self];
6830 [list_ setDelegate:self];
6836 - (void) reloadData {
6837 NSArray *packages = [database_ packages];
6839 [sections_ removeAllObjects];
6840 [filtered_ removeAllObjects];
6843 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6844 SectionMap sections;
6845 sections.resize(64);
6847 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6851 for (Package *package in packages) {
6852 NSString *name([package section]);
6853 NSString *key(name == nil ? @"" : name);
6858 _profile(SectionsView$reloadData$Section)
6859 section = §ions[key];
6860 if (*section == nil) {
6861 _profile(SectionsView$reloadData$Section$Allocate)
6862 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6867 [*section addToCount];
6869 _profile(SectionsView$reloadData$Filter)
6870 if (![package valid] || ![package visible])
6874 [*section addToRow];
6878 _profile(SectionsView$reloadData$Section)
6879 section = [sections objectForKey:key];
6880 if (section == nil) {
6881 _profile(SectionsView$reloadData$Section$Allocate)
6882 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6883 [sections setObject:section forKey:key];
6888 [section addToCount];
6890 _profile(SectionsView$reloadData$Filter)
6891 if (![package valid] || ![package visible])
6901 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6902 [sections_ addObject:i->second];
6904 [sections_ addObjectsFromArray:[sections allValues]];
6907 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6909 for (Section *section in sections_) {
6910 size_t count([section row]);
6914 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6915 [section setCount:count];
6916 [filtered_ addObject:section];
6919 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6920 initWithTitle:[sections_ count] == 0 ? nil : UCLocalize("EDIT")
6921 style:UIBarButtonItemStylePlain
6923 action:@selector(editButtonClicked)
6925 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] != nil];
6926 [rightItem release];
6932 - (void) resetView {
6934 [self editButtonClicked];
6937 - (void) editButtonClicked {
6938 if ((editing_ = !editing_))
6941 [delegate_ updateData];
6943 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6944 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6945 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6948 - (UIView *) accessoryView {
6954 /* Changes Controller {{{ */
6955 @interface ChangesController : CYViewController {
6956 _transient Database *database_;
6957 NSMutableArray *packages_;
6958 NSMutableArray *sections_;
6961 BOOL hasSentFirstLoad_;
6964 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6965 - (void) reloadData;
6969 @implementation ChangesController
6972 [list_ setDelegate:nil];
6973 [list_ setDataSource:nil];
6975 [packages_ release];
6976 [sections_ release];
6981 - (void) viewDidAppear:(BOOL)animated {
6982 [super viewDidAppear:animated];
6983 if (!hasSentFirstLoad_) {
6984 hasSentFirstLoad_ = YES;
6985 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6987 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6991 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6992 NSInteger count([sections_ count]);
6993 return count == 0 ? 1 : count;
6996 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6997 if ([sections_ count] == 0)
6999 return [[sections_ objectAtIndex:section] name];
7002 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7003 if ([sections_ count] == 0)
7005 return [[sections_ objectAtIndex:section] count];
7008 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7009 Section *section([sections_ objectAtIndex:[path section]]);
7010 NSInteger row([path row]);
7011 return [packages_ objectAtIndex:([section row] + row)];
7014 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7015 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
7017 cell = [[[PackageCell alloc] init] autorelease];
7018 [cell setPackage:[self packageAtIndexPath:path]];
7022 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7023 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7026 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7027 Package *package([self packageAtIndexPath:path]);
7028 PackageController *view([delegate_ packageController]);
7029 [view setDelegate:delegate_];
7030 [view setPackage:package];
7031 [[self navigationController] pushViewController:view animated:YES];
7035 - (void) refreshButtonClicked {
7036 [[UIApplication sharedApplication] beginUpdate];
7037 [[self navigationItem] setLeftBarButtonItem:nil];
7040 - (void) upgradeButtonClicked {
7041 [delegate_ distUpgrade];
7044 - (id) title { return UCLocalize("CHANGES"); }
7046 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7047 if ((self = [super init]) != nil) {
7048 database_ = database;
7049 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7051 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
7052 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7054 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7055 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7056 [list_ setRowHeight:73.0f];
7057 [[self view] addSubview:list_];
7059 [list_ setDataSource:self];
7060 [list_ setDelegate:self];
7062 delegate_ = delegate;
7066 - (void) _reloadPackages:(NSArray *)packages {
7068 for (Package *package in packages)
7070 [package uninstalled] && [package valid] && [package visible] ||
7071 [package upgradableAndEssential:YES]
7073 [packages_ addObject:package];
7076 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7080 - (void) reloadData {
7081 NSArray *packages = [database_ packages];
7083 [packages_ removeAllObjects];
7084 [sections_ removeAllObjects];
7086 UIProgressHUD *hud([delegate_ addProgressHUD]);
7088 [hud setText:@"Loading Changes"];
7089 NSLog(@"HUD:%@::%@", delegate_, hud);
7090 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7091 [delegate_ removeProgressHUD:hud];
7093 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7094 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7095 Section *section = nil;
7099 bool unseens = false;
7101 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7103 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7104 Package *package = [packages_ objectAtIndex:offset];
7106 BOOL uae = [package upgradableAndEssential:YES];
7112 _profile(ChangesController$reloadData$Remember)
7113 seen = [package seen];
7116 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7121 name = UCLocalize("UNKNOWN");
7123 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7127 _profile(ChangesController$reloadData$Allocate)
7128 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7129 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7130 [sections_ addObject:section];
7134 [section addToCount];
7135 } else if ([package ignored])
7136 [ignored addToCount];
7139 [upgradable addToCount];
7144 CFRelease(formatter);
7147 Section *last = [sections_ lastObject];
7148 size_t count = [last count];
7149 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7150 [sections_ removeLastObject];
7153 if ([ignored count] != 0)
7154 [sections_ insertObject:ignored atIndex:0];
7156 [sections_ insertObject:upgradable atIndex:0];
7160 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7161 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7162 style:UIBarButtonItemStylePlain
7164 action:@selector(upgradeButtonClicked)
7166 if (upgrades_ > 0) [[self navigationItem] setRightBarButtonItem:rightItem];
7167 [rightItem release];
7169 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
7170 initWithTitle:UCLocalize("REFRESH")
7171 style:UIBarButtonItemStylePlain
7173 action:@selector(refreshButtonClicked)
7175 if (![[UIApplication sharedApplication] updating]) [[self navigationItem] setLeftBarButtonItem:leftItem];
7181 /* Search Controller {{{ */
7182 @interface SearchController : FilteredPackageController {
7186 - (id) initWithDatabase:(Database *)database;
7187 - (void) reloadData;
7191 @implementation SearchController
7198 - (void) searchBarSearchButtonClicked:(id)searchBar {
7199 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7200 [search_ resignFirstResponder];
7204 - (void) searchBar:(id)searchBar textDidChange:(NSString *)text {
7205 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7209 - (id) title { return nil; }
7211 - (id) initWithDatabase:(Database *)database {
7212 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7215 - (void)viewDidAppear:(BOOL)animated {
7216 [super viewDidAppear:animated];
7218 search_ = [[objc_getClass("UISearchBar") alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7219 [search_ layoutSubviews];
7220 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7221 UITextField *textField = [search_ searchField];
7222 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7223 [search_ setDelegate:self];
7224 [textField setEnablesReturnKeyAutomatically:NO];
7225 [[self navigationItem] setTitleView:textField];
7229 - (void) _reloadData {
7232 - (void) reloadData {
7233 _profile(SearchController$reloadData)
7234 [packages_ reloadData];
7237 [packages_ resetCursor];
7240 - (void) didSelectPackage:(Package *)package {
7241 [search_ resignFirstResponder];
7242 [super didSelectPackage:package];
7247 /* Settings Controller {{{ */
7248 @interface SettingsController : CYViewController {
7249 _transient Database *database_;
7252 UIPreferencesTable *table_;
7253 _UISwitchSlider *subscribedSwitch_;
7254 _UISwitchSlider *ignoredSwitch_;
7255 UIPreferencesControlTableCell *subscribedCell_;
7256 UIPreferencesControlTableCell *ignoredCell_;
7259 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7263 @implementation SettingsController
7266 [table_ setDataSource:nil];
7269 if (package_ != nil)
7272 [subscribedSwitch_ release];
7273 [ignoredSwitch_ release];
7274 [subscribedCell_ release];
7275 [ignoredCell_ release];
7279 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7280 if (package_ == nil)
7286 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7287 if (package_ == nil)
7300 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7301 if (package_ == nil)
7314 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7315 if (package_ == nil)
7328 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7329 if (package_ == nil)
7332 _UISwitchSlider *slider([cell control]);
7333 BOOL value([slider value] != 0);
7334 NSMutableDictionary *metadata([package_ metadata]);
7337 if (NSNumber *number = [metadata objectForKey:key])
7338 before = [number boolValue];
7342 if (value != before) {
7343 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7345 [delegate_ updateData];
7349 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7350 [self onSomething:cell withKey:@"IsSubscribed"];
7353 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7354 [self onSomething:cell withKey:@"IsIgnored"];
7357 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7358 if (package_ == nil)
7362 case 0: switch (row) {
7364 return subscribedCell_;
7366 return ignoredCell_;
7370 case 1: switch (row) {
7372 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7373 [cell setShowSelection:NO];
7374 [cell setTitle:UCLocalize("SHOW_ALL_CHANGES_EX")];
7387 - (id) title { return UCLocalize("SETTINGS"); }
7389 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7390 if ((self = [super init])) {
7391 database_ = database;
7392 name_ = [package retain];
7394 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7396 table_ = [[UIPreferencesTable alloc] initWithFrame:[[self view] bounds]];
7397 [[self view] addSubview:table_];
7399 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7400 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventTouchUpInside];
7402 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7403 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventTouchUpInside];
7405 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7406 [subscribedCell_ setShowSelection:NO];
7407 [subscribedCell_ setTitle:UCLocalize("SHOW_ALL_CHANGES")];
7408 [subscribedCell_ setControl:subscribedSwitch_];
7410 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7411 [ignoredCell_ setShowSelection:NO];
7412 [ignoredCell_ setTitle:UCLocalize("IGNORE_UPGRADES")];
7413 [ignoredCell_ setControl:ignoredSwitch_];
7415 [table_ setDataSource:self];
7420 - (void) reloadData {
7421 if (package_ != nil)
7422 [package_ autorelease];
7423 package_ = [database_ packageWithName:name_];
7424 if (package_ != nil) {
7426 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7427 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7430 [table_ reloadData];
7436 /* Signature Controller {{{ */
7437 @interface SignatureController : CYBrowserController {
7438 _transient Database *database_;
7442 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7446 @implementation SignatureController
7453 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7455 [super webView:sender didClearWindowObject:window forFrame:frame];
7458 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7459 if ((self = [super init]) != nil) {
7460 database_ = database;
7461 package_ = [package retain];
7466 - (void) reloadData {
7467 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7472 /* Role Controller {{{ */
7473 @interface RoleController : CYViewController {
7474 _transient Database *database_;
7476 UITableView *table_;
7477 UISegmentedControl *segment_;
7482 @implementation RoleController
7486 [container_ release];
7491 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7492 if ((self = [super init])) {
7493 database_ = database;
7494 roledelegate_ = delegate;
7496 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7498 NSArray *items = [NSArray arrayWithObjects:
7500 UCLocalize("HACKER"),
7501 UCLocalize("DEVELOPER"),
7503 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7504 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7505 [container_ addSubview:segment_];
7506 CGFloat width = [[self view] frame].size.width;
7507 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7510 if ([Role_ isEqualToString:@"User"]) index = 0;
7511 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7512 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7514 [segment_ setSelectedSegmentIndex:index];
7515 [self showDoneButton];
7518 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7520 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7521 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7522 [table_ setDelegate:self];
7523 [table_ setDataSource:self];
7524 [[self view] addSubview:table_];
7525 [table_ reloadData];
7530 switch ([segment_ selectedSegmentIndex]) {
7531 case 0: Role_ = @"User"; break;
7532 case 1: Role_ = @"Hacker"; break;
7533 case 2: Role_ = @"Developer"; break;
7538 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7542 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7546 [delegate_ updateData];
7549 - (void) segmentChanged:(UISegmentedControl *)control {
7550 [self showDoneButton];
7553 - (void) doneButtonClicked {
7555 [[self navigationController] dismissModalViewControllerAnimated:YES];
7558 - (void) showDoneButton {
7559 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7560 initWithTitle:UCLocalize("DONE")
7561 style:UIBarButtonItemStyleDone
7563 action:@selector(doneButtonClicked)
7565 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] == nil];
7566 [rightItem release];
7569 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7573 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7577 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7578 return nil; // This method is required by the protocol.
7581 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7583 return UCLocalize("ROLE_EX");
7585 return [NSString stringWithFormat:
7586 @"%@: %@\n%@: %@\n%@: %@",
7587 UCLocalize("USER"), UCLocalize("USER_EX"),
7588 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7589 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7594 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7595 if (section == 3) return 44.0f;
7599 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7600 if (section == 3) return container_;
7607 /* Cydia Container {{{ */
7608 @interface CYContainer : UIViewController <ProgressDelegate> {
7609 _transient Database *database_;
7610 RefreshBar *refreshbar_;
7615 UIViewController *root_;
7620 @implementation CYContainer
7622 // NOTE: UIWindow only sends the top controller these messages,
7623 // So we have to forward them on.
7625 - (void) viewDidAppear:(BOOL)animated {
7626 [super viewDidAppear:animated];
7627 [root_ viewDidAppear:animated];
7630 - (void) viewWillAppear:(BOOL)animated {
7631 [super viewWillAppear:animated];
7632 [root_ viewWillAppear:animated];
7635 - (void) viewDidDisappear:(BOOL)animated {
7636 [super viewDidDisappear:animated];
7637 [root_ viewDidDisappear:animated];
7640 - (void) viewWillDisappear:(BOOL)animated {
7641 [super viewWillDisappear:animated];
7642 [root_ viewWillDisappear:animated];
7645 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7646 return YES; /* XXX: return YES; */
7649 - (void) setRootController:(UIViewController *)controller {
7651 [[self view] addSubview:[root_ view]];
7654 - (void) setUpdate:(NSDate *)date {
7658 - (void) beginUpdate {
7660 [refreshbar_ start];
7665 detachNewThreadSelector:@selector(performUpdate)
7671 - (void) performUpdate { _pooled
7673 status.setDelegate(self);
7674 [database_ updateWithStatus:status];
7677 performSelectorOnMainThread:@selector(completeUpdate)
7683 - (void) completeUpdate {
7686 [self raiseBar:YES];
7688 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7691 - (void) cancelUpdate {
7692 [refreshbar_ cancel];
7693 [self completeUpdate];
7696 - (void) cancelPressed {
7697 [self cancelUpdate];
7704 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7705 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7708 - (void) startProgress {
7711 - (void) setProgressTitle:(NSString *)title {
7713 performSelectorOnMainThread:@selector(_setProgressTitle:)
7719 - (bool) isCancelling:(size_t)received {
7723 - (void) setProgressPercent:(float)percent {
7725 performSelectorOnMainThread:@selector(_setProgressPercent:)
7726 withObject:[NSNumber numberWithFloat:percent]
7731 - (void) addProgressOutput:(NSString *)output {
7733 performSelectorOnMainThread:@selector(_addProgressOutput:)
7739 - (void) _setProgressTitle:(NSString *)title {
7740 [refreshbar_ setPrompt:title];
7743 - (void) _setProgressPercent:(NSNumber *)percent {
7744 [refreshbar_ setProgress:[percent floatValue]];
7747 - (void) _addProgressOutput:(NSString *)output {
7750 - (void) setUpdateDelegate:(id)delegate {
7751 updatedelegate_ = delegate;
7754 - (void) dropBar:(BOOL)animated {
7755 if (dropped_) return;
7758 [[self view] addSubview:refreshbar_];
7760 if (animated) [UIView beginAnimations:nil context:NULL];
7761 CGRect barframe = [refreshbar_ frame];
7762 CGRect viewframe = [[root_ view] frame];
7763 viewframe.origin.y += barframe.size.height + 20.0f;
7764 viewframe.size.height -= barframe.size.height + 20.0f;
7765 [[root_ view] setFrame:viewframe];
7766 if (animated) [UIView commitAnimations];
7768 // Ensure bar has the proper width for our view, it might have changed
7769 barframe.size.width = viewframe.size.width;
7770 [refreshbar_ setFrame:barframe];
7772 // XXX: fix Apple's layout bug
7773 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7776 - (void) raiseBar:(BOOL)animated {
7777 if (!dropped_) return;
7780 [refreshbar_ removeFromSuperview];
7782 if (animated) [UIView beginAnimations:nil context:NULL];
7783 CGRect barframe = [refreshbar_ frame];
7784 CGRect viewframe = [[root_ view] frame];
7785 viewframe.origin.y -= barframe.size.height + 20.0f;
7786 viewframe.size.height += barframe.size.height + 20.0f;
7787 [[root_ view] setFrame:viewframe];
7788 if (animated) [UIView commitAnimations];
7790 // XXX: fix Apple's layout bug
7791 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7794 - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration
7796 // XXX: fix Apple's layout bug
7797 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7800 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7806 // XXX: fix Apple's layout bug
7807 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7811 [refreshbar_ release];
7815 - (id) initWithDatabase: (Database *)database {
7816 if ((self = [super init]) != nil) {
7817 database_ = database;
7819 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7821 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7838 @interface Cydia : UIApplication <
7839 ConfirmationControllerDelegate,
7840 ProgressControllerDelegate,
7844 CYContainer *container_;
7848 NSMutableArray *essential_;
7849 NSMutableArray *broken_;
7851 Database *database_;
7855 UIKeyboard *keyboard_;
7856 UIProgressHUD *hud_;
7858 SectionsController *sections_;
7859 ChangesController *changes_;
7860 ManageController *manage_;
7861 SearchController *search_;
7862 SourceTable *sources_;
7863 InstalledController *installed_;
7866 #if RecyclePackageViews
7867 NSMutableArray *details_;
7873 - (UIViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7874 - (void) setPage:(UIViewController *)page;
7878 static _finline void _setHomePage(Cydia *self) {
7879 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7882 @implementation Cydia
7884 - (void) beginUpdate {
7885 [container_ beginUpdate];
7889 return [container_ updating];
7892 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7897 if ([broken_ count] != 0) {
7898 int count = [broken_ count];
7900 UIAlertView *alert = [[[UIAlertView alloc]
7901 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7902 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7904 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7905 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
7908 [alert setContext:@"fixhalf"];
7910 } else if (!Ignored_ && [essential_ count] != 0) {
7911 int count = [essential_ count];
7913 UIAlertView *alert = [[[UIAlertView alloc]
7914 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7915 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
7917 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
7918 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
7921 [alert setContext:@"upgrade"];
7926 - (void) _saveConfig {
7929 NSString *error(nil);
7930 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7932 NSError *error(nil);
7933 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7934 NSLog(@"failure to save metadata data: %@", error);
7937 NSLog(@"failure to serialize metadata: %@", error);
7945 - (void) _updateData {
7948 /* XXX: this is just stupid */
7949 if (tag_ != 1 && sections_ != nil)
7950 [sections_ reloadData];
7951 if (tag_ != 2 && changes_ != nil)
7952 [changes_ reloadData];
7953 if (tag_ != 4 && search_ != nil)
7954 [search_ reloadData];
7956 [[tabbar_ selectedViewController] reloadData];
7959 - (int)indexOfTabWithTag:(int)tag {
7961 for (UINavigationController *controller in [tabbar_ viewControllers]) {
7962 if ([[controller tabBarItem] tag] == tag) return i;
7969 - (void) _refreshIfPossible {
7970 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
7972 Reachability* reachability = [Reachability reachabilityWithHostName:@"cydia.saurik.com"];
7973 NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
7975 if (loaded_ || ManualRefresh || remoteHostStatus == NotReachable) loaded:
7976 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
7980 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
7982 if (update != nil) {
7983 NSTimeInterval interval([update timeIntervalSinceNow]);
7984 if (interval <= 0 && interval > -(15*60))
7988 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
7994 - (void) refreshIfPossible {
7995 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
7998 - (void) _reloadData {
8001 UIProgressHUD *hud([self addProgressHUD]);
8002 [hud setText:(loaded_ ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
8004 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8007 [self removeProgressHUD:hud];
8011 [essential_ removeAllObjects];
8012 [broken_ removeAllObjects];
8014 NSArray *packages([database_ packages]);
8015 for (Package *package in packages) {
8017 [broken_ addObject:package];
8018 if ([package upgradableAndEssential:NO]) {
8019 if ([package essential])
8020 [essential_ addObject:package];
8026 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8027 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:badge];
8028 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:YES];
8030 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8031 [self setApplicationBadge:badge];
8033 [self setApplicationBadgeString:badge];
8035 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:nil];
8036 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:NO];
8038 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8039 [self removeApplicationBadge];
8040 else // XXX: maybe use setApplicationBadgeString also?
8041 [self setApplicationIconBadgeNumber:0];
8046 [self refreshIfPossible];
8049 - (void) updateData {
8050 [database_ setVisible];
8059 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8060 _assert(file != NULL);
8062 for (NSString *key in [Sources_ allKeys]) {
8063 NSDictionary *source([Sources_ objectForKey:key]);
8065 fprintf(file, "%s %s %s\n",
8066 [[source objectForKey:@"Type"] UTF8String],
8067 [[source objectForKey:@"URI"] UTF8String],
8068 [[source objectForKey:@"Distribution"] UTF8String]
8076 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8077 UINavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8078 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8079 [container_ presentModalViewController:navigation animated:YES];
8082 detachNewThreadSelector:@selector(update_)
8085 title:UCLocalize("UPDATING_SOURCES")
8089 - (void) reloadData {
8090 @synchronized (self) {
8096 pkgProblemResolver *resolver = [database_ resolver];
8098 resolver->InstallProtect();
8099 if (!resolver->Resolve(true))
8103 - (CGRect) popUpBounds {
8104 return [[tabbar_ view] bounds];
8108 if (![database_ prepare])
8111 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8112 [page setDelegate:self];
8113 id confirm_ = [[CYNavigationController alloc] initWithRootViewController:page];
8114 [confirm_ setDelegate:self];
8116 if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8117 [container_ presentModalViewController:confirm_ animated:YES];
8123 @synchronized (self) {
8128 - (void) clearPackage:(Package *)package {
8129 @synchronized (self) {
8136 - (void) installPackages:(NSArray *)packages {
8137 @synchronized (self) {
8138 for (Package *package in packages)
8145 - (void) installPackage:(Package *)package {
8146 @synchronized (self) {
8153 - (void) removePackage:(Package *)package {
8154 @synchronized (self) {
8161 - (void) distUpgrade {
8162 @synchronized (self) {
8163 if (![database_ upgrade])
8170 @synchronized (self) {
8175 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8176 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8178 if (navigation != nil) {
8179 [navigation pushViewController:progress animated:YES];
8181 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8182 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8183 [container_ presentModalViewController:navigation animated:YES];
8187 detachNewThreadSelector:@selector(perform)
8190 title:UCLocalize("RUNNING")
8194 - (void) progressControllerIsComplete:(ProgressController *)progress {
8198 - (void) setPage:(UIViewController *)page {
8199 [page setDelegate:self];
8201 UINavigationController *navController = [tabbar_ selectedViewController];
8202 [navController setViewControllers:[NSArray arrayWithObject:page] animated:NO];
8203 for (UIViewController *page in [tabbar_ viewControllers]) {
8204 if (page != navController) [page setViewControllers:nil];
8208 - (UIViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8209 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8210 [browser loadURL:url];
8214 - (SectionsController *) sectionsController {
8215 if (sections_ == nil)
8216 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8220 - (ChangesController *) changesController {
8221 if (changes_ == nil)
8222 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8226 - (ManageController *) manageController {
8227 if (manage_ == nil) {
8228 manage_ = (ManageController *) [[self
8229 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8230 withClass:[ManageController class]
8232 if (!IsWildcat_) queueDelegate_ = manage_;
8237 - (SearchController *) searchController {
8239 search_ = [[SearchController alloc] initWithDatabase:database_];
8243 - (SourceTable *) sourcesController {
8244 if (sources_ == nil)
8245 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8249 - (InstalledController *) installedController {
8250 if (installed_ == nil) {
8251 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8252 if (IsWildcat_) queueDelegate_ = installed_;
8257 - (void) tabBarController:(id)tabBarController didSelectViewController:(UIViewController *)viewController {
8258 int tag = [[viewController tabBarItem] tag];
8260 [[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8262 } else if (tag_ == 1) {
8263 [[self sectionsController] resetView];
8267 case kCydiaTag: _setHomePage(self); break;
8269 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8270 case kChangesTag: [self setPage:[self changesController]]; break;
8271 case kManageTag: [self setPage:[self manageController]]; break;
8272 case kInstalledTag: [self setPage:[self installedController]]; break;
8273 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8274 case kSearchTag: [self setPage:[self searchController]]; break;
8282 - (void) showSettings {
8283 RoleController *role = [[RoleController alloc] initWithDatabase:database_ delegate:self];
8284 UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:role];
8285 [container_ presentModalViewController:nav animated:YES];
8288 - (void) setPackageController:(PackageController *)view {
8290 [view setPackage:nil];
8291 #if RecyclePackageViews
8292 if ([details_ count] < 3)
8293 [details_ addObject:view];
8298 - (PackageController *) _packageController {
8299 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8302 - (PackageController *) packageController {
8303 #if RecyclePackageViews
8304 PackageController *view;
8305 size_t count([details_ count]);
8308 view = [self _packageController];
8310 [details_ addObject:[self _packageController]];
8312 view = [[[details_ lastObject] retain] autorelease];
8313 [details_ removeLastObject];
8320 return [self _packageController];
8324 - (void) cancelAndClear:(bool)clear {
8325 @synchronized (self) {
8327 /* XXX: clear marks instead of reloading data */
8328 /*pkgCacheFile &cache([database_ cache]);
8329 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
8330 if (!cache[iterator].Keep()) cache->MarkKeep(iterator, false, false);
8336 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kManageTag] != -1 ? [self indexOfTabWithTag:kManageTag] : [self indexOfTabWithTag:kInstalledTag]] tabBarItem] setBadgeValue:nil];
8337 [queueDelegate_ queueStatusDidChange];*/
8342 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kManageTag] != -1 ? [self indexOfTabWithTag:kManageTag] : [self indexOfTabWithTag:kInstalledTag]] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8343 [[tabbar_ selectedViewController] reloadData];
8345 [queueDelegate_ queueStatusDidChange];
8350 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8351 NSString *context([alert context]);
8353 if ([context isEqualToString:@"fixhalf"]) {
8354 if (button == [alert firstOtherButtonIndex]) {
8355 @synchronized (self) {
8356 for (Package *broken in broken_) {
8359 NSString *id = [broken id];
8360 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8361 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8362 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8363 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8369 } else if (button == [alert cancelButtonIndex]) {
8370 [broken_ removeAllObjects];
8374 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8375 } else if ([context isEqualToString:@"upgrade"]) {
8376 if (button == [alert firstOtherButtonIndex]) {
8377 @synchronized (self) {
8378 for (Package *essential in essential_)
8379 [essential install];
8384 } else if (button == [alert firstOtherButtonIndex] + 1) {
8386 } else if (button == [alert cancelButtonIndex]) {
8390 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8394 - (void) system:(NSString *)command { _pooled
8395 system([command UTF8String]);
8398 - (void) applicationWillSuspend {
8400 [super applicationWillSuspend];
8403 - (void) applicationSuspend:(__GSEvent *)event {
8404 // FIXME: This needs to be fixed, but we no longer have a progress_.
8405 // What's the best solution?
8406 if (hud_ == nil)// && ![progress_ isRunning])
8407 [super applicationSuspend:event];
8410 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8412 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8415 - (void) _setSuspended:(BOOL)value {
8417 [super _setSuspended:value];
8420 - (UIProgressHUD *) addProgressHUD {
8421 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8422 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8424 [window_ setUserInteractionEnabled:NO];
8426 [[container_ view] addSubview:hud];
8430 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8432 [hud removeFromSuperview];
8433 [window_ setUserInteractionEnabled:YES];
8436 - (UIViewController *) pageForPackage:(NSString *)name {
8437 if (Package *package = [database_ packageWithName:name]) {
8438 PackageController *view([self packageController]);
8439 [view setPackage:package];
8442 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8443 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8444 return [self _pageForURL:url withClass:[CYBrowserController class]];
8448 - (UIViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8452 NSString *href([url absoluteString]);
8453 if ([href hasPrefix:@"apptapp://package/"])
8454 return [self pageForPackage:[href substringFromIndex:18]];
8456 NSString *scheme([[url scheme] lowercaseString]);
8457 if (![scheme isEqualToString:@"cydia"])
8459 NSString *path([url absoluteString]);
8460 if ([path length] < 8)
8462 path = [path substringFromIndex:8];
8463 if (![path hasPrefix:@"/"])
8464 path = [@"/" stringByAppendingString:path];
8466 if ([path isEqualToString:@"/add-source"])
8467 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8468 else if ([path isEqualToString:@"/storage"])
8469 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8470 else if ([path isEqualToString:@"/sources"])
8471 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8472 else if ([path isEqualToString:@"/packages"])
8473 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8474 else if ([path hasPrefix:@"/url/"])
8475 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8476 else if ([path hasPrefix:@"/launch/"])
8477 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8478 else if ([path hasPrefix:@"/package-settings/"])
8479 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8480 else if ([path hasPrefix:@"/package-signature/"])
8481 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8482 else if ([path hasPrefix:@"/package/"])
8483 return [self pageForPackage:[path substringFromIndex:9]];
8484 else if ([path hasPrefix:@"/files/"]) {
8485 NSString *name = [path substringFromIndex:7];
8487 if (Package *package = [database_ packageWithName:name]) {
8488 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8489 [files setPackage:package];
8497 - (void) applicationOpenURL:(NSURL *)url {
8498 [super applicationOpenURL:url];
8500 if (UIViewController *page = [self pageForURL:url hasTag:&tag]) {
8501 [self setPage:page];
8503 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8507 - (void) applicationWillResignActive:(UIApplication *)application {
8508 // Stop refreshing if you get a phone call or lock the device.
8509 if ([container_ updating]) [container_ cancelUpdate];
8511 [super applicationWillResignActive:application];
8514 - (void) applicationDidFinishLaunching:(id)unused {
8515 [CYBrowserController _initialize];
8517 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8519 Font12_ = [[UIFont systemFontOfSize:12] retain];
8520 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8521 Font14_ = [[UIFont systemFontOfSize:14] retain];
8522 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8523 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8527 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8528 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8530 UIScreen *screen([UIScreen mainScreen]);
8532 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8533 [window_ orderFront:self];
8534 [window_ makeKey:self];
8535 [window_ setHidden:NO];
8537 database_ = [Database sharedInstance];
8540 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8541 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8542 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8543 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8544 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8545 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8546 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8547 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8548 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8551 [self setIdleTimerDisabled:YES];
8553 hud_ = [self addProgressHUD];
8554 [hud_ setText:@"Reorganizing:\n\nWill Automatically\nClose When Done"];
8555 [self setStatusBarShowsProgress:YES];
8557 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8559 [self setStatusBarShowsProgress:NO];
8560 [self removeProgressHUD:hud_];
8563 if (ExecFork() == 0) {
8564 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8565 perror("launchctl stop");
8572 [self showSettings];
8576 NSMutableArray *controllers = [NSMutableArray array];
8577 [controllers addObject:[[CYNavigationController alloc] initWithDatabase:database_]];
8578 [controllers addObject:[[CYNavigationController alloc] initWithDatabase:database_]];
8579 [controllers addObject:[[CYNavigationController alloc] initWithDatabase:database_]];
8580 if (IsWildcat_) [controllers addObject:[[CYNavigationController alloc] initWithDatabase:database_]];
8581 [controllers addObject:[[CYNavigationController alloc] initWithDatabase:database_]];
8582 [controllers addObject:[[CYNavigationController alloc] initWithDatabase:database_]];
8584 NSMutableArray *items = [NSMutableArray arrayWithObjects:
8585 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8586 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8587 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8588 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8593 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8594 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8596 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8599 for (int i = 0; i < [items count]; i++) {
8600 [[controllers objectAtIndex:i] setTabBarItem:[items objectAtIndex:i]];
8603 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8604 [tabbar_ setViewControllers:controllers];
8605 [tabbar_ setDelegate:self];
8606 [tabbar_ setSelectedIndex:0];
8608 container_ = [[CYContainer alloc] initWithDatabase:database_];
8609 [container_ setUpdateDelegate:self];
8610 [container_ setRootController:tabbar_];
8611 [window_ addSubview:[container_ view]];
8612 [[tabbar_ view] setFrame:CGRectMake(0, -20.0f, [window_ bounds].size.width, [window_ bounds].size.height)];
8614 [UIKeyboard initImplementationNow];
8618 #if RecyclePackageViews
8619 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8620 [details_ addObject:[self _packageController]];
8621 [details_ addObject:[self _packageController]];
8629 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8630 if (item != nil && IsWildcat_) {
8631 [sheet showFromBarButtonItem:item animated:YES];
8633 [sheet showInView:window_];
8640 id Alloc_(id self, SEL selector) {
8641 id object = alloc_(self, selector);
8642 lprintf("[%s]A-%p\n", self->isa->name, object);
8647 id Dealloc_(id self, SEL selector) {
8648 id object = dealloc_(self, selector);
8649 lprintf("[%s]D-%p\n", self->isa->name, object);
8653 Class $WebDefaultUIKitDelegate;
8655 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8656 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8657 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8658 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8661 static NSNumber *shouldPlayKeyboardSounds;
8665 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int soundIndex) {
8666 switch (soundIndex) {
8667 case 1104: // Keyboard Button Clicked
8668 case 1105: // Keyboard Delete Repeated
8669 if (!shouldPlayKeyboardSounds) {
8670 NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"];
8671 shouldPlayKeyboardSounds = [[dict objectForKey:@"keyboard"] ?: (id)kCFBooleanTrue retain];
8674 if (![shouldPlayKeyboardSounds boolValue])
8677 _UIHardware$_playSystemSound$(self, _cmd, soundIndex);
8681 int main(int argc, char *argv[]) { _pooled
8684 if (Class $UIDevice = objc_getClass("UIDevice")) {
8685 UIDevice *device([$UIDevice currentDevice]);
8686 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8690 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8692 /* Library Hacks {{{ */
8693 class_addMethod(objc_getClass("WebScriptObject"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &WebScriptObject$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8694 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8696 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8697 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8698 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8699 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8700 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8703 $UIHardware = objc_getClass("UIHardware");
8704 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8705 if (UIHardware$_playSystemSound$ != NULL) {
8706 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8707 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8710 /* Set Locale {{{ */
8711 Locale_ = CFLocaleCopyCurrent();
8712 Languages_ = [NSLocale preferredLanguages];
8713 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8714 //NSLog(@"%@", [Languages_ description]);
8717 if (Languages_ == nil || [Languages_ count] == 0)
8718 // XXX: consider just setting to C and then falling through?
8721 lang = [[Languages_ objectAtIndex:0] UTF8String];
8722 setenv("LANG", lang, true);
8725 //std::setlocale(LC_ALL, lang);
8726 NSLog(@"Setting Language: %s", lang);
8729 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8731 /* Parse Arguments {{{ */
8732 bool substrate(false);
8738 for (int argi(1); argi != argc; ++argi)
8739 if (strcmp(argv[argi], "--") == 0) {
8741 argv[argi] = argv[0];
8747 for (int argi(1); argi != arge; ++argi)
8748 if (strcmp(args[argi], "--substrate") == 0)
8751 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8755 App_ = [[NSBundle mainBundle] bundlePath];
8756 Home_ = NSHomeDirectory();
8762 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8763 alloc_ = alloc->method_imp;
8764 alloc->method_imp = (IMP) &Alloc_;*/
8766 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8767 dealloc_ = dealloc->method_imp;
8768 dealloc->method_imp = (IMP) &Dealloc_;*/
8770 /* System Information {{{ */
8774 size = sizeof(maxproc);
8775 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8776 perror("sysctlbyname(\"kern.maxproc\", ?)");
8777 else if (maxproc < 64) {
8779 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8780 perror("sysctlbyname(\"kern.maxproc\", #)");
8783 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8784 char *osversion = new char[size];
8785 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8786 perror("sysctlbyname(\"kern.osversion\", ?)");
8788 System_ = [NSString stringWithUTF8String:osversion];
8790 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8791 char *machine = new char[size];
8792 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8793 perror("sysctlbyname(\"hw.machine\", ?)");
8797 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8798 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8799 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8800 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8804 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8805 NSData *data((NSData *) ecid);
8806 size_t length([data length]);
8807 uint8_t bytes[length];
8808 [data getBytes:bytes];
8809 char string[length * 2 + 1];
8810 for (size_t i(0); i != length; ++i)
8811 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8812 ChipID_ = [NSString stringWithUTF8String:string];
8816 IOObjectRelease(service);
8820 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8822 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8823 Build_ = [system objectForKey:@"ProductBuildVersion"];
8824 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8825 Product_ = [info objectForKey:@"SafariProductVersion"];
8826 Safari_ = [info objectForKey:@"CFBundleVersion"];
8829 /* Load Database {{{ */
8831 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8833 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8836 if (Metadata_ == NULL)
8837 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8840 Role_ = [Metadata_ objectForKey:@"Settings"];
8842 Packages_ = [Metadata_ objectForKey:@"Packages"];
8843 Sections_ = [Metadata_ objectForKey:@"Sections"];
8844 Sources_ = [Metadata_ objectForKey:@"Sources"];
8846 Token_ = [Metadata_ objectForKey:@"Token"];
8849 if (Settings_ != nil)
8850 Role_ = [Settings_ objectForKey:@"Role"];
8852 if (Packages_ == nil) {
8853 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8854 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8857 if (Sections_ == nil) {
8858 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8859 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8862 if (Sources_ == nil) {
8863 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8864 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8869 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8872 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8874 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
8875 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
8876 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8877 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8878 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8879 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8881 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
8883 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8884 unlink("/tmp/.cydia.fw");
8886 } else if (access("/User", F_OK) != 0 || version < 2) {
8889 system("/usr/libexec/cydia/firmware.sh");
8893 _assert([[NSFileManager defaultManager]
8894 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8895 withIntermediateDirectories:YES
8900 if (access("/tmp/cydia.chk", F_OK) == 0) {
8901 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8902 _assert(errno == ENOENT);
8903 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8904 _assert(errno == ENOENT);
8907 /* APT Initialization {{{ */
8908 _assert(pkgInitConfig(*_config));
8909 _assert(pkgInitSystem(*_config, _system));
8912 _config->Set("APT::Acquire::Translation", lang);
8913 _config->Set("Acquire::http::Timeout", 15);
8914 _config->Set("Acquire::http::MaxParallel", 3);
8916 /* Color Choices {{{ */
8917 space_ = CGColorSpaceCreateDeviceRGB();
8919 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8920 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8921 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8922 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8923 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8924 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8925 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8926 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8927 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8929 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8930 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8932 /* UIKit Configuration {{{ */
8933 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8934 if ($GSFontSetUseLegacyFontMetrics != NULL)
8935 $GSFontSetUseLegacyFontMetrics(YES);
8937 // XXX: I have a feeling this was important
8938 //UIKeyboardDisableAutomaticAppearance();
8941 Colon_ = UCLocalize("COLON_DELIMITED");
8942 Error_ = UCLocalize("ERROR");
8943 Warning_ = UCLocalize("WARNING");
8946 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8948 CGColorSpaceRelease(space_);