1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2010 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "UICaboodle/UCPlatform.h"
45 #include "UICaboodle/UCLocalize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <UIKit/UIKit.h>
63 #include "iPhonePrivate.h"
65 #include <IOKit/IOKitLib.h>
67 #include <WebCore/WebCoreThread.h>
74 #include <ext/stdio_filebuf.h>
78 #include <apt-pkg/acquire.h>
79 #include <apt-pkg/acquire-item.h>
80 #include <apt-pkg/algorithms.h>
81 #include <apt-pkg/cachefile.h>
82 #include <apt-pkg/clean.h>
83 #include <apt-pkg/configuration.h>
84 #include <apt-pkg/debindexfile.h>
85 #include <apt-pkg/debmetaindex.h>
86 #include <apt-pkg/error.h>
87 #include <apt-pkg/init.h>
88 #include <apt-pkg/mmap.h>
89 #include <apt-pkg/pkgrecords.h>
90 #include <apt-pkg/sha1.h>
91 #include <apt-pkg/sourcelist.h>
92 #include <apt-pkg/sptr.h>
93 #include <apt-pkg/strutl.h>
94 #include <apt-pkg/tagfile.h>
96 #include <apr-1/apr_pools.h>
98 #include <sys/types.h>
100 #include <sys/sysctl.h>
101 #include <sys/param.h>
102 #include <sys/mount.h>
109 #include <mach-o/nlist.h>
119 #include <ext/hash_map>
121 #include "UICaboodle/BrowserView.h"
122 #include "UICaboodle/ResetView.h"
124 #include "substrate.h"
126 // Apple's sample Reachability code, ASPL licensed.
127 #include "Reachability.h"
134 #define _timestamp ({ \
136 gettimeofday(&tv, NULL); \
137 tv.tv_sec * 1000000 + tv.tv_usec; \
140 typedef std::vector<class ProfileTime *> TimeList;
150 ProfileTime(const char *name) :
154 times_.push_back(this);
157 void AddTime(uint64_t time) {
164 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
176 ProfileTimer(ProfileTime &time) :
183 time_.AddTime(_timestamp - start_);
188 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
190 std::cerr << "========" << std::endl;
193 #define _profile(name) { \
194 static ProfileTime name(#name); \
195 ProfileTimer _ ## name(name);
200 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
202 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
204 void NSLogPoint(const char *fix, const CGPoint &point) {
205 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
208 void NSLogRect(const char *fix, const CGRect &rect) {
209 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
212 static _finline NSString *CydiaURL(NSString *path) {
214 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
215 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
216 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
217 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
218 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
219 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
222 static _finline void UpdateExternalStatus(uint64_t newStatus) {
224 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
225 notify_set_state(notify_token, newStatus);
226 notify_cancel(notify_token);
228 notify_post("com.saurik.Cydia.status");
231 /* [NSObject yieldToSelector:(withObject:)] {{{*/
232 @interface NSObject (Cydia)
233 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
234 - (id) yieldToSelector:(SEL)selector;
237 @implementation NSObject (Cydia)
242 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
243 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
244 id object([[context objectAtIndex:1] nonretainedObjectValue]);
245 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
247 /* XXX: deal with exceptions */
248 id value([self performSelector:selector withObject:object]);
250 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
251 [context removeAllObjects];
252 if ([signature methodReturnLength] != 0 && value != nil)
253 [context addObject:value];
258 performSelectorOnMainThread:@selector(doNothing)
264 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
265 /*return [self performSelector:selector withObject:object];*/
267 volatile bool stopped(false);
269 NSMutableArray *context([NSMutableArray arrayWithObjects:
270 [NSValue valueWithPointer:selector],
271 [NSValue valueWithNonretainedObject:object],
272 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
275 NSThread *thread([[[NSThread alloc]
277 selector:@selector(_yieldToContext:)
283 NSRunLoop *loop([NSRunLoop currentRunLoop]);
284 NSDate *future([NSDate distantFuture]);
286 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
288 return [context count] == 0 ? nil : [context objectAtIndex:0];
291 - (id) yieldToSelector:(SEL)selector {
292 return [self yieldToSelector:selector withObject:nil];
298 @interface CYActionSheet : UIAlertView {
302 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
305 @implementation CYActionSheet
307 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
308 if ((self = [super init])) {
309 [self setTitle:title];
310 [self setDelegate:self];
311 for (NSString *button in buttons) [self addButtonWithTitle:button];
312 [self setCancelButtonIndex:index];
316 - (void)_updateFrameForDisplay {
317 [super _updateFrameForDisplay];
318 if ([self cancelButtonIndex] == -1) {
319 NSArray *buttons = [self buttons];
320 if ([buttons count]) {
321 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
322 for (UIThreePartButton *button in buttons)
323 [button setBackground:background forState:0];
328 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
329 button_ = buttonIndex + 1;
333 [self dismissWithClickedButtonIndex:-1 animated:YES];
336 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
337 [self setRunsModal:YES];
345 /* NSForcedOrderingSearch doesn't work on the iPhone */
346 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
347 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
348 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
350 /* Information Dictionaries {{{ */
351 @interface NSMutableArray (Cydia)
352 - (void) addInfoDictionary:(NSDictionary *)info;
355 @implementation NSMutableArray (Cydia)
357 - (void) addInfoDictionary:(NSDictionary *)info {
358 [self addObject:info];
363 @interface NSMutableDictionary (Cydia)
364 - (void) addInfoDictionary:(NSDictionary *)info;
367 @implementation NSMutableDictionary (Cydia)
369 - (void) addInfoDictionary:(NSDictionary *)info {
370 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
376 #define lprintf(args...) fprintf(stderr, args)
379 #define TraceLogging (1 && !ForRelease)
380 #define HistogramInsertionSort (0 && !ForRelease)
381 #define ProfileTimes (0 && !ForRelease)
382 #define ForSaurik (0 && !ForRelease)
383 #define LogBrowser (0 && !ForRelease)
384 #define TrackResize (0 && !ForRelease)
385 #define ManualRefresh (0 && !ForRelease)
386 #define ShowInternals (0 && !ForRelease)
387 #define IgnoreInstall (0 && !ForRelease)
388 #define RecycleWebViews 0
389 #define RecyclePackageViews (1 && ForRelease)
390 #define AlwaysReload (1 && !ForRelease)
394 #define _trace(args...)
399 #define _profile(name) {
402 #define PrintTimes() do {} while (false)
406 typedef uint32_t (*SKRadixFunction)(id, void *);
408 @interface NSMutableArray (Radix)
409 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
410 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
418 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
419 struct RadixItem_ *lhs(swap), *rhs(swap + count);
421 static const size_t width = 32;
422 static const size_t bits = 11;
423 static const size_t slots = 1 << bits;
424 static const size_t passes = (width + (bits - 1)) / bits;
426 size_t *hist(new size_t[slots]);
428 for (size_t pass(0); pass != passes; ++pass) {
429 memset(hist, 0, sizeof(size_t) * slots);
431 for (size_t i(0); i != count; ++i) {
432 uint32_t key(lhs[i].key);
434 key &= _not(uint32_t) >> width - bits;
439 for (size_t i(0); i != slots; ++i) {
440 size_t local(offset);
445 for (size_t i(0); i != count; ++i) {
446 uint32_t key(lhs[i].key);
448 key &= _not(uint32_t) >> width - bits;
449 rhs[hist[key]++] = lhs[i];
452 RadixItem_ *tmp(lhs);
459 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
460 for (size_t i(0); i != count; ++i)
461 [values addObject:[self objectAtIndex:lhs[i].index]];
462 [self setArray:values];
467 @implementation NSMutableArray (Radix)
469 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
470 size_t count([self count]);
475 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
476 [invocation setSelector:selector];
477 [invocation setArgument:&object atIndex:2];
479 /* XXX: this is an unsafe optimization of doomy hell */
480 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
481 _assert(method != NULL);
482 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
483 _assert(imp != NULL);
486 struct RadixItem_ *swap(new RadixItem_[count * 2]);
488 for (size_t i(0); i != count; ++i) {
489 RadixItem_ &item(swap[i]);
492 id object([self objectAtIndex:i]);
495 [invocation setTarget:object];
497 [invocation getReturnValue:&item.key];
499 item.key = imp(object, selector, object);
503 RadixSort_(self, count, swap);
506 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
507 size_t count([self count]);
508 struct RadixItem_ *swap(new RadixItem_[count * 2]);
510 for (size_t i(0); i != count; ++i) {
511 RadixItem_ &item(swap[i]);
514 id object([self objectAtIndex:i]);
515 item.key = function(object, argument);
518 RadixSort_(self, count, swap);
523 /* Insertion Sort {{{ */
525 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
526 const char *ptr = (const char *)list;
528 CFIndex half = count / 2;
529 const char *probe = ptr + elementSize * half;
530 CFComparisonResult cr = comparator(element, probe, context);
531 if (0 == cr) return (probe - (const char *)list) / elementSize;
532 ptr = (cr < 0) ? ptr : probe + elementSize;
533 count = (cr < 0) ? half : (half + (count & 1) - 1);
535 return (ptr - (const char *)list) / elementSize;
538 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
539 const char *ptr = (const char *)list;
541 CFIndex half = count / 2;
542 const char *probe = ptr + elementSize * half;
543 CFComparisonResult cr = comparator(element, probe, context);
544 if (0 == cr) return (probe - (const char *)list) / elementSize;
545 ptr = (cr < 0) ? ptr : probe + elementSize;
546 count = (cr < 0) ? half : (half + (count & 1) - 1);
548 return (ptr - (const char *)list) / elementSize;
551 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
552 if (range.length == 0)
554 const void **values(new const void *[range.length]);
555 CFArrayGetValues(array, range, values);
557 #if HistogramInsertionSort
558 uint32_t total(0), *offsets(new uint32_t[range.length]);
561 for (CFIndex index(1); index != range.length; ++index) {
562 const void *value(values[index]);
563 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
564 CFIndex correct(index);
565 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
568 if (correct != index) {
569 size_t offset(index - correct);
570 #if HistogramInsertionSort
574 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
576 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
577 values[correct] = value;
581 CFArrayReplaceValues(array, range, values, range.length);
584 #if HistogramInsertionSort
585 for (CFIndex index(0); index != range.length; ++index)
586 if (offsets[index] != 0)
587 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
588 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
595 /* Apple Bug Fixes {{{ */
596 @implementation UIWebDocumentView (Cydia)
598 - (void) _setScrollerOffset:(CGPoint)offset {
599 UIScroller *scroller([self _scroller]);
601 CGSize size([scroller contentSize]);
602 CGSize bounds([scroller bounds].size);
605 max.x = size.width - bounds.width;
606 max.y = size.height - bounds.height;
614 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
615 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
617 [scroller setOffset:offset];
623 NSUInteger WebScriptObject$countByEnumeratingWithState$objects$count$(WebScriptObject *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
624 size_t length([self count] - state->state);
627 else if (length > count)
629 for (size_t i(0); i != length; ++i)
630 objects[i] = [self objectAtIndex:state->state++];
631 state->itemsPtr = objects;
632 state->mutationsPtr = (unsigned long *) self;
636 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
637 size_t length([self length] - state->state);
640 else if (length > count)
642 for (size_t i(0); i != length; ++i)
643 objects[i] = [self item:state->state++];
644 state->itemsPtr = objects;
645 state->mutationsPtr = (unsigned long *) self;
649 /* Cydia NSString Additions {{{ */
650 @interface NSString (Cydia)
651 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
652 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
653 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
654 - (NSComparisonResult) compareByPath:(NSString *)other;
655 - (NSString *) stringByCachingURLWithCurrentCDN;
656 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
659 @implementation NSString (Cydia)
661 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
662 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
665 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
666 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
667 memcpy(data, bytes, length);
668 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
671 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
672 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
675 - (NSComparisonResult) compareByPath:(NSString *)other {
676 NSString *prefix = [self commonPrefixWithString:other options:0];
677 size_t length = [prefix length];
679 NSRange lrange = NSMakeRange(length, [self length] - length);
680 NSRange rrange = NSMakeRange(length, [other length] - length);
682 lrange = [self rangeOfString:@"/" options:0 range:lrange];
683 rrange = [other rangeOfString:@"/" options:0 range:rrange];
685 NSComparisonResult value;
687 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
688 value = NSOrderedSame;
689 else if (lrange.location == NSNotFound)
690 value = NSOrderedAscending;
691 else if (rrange.location == NSNotFound)
692 value = NSOrderedDescending;
694 value = NSOrderedSame;
696 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
697 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
698 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
699 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
701 NSComparisonResult result = [lpath compare:rpath];
702 return result == NSOrderedSame ? value : result;
705 - (NSString *) stringByCachingURLWithCurrentCDN {
707 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
708 withString:@"://cache.cydia.saurik.com/"
712 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
713 return [(id)CFURLCreateStringByAddingPercentEscapes(
718 kCFStringEncodingUTF8
725 /* C++ NSString Wrapper Cache {{{ */
732 _finline void clear_() {
733 if (cache_ != NULL) {
740 _finline bool empty() const {
744 _finline size_t size() const {
748 _finline char *data() const {
752 _finline void clear() {
757 _finline CYString() :
764 _finline ~CYString() {
768 void operator =(const CYString &rhs) {
772 if (rhs.cache_ == nil)
775 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
778 void set(apr_pool_t *pool, const char *data, size_t size) {
784 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
785 memcpy(temp, data, size);
792 _finline void set(apr_pool_t *pool, const char *data) {
793 set(pool, data, data == NULL ? 0 : strlen(data));
796 _finline void set(apr_pool_t *pool, const std::string &rhs) {
797 set(pool, rhs.data(), rhs.size());
800 bool operator ==(const CYString &rhs) const {
801 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
804 operator CFStringRef() {
805 if (cache_ == NULL) {
808 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
810 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
814 _finline operator id() {
815 return (NSString *) static_cast<CFStringRef>(*this);
819 /* C++ NSString Algorithm Adapters {{{ */
821 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
824 struct NSStringMapHash :
825 std::unary_function<NSString *, size_t>
827 _finline size_t operator ()(NSString *value) const {
828 return CFStringHashNSString((CFStringRef) value);
832 struct NSStringMapLess :
833 std::binary_function<NSString *, NSString *, bool>
835 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
836 return [lhs compare:rhs] == NSOrderedAscending;
840 struct NSStringMapEqual :
841 std::binary_function<NSString *, NSString *, bool>
843 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
844 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
845 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
846 //[lhs isEqualToString:rhs];
851 /* Perl-Compatible RegEx {{{ */
861 Pcre(const char *regex) :
866 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
869 lprintf("%d:%s\n", offset, error);
873 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
874 matches_ = new int[(capture_ + 1) * 3];
882 NSString *operator [](size_t match) {
883 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
886 bool operator ()(NSString *data) {
887 // XXX: length is for characters, not for bytes
888 return operator ()([data UTF8String], [data length]);
891 bool operator ()(const char *data, size_t size) {
893 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
897 /* Mime Addresses {{{ */
898 @interface Address : NSObject {
904 - (NSString *) address;
906 - (void) setAddress:(NSString *)address;
908 + (Address *) addressWithString:(NSString *)string;
909 - (Address *) initWithString:(NSString *)string;
912 @implementation Address
921 - (NSString *) name {
925 - (NSString *) address {
929 - (void) setAddress:(NSString *)address {
931 [address_ autorelease];
935 address_ = [address retain];
938 + (Address *) addressWithString:(NSString *)string {
939 return [[[Address alloc] initWithString:string] autorelease];
942 + (NSArray *) _attributeKeys {
943 return [NSArray arrayWithObjects:@"address", @"name", nil];
946 - (NSArray *) attributeKeys {
947 return [[self class] _attributeKeys];
950 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
951 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
954 - (Address *) initWithString:(NSString *)string {
955 if ((self = [super init]) != nil) {
956 const char *data = [string UTF8String];
957 size_t size = [string length];
959 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
961 if (address_r(data, size)) {
962 name_ = [address_r[1] retain];
963 address_ = [address_r[2] retain];
965 name_ = [string retain];
973 /* CoreGraphics Primitives {{{ */
984 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
987 Set(space, red, green, blue, alpha);
992 CGColorRelease(color_);
999 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1001 float color[] = {red, green, blue, alpha};
1002 color_ = CGColorCreate(space, color);
1005 operator CGColorRef() {
1011 /* Random Global Variables {{{ */
1012 static const int PulseInterval_ = 50000;
1013 static const int ButtonBarWidth_ = 60;
1014 static const int ButtonBarHeight_ = 48;
1015 static const float KeyboardTime_ = 0.3f;
1018 static NSArray *Finishes_;
1020 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1021 #define NotifyConfig_ "/etc/notify.conf"
1023 static bool Queuing_;
1025 static CGColor Blue_;
1026 static CGColor Blueish_;
1027 static CGColor Black_;
1028 static CGColor Off_;
1029 static CGColor White_;
1030 static CGColor Gray_;
1031 static CGColor Green_;
1032 static CGColor Purple_;
1033 static CGColor Purplish_;
1035 static UIColor *InstallingColor_;
1036 static UIColor *RemovingColor_;
1038 static NSString *App_;
1039 static NSString *Home_;
1041 static BOOL Advanced_;
1042 static BOOL Ignored_;
1044 static UIFont *Font12_;
1045 static UIFont *Font12Bold_;
1046 static UIFont *Font14_;
1047 static UIFont *Font18Bold_;
1048 static UIFont *Font22Bold_;
1050 static const char *Machine_ = NULL;
1051 static const NSString *System_ = NULL;
1052 static const NSString *SerialNumber_ = nil;
1053 static const NSString *ChipID_ = nil;
1054 static const NSString *Token_ = nil;
1055 static const NSString *UniqueID_ = nil;
1056 static const NSString *Build_ = nil;
1057 static const NSString *Product_ = nil;
1058 static const NSString *Safari_ = nil;
1060 static CFLocaleRef Locale_;
1061 static NSArray *Languages_;
1062 static CGColorSpaceRef space_;
1064 static NSDictionary *SectionMap_;
1065 static NSMutableDictionary *Metadata_;
1066 static _transient NSMutableDictionary *Settings_;
1067 static _transient NSString *Role_;
1068 static _transient NSMutableDictionary *Packages_;
1069 static _transient NSMutableDictionary *Sections_;
1070 static _transient NSMutableDictionary *Sources_;
1071 static bool Changed_;
1072 static NSDate *now_;
1074 static bool IsWildcat_;
1077 static NSMutableArray *Documents_;
1081 /* Display Helpers {{{ */
1082 inline float Interpolate(float begin, float end, float fraction) {
1083 return (end - begin) * fraction + begin;
1086 /* XXX: localize this! */
1087 NSString *SizeString(double size) {
1088 bool negative = size < 0;
1093 while (size > 1024) {
1098 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1100 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1103 static _finline CFStringRef CFCString(const char *value) {
1104 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1107 const char *StripVersion_(const char *version) {
1108 const char *colon(strchr(version, ':'));
1110 version = colon + 1;
1114 CFStringRef StripVersion(const char *version) {
1115 const char *colon(strchr(version, ':'));
1117 version = colon + 1;
1118 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1120 return CFCString(version);
1123 NSString *LocalizeSection(NSString *section) {
1124 static Pcre title_r("^(.*?) \\((.*)\\)$");
1125 if (title_r(section)) {
1126 NSString *parent(title_r[1]);
1127 NSString *child(title_r[2]);
1129 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1130 LocalizeSection(parent),
1131 LocalizeSection(child)
1135 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1138 NSString *Simplify(NSString *title) {
1139 const char *data = [title UTF8String];
1140 size_t size = [title length];
1142 static Pcre square_r("^\\[(.*)\\]$");
1143 if (square_r(data, size))
1144 return Simplify(square_r[1]);
1146 static Pcre paren_r("^\\((.*)\\)$");
1147 if (paren_r(data, size))
1148 return Simplify(paren_r[1]);
1150 static Pcre title_r("^(.*?) \\((.*)\\)$");
1151 if (title_r(data, size))
1152 return Simplify(title_r[1]);
1158 NSString *GetLastUpdate() {
1159 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1162 return UCLocalize("NEVER_OR_UNKNOWN");
1164 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1165 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1167 CFRelease(formatter);
1169 return [(NSString *) formatted autorelease];
1172 bool isSectionVisible(NSString *section) {
1173 NSDictionary *metadata([Sections_ objectForKey:section]);
1174 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1175 return hidden == nil || ![hidden boolValue];
1180 /* Delegate Prototypes {{{ */
1184 @interface NSObject (ProgressDelegate)
1187 @protocol ProgressDelegate
1188 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1189 - (void) setProgressTitle:(NSString *)title;
1190 - (void) setProgressPercent:(float)percent;
1191 - (void) startProgress;
1192 - (void) addProgressOutput:(NSString *)output;
1193 - (bool) isCancelling:(size_t)received;
1196 @protocol ConfigurationDelegate
1197 - (void) repairWithSelector:(SEL)selector;
1198 - (void) setConfigurationData:(NSString *)data;
1201 @class PackageController;
1203 @protocol CydiaDelegate
1204 - (void) setPackageController:(PackageController *)view;
1205 - (void) clearPackage:(Package *)package;
1206 - (void) installPackage:(Package *)package;
1207 - (void) installPackages:(NSArray *)packages;
1208 - (void) removePackage:(Package *)package;
1209 - (void) beginUpdate;
1211 - (void) distUpgrade;
1213 - (void) updateData;
1215 - (void) showSettings;
1216 - (UIProgressHUD *) addProgressHUD;
1217 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1218 - (CYViewController *) pageForPackage:(NSString *)name;
1219 - (PackageController *) packageController;
1220 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1224 /* Status Delegation {{{ */
1226 public pkgAcquireStatus
1229 _transient NSObject<ProgressDelegate> *delegate_;
1237 void setDelegate(id delegate) {
1238 delegate_ = delegate;
1241 NSObject<ProgressDelegate> *getDelegate() const {
1245 virtual bool MediaChange(std::string media, std::string drive) {
1249 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1252 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1253 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1254 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1257 virtual void Done(pkgAcquire::ItemDesc &item) {
1260 virtual void Fail(pkgAcquire::ItemDesc &item) {
1262 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1263 item.Owner->Status == pkgAcquire::Item::StatDone
1267 std::string &error(item.Owner->ErrorText);
1271 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1272 NSArray *fields([description componentsSeparatedByString:@" "]);
1273 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1275 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1276 withObject:[NSArray arrayWithObjects:
1277 [NSString stringWithUTF8String:error.c_str()],
1284 virtual bool Pulse(pkgAcquire *Owner) {
1285 bool value = pkgAcquireStatus::Pulse(Owner);
1288 double(CurrentBytes + CurrentItems) /
1289 double(TotalBytes + TotalItems)
1292 [delegate_ setProgressPercent:percent];
1293 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1296 virtual void Start() {
1297 [delegate_ startProgress];
1300 virtual void Stop() {
1304 /* Progress Delegation {{{ */
1309 _transient id<ProgressDelegate> delegate_;
1313 virtual void Update() {
1314 /*if (abs(Percent - percent_) > 2)
1315 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1319 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1320 [delegate_ setProgressPercent:(Percent / 100)];*/
1330 void setDelegate(id delegate) {
1331 delegate_ = delegate;
1334 id getDelegate() const {
1338 virtual void Done() {
1340 //[delegate_ setProgressPercent:1];
1345 /* Database Interface {{{ */
1346 typedef std::map< unsigned long, _H<Source> > SourceMap;
1348 @interface Database : NSObject {
1354 pkgCacheFile cache_;
1355 pkgDepCache::Policy *policy_;
1356 pkgRecords *records_;
1357 pkgProblemResolver *resolver_;
1358 pkgAcquire *fetcher_;
1360 SPtr<pkgPackageManager> manager_;
1361 pkgSourceList *list_;
1364 NSMutableArray *packages_;
1366 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1375 + (Database *) sharedInstance;
1378 - (void) _readCydia:(NSNumber *)fd;
1379 - (void) _readStatus:(NSNumber *)fd;
1380 - (void) _readOutput:(NSNumber *)fd;
1384 - (Package *) packageWithName:(NSString *)name;
1386 - (pkgCacheFile &) cache;
1387 - (pkgDepCache::Policy *) policy;
1388 - (pkgRecords *) records;
1389 - (pkgProblemResolver *) resolver;
1390 - (pkgAcquire &) fetcher;
1391 - (pkgSourceList &) list;
1392 - (NSArray *) packages;
1393 - (NSArray *) sources;
1394 - (void) reloadData;
1402 - (void) setVisible;
1404 - (void) updateWithStatus:(Status &)status;
1406 - (void) setDelegate:(id)delegate;
1407 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1410 /* Delegate Helpers {{{ */
1411 @implementation NSObject (ProgressDelegate)
1413 - (void) _setProgressErrorPackage:(NSArray *)args {
1414 [self performSelector:@selector(setProgressError:forPackage:)
1415 withObject:[args objectAtIndex:0]
1416 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1420 - (void) _setProgressErrorTitle:(NSArray *)args {
1421 [self performSelector:@selector(setProgressError:withTitle:)
1422 withObject:[args objectAtIndex:0]
1423 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1427 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1428 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1429 withObject:[NSArray arrayWithObjects:error, title, nil]
1434 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1435 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1436 // XXX: holy typecast batman!
1437 [(id<ProgressDelegate>)self setProgressError:error withTitle:(package == nil ? id : [package name])];
1443 /* Source Class {{{ */
1444 @interface Source : NSObject {
1445 CYString depiction_;
1446 CYString description_;
1452 CYString distribution_;
1457 NSString *authority_;
1459 CYString defaultIcon_;
1461 NSDictionary *record_;
1465 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1467 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1469 - (NSString *) depictionForPackage:(NSString *)package;
1470 - (NSString *) supportForPackage:(NSString *)package;
1472 - (NSDictionary *) record;
1476 - (NSString *) distribution;
1477 - (NSString *) type;
1479 - (NSString *) host;
1481 - (NSString *) name;
1482 - (NSString *) description;
1483 - (NSString *) label;
1484 - (NSString *) origin;
1485 - (NSString *) version;
1487 - (NSString *) defaultIcon;
1491 @implementation Source
1495 distribution_.clear();
1498 description_.clear();
1504 defaultIcon_.clear();
1506 if (record_ != nil) {
1516 if (authority_ != nil) {
1517 [authority_ release];
1527 + (NSArray *) _attributeKeys {
1528 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1531 - (NSArray *) attributeKeys {
1532 return [[self class] _attributeKeys];
1535 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1536 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1539 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1542 trusted_ = index->IsTrusted();
1544 uri_.set(pool, index->GetURI());
1545 distribution_.set(pool, index->GetDist());
1546 type_.set(pool, index->GetType());
1548 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1549 if (dindex != NULL) {
1551 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1554 pkgTagFile tags(&fd);
1556 pkgTagSection section;
1563 {"default-icon", &defaultIcon_},
1564 {"depiction", &depiction_},
1565 {"description", &description_},
1567 {"origin", &origin_},
1568 {"support", &support_},
1569 {"version", &version_},
1572 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1573 const char *start, *end;
1575 if (section.Find(names[i].name_, start, end)) {
1576 CYString &value(*names[i].value_);
1577 value.set(pool, start, end - start);
1583 record_ = [Sources_ objectForKey:[self key]];
1585 record_ = [record_ retain];
1587 NSURL *url([NSURL URLWithString:uri_]);
1591 host_ = [[host_ lowercaseString] retain];
1596 authority_ = [url path];
1598 if (authority_ != nil)
1599 authority_ = [authority_ retain];
1602 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1603 if ((self = [super init]) != nil) {
1604 [self setMetaIndex:index inPool:pool];
1608 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1609 NSDictionary *lhr = [self record];
1610 NSDictionary *rhr = [source record];
1613 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1615 NSString *lhs = [self name];
1616 NSString *rhs = [source name];
1618 if ([lhs length] != 0 && [rhs length] != 0) {
1619 unichar lhc = [lhs characterAtIndex:0];
1620 unichar rhc = [rhs characterAtIndex:0];
1622 if (isalpha(lhc) && !isalpha(rhc))
1623 return NSOrderedAscending;
1624 else if (!isalpha(lhc) && isalpha(rhc))
1625 return NSOrderedDescending;
1628 return [lhs compare:rhs options:LaxCompareOptions_];
1631 - (NSString *) depictionForPackage:(NSString *)package {
1632 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1635 - (NSString *) supportForPackage:(NSString *)package {
1636 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1639 - (NSDictionary *) record {
1647 - (NSString *) uri {
1651 - (NSString *) distribution {
1652 return distribution_;
1655 - (NSString *) type {
1659 - (NSString *) key {
1660 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1663 - (NSString *) host {
1667 - (NSString *) name {
1668 return origin_.empty() ? authority_ : origin_;
1671 - (NSString *) description {
1672 return description_;
1675 - (NSString *) label {
1676 return label_.empty() ? authority_ : label_;
1679 - (NSString *) origin {
1683 - (NSString *) version {
1687 - (NSString *) defaultIcon {
1688 return defaultIcon_;
1693 /* Relationship Class {{{ */
1694 @interface Relationship : NSObject {
1699 - (NSString *) type;
1701 - (NSString *) name;
1705 @implementation Relationship
1713 - (NSString *) type {
1721 - (NSString *) name {
1728 /* Package Class {{{ */
1729 @interface Package : NSObject {
1733 pkgCache::VerIterator version_;
1734 pkgCache::PkgIterator iterator_;
1735 _transient Database *database_;
1736 pkgCache::VerFileIterator file_;
1743 NSString *section$_;
1750 CYString installed_;
1756 CYString depiction_;
1767 NSMutableArray *tags_;
1770 NSArray *relationships_;
1772 NSMutableDictionary *metadata_;
1773 _transient NSDate *firstSeen_;
1774 _transient NSDate *lastSeen_;
1778 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1779 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1781 - (pkgCache::PkgIterator) iterator;
1784 - (NSString *) section;
1785 - (NSString *) simpleSection;
1787 - (NSString *) longSection;
1788 - (NSString *) shortSection;
1792 - (Address *) maintainer;
1794 - (NSString *) longDescription;
1795 - (NSString *) shortDescription;
1798 - (NSMutableDictionary *) metadata;
1800 - (BOOL) subscribed;
1803 - (NSString *) latest;
1804 - (NSString *) installed;
1805 - (BOOL) uninstalled;
1808 - (BOOL) upgradableAndEssential:(BOOL)essential;
1811 - (BOOL) unfiltered;
1815 - (BOOL) halfConfigured;
1816 - (BOOL) halfInstalled;
1818 - (NSString *) mode;
1820 - (void) setVisible;
1823 - (NSString *) name;
1825 - (NSString *) homepage;
1826 - (NSString *) depiction;
1827 - (Address *) author;
1829 - (NSString *) support;
1831 - (NSArray *) files;
1832 - (NSArray *) relationships;
1833 - (NSArray *) warnings;
1834 - (NSArray *) applications;
1836 - (Source *) source;
1837 - (NSString *) role;
1839 - (BOOL) matches:(NSString *)text;
1841 - (bool) hasSupportingRole;
1842 - (BOOL) hasTag:(NSString *)tag;
1843 - (NSString *) primaryPurpose;
1844 - (NSArray *) purposes;
1845 - (bool) isCommercial;
1847 - (CYString &) cyname;
1849 - (uint32_t) compareBySection:(NSArray *)sections;
1851 - (uint32_t) compareForChanges;
1856 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1857 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1858 - (bool) isInstalledAndVisible:(NSNumber *)number;
1859 - (bool) isVisibleInSection:(NSString *)section;
1860 - (bool) isVisibleInSource:(Source *)source;
1864 uint32_t PackageChangesRadix(Package *self, void *) {
1869 uint32_t timestamp : 30;
1870 uint32_t ignored : 1;
1871 uint32_t upgradable : 1;
1875 bool upgradable([self upgradableAndEssential:YES]);
1876 value.bits.upgradable = upgradable ? 1 : 0;
1879 value.bits.timestamp = 0;
1880 value.bits.ignored = [self ignored] ? 0 : 1;
1881 value.bits.upgradable = 1;
1883 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1884 value.bits.ignored = 0;
1885 value.bits.upgradable = 0;
1888 return _not(uint32_t) - value.key;
1891 _finline static void Stifle(uint8_t &value) {
1894 uint32_t PackagePrefixRadix(Package *self, void *context) {
1895 size_t offset(reinterpret_cast<size_t>(context));
1896 CYString &name([self cyname]);
1898 size_t size(name.size());
1901 char *text(name.data());
1904 if (!isdigit(text[0]))
1908 while (size != digits && isdigit(text[digits]))
1918 if (offset == 0 && zeros != 0) {
1919 memset(data, '0', zeros);
1920 memcpy(data + zeros, text, 4 - zeros);
1922 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1923 if (size <= offset - zeros)
1926 text += offset - zeros;
1927 size -= offset - zeros;
1930 memcpy(data, text, 4);
1932 memcpy(data, text, size);
1933 memset(data + size, 0, 4 - size);
1936 for (size_t i(0); i != 4; ++i)
1937 if (isalpha(data[i]))
1942 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1944 /* XXX: ntohl may be more honest */
1945 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1948 CYString &(*PackageName)(Package *self, SEL sel);
1950 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1951 _profile(PackageNameCompare)
1952 CYString &lhi(PackageName(lhs, @selector(cyname)));
1953 CYString &rhi(PackageName(rhs, @selector(cyname)));
1954 CFStringRef lhn(lhi), rhn(rhi);
1957 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1958 else if (rhn == NULL)
1959 return NSOrderedDescending;
1961 _profile(PackageNameCompare$NumbersLast)
1962 if (!lhi.empty() && !rhi.empty()) {
1963 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1964 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1965 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1966 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1967 return lha ? NSOrderedAscending : NSOrderedDescending;
1971 CFIndex length = CFStringGetLength(lhn);
1973 _profile(PackageNameCompare$Compare)
1974 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1979 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1980 return PackageNameCompare(*lhs, *rhs, context);
1983 struct PackageNameOrdering :
1984 std::binary_function<Package *, Package *, bool>
1986 _finline bool operator ()(Package *lhs, Package *rhs) const {
1987 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1991 @implementation Package
1993 - (NSString *) description {
1994 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2000 if (section$_ != nil)
2001 [section$_ release];
2006 if (sponsor$_ != nil)
2007 [sponsor$_ release];
2008 if (author$_ != nil)
2015 if (relationships_ != nil)
2016 [relationships_ release];
2017 if (metadata_ != nil)
2018 [metadata_ release];
2023 + (NSString *) webScriptNameForSelector:(SEL)selector {
2024 if (selector == @selector(hasTag:))
2030 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2031 return [self webScriptNameForSelector:selector] == nil;
2034 + (NSArray *) _attributeKeys {
2035 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];
2038 - (NSArray *) attributeKeys {
2039 return [[self class] _attributeKeys];
2042 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2043 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2053 _profile(Package$parse)
2054 pkgRecords::Parser *parser;
2056 _profile(Package$parse$Lookup)
2057 parser = &[database_ records]->Lookup(file_);
2062 _profile(Package$parse$Find)
2068 {"depiction", &depiction_},
2069 {"homepage", &homepage_},
2070 {"website", &website},
2072 {"support", &support_},
2073 {"sponsor", &sponsor_},
2074 {"author", &author_},
2077 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2078 const char *start, *end;
2080 if (parser->Find(names[i].name_, start, end)) {
2081 CYString &value(*names[i].value_);
2082 _profile(Package$parse$Value)
2083 value.set(pool_, start, end - start);
2089 _profile(Package$parse$Tagline)
2090 const char *start, *end;
2091 if (parser->ShortDesc(start, end)) {
2092 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2095 while (stop != start && stop[-1] == '\r')
2097 tagline_.set(pool_, start, stop - start);
2101 _profile(Package$parse$Retain)
2102 if (homepage_.empty())
2103 homepage_ = website;
2104 if (homepage_ == depiction_)
2110 - (void) setVisible {
2111 visible_ = required_ && [self unfiltered];
2114 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2115 if ((self = [super init]) != nil) {
2116 _profile(Package$initWithVersion)
2117 @synchronized (database) {
2118 era_ = [database era];
2122 iterator_ = version.ParentPkg();
2123 database_ = database;
2125 _profile(Package$initWithVersion$Latest)
2126 latest_ = (NSString *) StripVersion(version_.VerStr());
2129 pkgCache::VerIterator current;
2130 _profile(Package$initWithVersion$Versions)
2131 current = iterator_.CurrentVer();
2133 installed_.set(pool_, StripVersion_(current.VerStr()));
2135 if (!version_.end())
2136 file_ = version_.FileList();
2138 pkgCache &cache([database_ cache]);
2139 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2143 _profile(Package$initWithVersion$Name)
2144 id_.set(pool_, iterator_.Name());
2145 name_.set(pool, iterator_.Display());
2149 _profile(Package$initWithVersion$Source)
2150 source_ = [database_ getSource:file_.File()];
2159 _profile(Package$initWithVersion$Tags)
2160 pkgCache::TagIterator tag(iterator_.TagList());
2162 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2164 const char *name(tag.Name());
2165 [tags_ addObject:(NSString *)CFCString(name)];
2166 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2167 role_ = (NSString *) CFCString(name + 6);
2168 if (required_ && strncmp(name, "require::", 9) == 0 && (
2173 } while (!tag.end());
2177 bool changed(false);
2178 NSString *key([id_ lowercaseString]);
2180 _profile(Package$initWithVersion$Metadata)
2181 metadata_ = [Packages_ objectForKey:key];
2183 if (metadata_ == nil) {
2186 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2187 firstSeen_, @"FirstSeen",
2188 latest_, @"LastVersion",
2193 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2194 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2196 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2197 subscribed_ = [subscribed boolValue];
2199 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2201 if (firstSeen_ == nil) {
2202 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2203 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2207 if (version == nil) {
2208 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2210 } else if (![version isEqualToString:latest_]) {
2211 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2213 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2218 metadata_ = [metadata_ retain];
2221 [Packages_ setObject:metadata_ forKey:key];
2226 _profile(Package$initWithVersion$Section)
2227 section_.set(pool_, iterator_.Section());
2230 obsolete_ = [self hasTag:@"cydia::obsolete"];
2231 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2233 } _end } return self;
2236 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2237 @synchronized ([Database class]) {
2238 pkgCache::VerIterator version;
2240 _profile(Package$packageWithIterator$GetCandidateVer)
2241 version = [database policy]->GetCandidateVer(iterator);
2247 return [[[Package alloc]
2248 initWithVersion:version
2255 - (pkgCache::PkgIterator) iterator {
2259 - (NSString *) section {
2260 if (section$_ == nil) {
2261 if (section_.empty())
2264 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2265 NSString *name(section_);
2268 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2269 if (NSString *rename = [value objectForKey:@"Rename"]) {
2274 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2278 - (NSString *) simpleSection {
2279 if (NSString *section = [self section])
2280 return Simplify(section);
2285 - (NSString *) longSection {
2286 return LocalizeSection([self section]);
2289 - (NSString *) shortSection {
2290 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2293 - (NSString *) uri {
2296 pkgIndexFile *index;
2297 pkgCache::PkgFileIterator file(file_.File());
2298 if (![database_ list].FindIndex(file, index))
2300 return [NSString stringWithUTF8String:iterator_->Path];
2301 //return [NSString stringWithUTF8String:file.Site()];
2302 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2306 - (Address *) maintainer {
2309 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2310 const std::string &maintainer(parser->Maintainer());
2311 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2315 return version_.end() ? 0 : version_->InstalledSize;
2318 - (NSString *) longDescription {
2321 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2322 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2324 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2325 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2326 if ([lines count] < 2)
2329 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2330 for (size_t i(1), e([lines count]); i != e; ++i) {
2331 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2332 [trimmed addObject:trim];
2335 return [trimmed componentsJoinedByString:@"\n"];
2338 - (NSString *) shortDescription {
2343 _profile(Package$index)
2344 CFStringRef name((CFStringRef) [self name]);
2345 if (CFStringGetLength(name) == 0)
2347 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2348 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2350 return toupper(character);
2354 - (NSMutableDictionary *) metadata {
2359 if (subscribed_ && lastSeen_ != nil)
2364 - (BOOL) subscribed {
2369 NSDictionary *metadata([self metadata]);
2370 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2371 return [ignored boolValue];
2376 - (NSString *) latest {
2380 - (NSString *) installed {
2384 - (BOOL) uninstalled {
2385 return installed_.empty();
2389 return !version_.end();
2392 - (BOOL) upgradableAndEssential:(BOOL)essential {
2393 _profile(Package$upgradableAndEssential)
2394 pkgCache::VerIterator current(iterator_.CurrentVer());
2396 return essential && essential_ && visible_;
2398 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2402 - (BOOL) essential {
2407 return [database_ cache][iterator_].InstBroken();
2410 - (BOOL) unfiltered {
2411 NSString *section([self section]);
2412 return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
2420 unsigned char current(iterator_->CurrentState);
2421 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2424 - (BOOL) halfConfigured {
2425 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2428 - (BOOL) halfInstalled {
2429 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2433 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2434 return state.Mode != pkgDepCache::ModeKeep;
2437 - (NSString *) mode {
2438 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2440 switch (state.Mode) {
2441 case pkgDepCache::ModeDelete:
2442 if ((state.iFlags & pkgDepCache::Purge) != 0)
2446 case pkgDepCache::ModeKeep:
2447 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2448 return @"REINSTALL";
2449 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2453 case pkgDepCache::ModeInstall:
2454 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2455 return @"REINSTALL";
2456 else*/ switch (state.Status) {
2458 return @"DOWNGRADE";
2464 return @"NEW_INSTALL";
2475 - (NSString *) name {
2476 return name_.empty() ? id_ : name_;
2479 - (UIImage *) icon {
2480 NSString *section = [self simpleSection];
2484 if ([icon_ hasPrefix:@"file:///"])
2485 // XXX: correct escaping
2486 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2487 if (icon == nil) if (section != nil)
2488 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2489 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2490 if ([dicon hasPrefix:@"file:///"])
2491 // XXX: correct escaping
2492 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2494 icon = [UIImage applicationImageNamed:@"unknown.png"];
2498 - (NSString *) homepage {
2502 - (NSString *) depiction {
2503 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2506 - (Address *) sponsor {
2507 if (sponsor$_ == nil) {
2508 if (sponsor_.empty())
2510 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2514 - (Address *) author {
2515 if (author$_ == nil) {
2516 if (author_.empty())
2518 author$_ = [[Address addressWithString:author_] retain];
2522 - (NSString *) support {
2523 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2526 - (NSArray *) files {
2527 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2528 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2531 fin.open([path UTF8String]);
2536 while (std::getline(fin, line))
2537 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2542 - (NSArray *) relationships {
2543 return relationships_;
2546 - (NSArray *) warnings {
2547 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2548 const char *name(iterator_.Name());
2550 size_t length(strlen(name));
2551 if (length < 2) invalid:
2552 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2553 else for (size_t i(0); i != length; ++i)
2555 /* XXX: technically this is not allowed */
2556 (name[i] < 'A' || name[i] > 'Z') &&
2557 (name[i] < 'a' || name[i] > 'z') &&
2558 (name[i] < '0' || name[i] > '9') &&
2559 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2562 if (strcmp(name, "cydia") != 0) {
2565 bool _private = false;
2568 bool repository = [[self section] isEqualToString:@"Repositories"];
2570 if (NSArray *files = [self files])
2571 for (NSString *file in files)
2572 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2574 else if (!user && [file isEqualToString:@"/User"])
2576 else if (!_private && [file isEqualToString:@"/private"])
2578 else if (!stash && [file isEqualToString:@"/var/stash"])
2581 /* XXX: this is not sensitive enough. only some folders are valid. */
2582 if (cydia && !repository)
2583 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2585 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2587 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2589 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2592 return [warnings count] == 0 ? nil : warnings;
2595 - (NSArray *) applications {
2596 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2598 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2600 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2601 if (NSArray *files = [self files])
2602 for (NSString *file in files)
2603 if (application_r(file)) {
2604 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2605 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2606 if ([id isEqualToString:me])
2609 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2611 display = application_r[1];
2613 NSString *bundle([file stringByDeletingLastPathComponent]);
2614 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2615 if (icon == nil || [icon length] == 0)
2617 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2619 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2620 [applications addObject:application];
2622 [application addObject:id];
2623 [application addObject:display];
2624 [application addObject:url];
2627 return [applications count] == 0 ? nil : applications;
2630 - (Source *) source {
2632 @synchronized (database_) {
2633 if ([database_ era] != era_ || file_.end())
2636 source_ = [database_ getSource:file_.File()];
2648 - (NSString *) role {
2652 - (BOOL) matches:(NSString *)text {
2658 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2659 if (range.location != NSNotFound)
2662 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2663 if (range.location != NSNotFound)
2666 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2667 if (range.location != NSNotFound)
2673 - (bool) hasSupportingRole {
2676 if ([role_ isEqualToString:@"enduser"])
2678 if ([Role_ isEqualToString:@"User"])
2680 if ([role_ isEqualToString:@"hacker"])
2682 if ([Role_ isEqualToString:@"Hacker"])
2684 if ([role_ isEqualToString:@"developer"])
2686 if ([Role_ isEqualToString:@"Developer"])
2691 - (BOOL) hasTag:(NSString *)tag {
2692 return tags_ == nil ? NO : [tags_ containsObject:tag];
2695 - (NSString *) primaryPurpose {
2696 for (NSString *tag in tags_)
2697 if ([tag hasPrefix:@"purpose::"])
2698 return [tag substringFromIndex:9];
2702 - (NSArray *) purposes {
2703 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2704 for (NSString *tag in tags_)
2705 if ([tag hasPrefix:@"purpose::"])
2706 [purposes addObject:[tag substringFromIndex:9]];
2707 return [purposes count] == 0 ? nil : purposes;
2710 - (bool) isCommercial {
2711 return [self hasTag:@"cydia::commercial"];
2714 - (CYString &) cyname {
2715 return name_.empty() ? id_ : name_;
2718 - (uint32_t) compareBySection:(NSArray *)sections {
2719 NSString *section([self section]);
2720 for (size_t i(0), e([sections count]); i != e; ++i) {
2721 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2725 return _not(uint32_t);
2728 - (uint32_t) compareForChanges {
2733 uint32_t timestamp : 30;
2734 uint32_t ignored : 1;
2735 uint32_t upgradable : 1;
2739 bool upgradable([self upgradableAndEssential:YES]);
2740 value.bits.upgradable = upgradable ? 1 : 0;
2743 value.bits.timestamp = 0;
2744 value.bits.ignored = [self ignored] ? 0 : 1;
2745 value.bits.upgradable = 1;
2747 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2748 value.bits.ignored = 0;
2749 value.bits.upgradable = 0;
2752 return _not(uint32_t) - value.key;
2756 pkgProblemResolver *resolver = [database_ resolver];
2757 resolver->Clear(iterator_);
2758 resolver->Protect(iterator_);
2762 pkgProblemResolver *resolver = [database_ resolver];
2763 resolver->Clear(iterator_);
2764 resolver->Protect(iterator_);
2765 pkgCacheFile &cache([database_ cache]);
2766 cache->MarkInstall(iterator_, false);
2767 pkgDepCache::StateCache &state((*cache)[iterator_]);
2768 if (!state.Install())
2769 cache->SetReInstall(iterator_, true);
2773 pkgProblemResolver *resolver = [database_ resolver];
2774 resolver->Clear(iterator_);
2775 resolver->Protect(iterator_);
2776 resolver->Remove(iterator_);
2777 [database_ cache]->MarkDelete(iterator_, true);
2780 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2781 _profile(Package$isUnfilteredAndSearchedForBy)
2784 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2785 value &= [self unfiltered];
2788 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2789 value &= [self matches:search];
2796 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2797 if ([search length] == 0)
2800 _profile(Package$isUnfilteredAndSelectedForBy)
2803 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2804 value &= [self unfiltered];
2807 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2808 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2815 - (bool) isInstalledAndVisible:(NSNumber *)number {
2816 return (![number boolValue] || [self visible]) && ![self uninstalled];
2819 - (bool) isVisibleInSection:(NSString *)name {
2820 NSString *section = [self section];
2825 section == nil && [name length] == 0 ||
2826 [name isEqualToString:section]
2830 - (bool) isVisibleInSource:(Source *)source {
2831 return [self source] == source && [self visible];
2836 /* Section Class {{{ */
2837 @interface Section : NSObject {
2842 NSString *localized_;
2845 - (NSComparisonResult) compareByLocalized:(Section *)section;
2846 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2847 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2848 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2849 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2850 - (NSString *) name;
2857 - (void) addToCount;
2859 - (void) setCount:(size_t)count;
2860 - (NSString *) localized;
2864 @implementation Section
2868 if (localized_ != nil)
2869 [localized_ release];
2873 - (NSComparisonResult) compareByLocalized:(Section *)section {
2874 NSString *lhs(localized_);
2875 NSString *rhs([section localized]);
2877 /*if ([lhs length] != 0 && [rhs length] != 0) {
2878 unichar lhc = [lhs characterAtIndex:0];
2879 unichar rhc = [rhs characterAtIndex:0];
2881 if (isalpha(lhc) && !isalpha(rhc))
2882 return NSOrderedAscending;
2883 else if (!isalpha(lhc) && isalpha(rhc))
2884 return NSOrderedDescending;
2887 return [lhs compare:rhs options:LaxCompareOptions_];
2890 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2891 if ((self = [self initWithName:name localize:NO]) != nil) {
2892 if (localized != nil)
2893 localized_ = [localized retain];
2897 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2898 return [self initWithName:name row:0 localize:localize];
2901 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2902 if ((self = [super init]) != nil) {
2903 name_ = [name retain];
2907 localized_ = [LocalizeSection(name_) retain];
2911 /* XXX: localize the index thingees */
2912 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2913 if ((self = [super init]) != nil) {
2914 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2920 - (NSString *) name {
2940 - (void) addToCount {
2944 - (void) setCount:(size_t)count {
2948 - (NSString *) localized {
2955 static NSString *Colon_;
2956 static NSString *Error_;
2957 static NSString *Warning_;
2959 /* Database Implementation {{{ */
2960 @implementation Database
2962 + (Database *) sharedInstance {
2963 static Database *instance;
2964 if (instance == nil)
2965 instance = [[Database alloc] init];
2975 NSRecycleZone(zone_);
2976 // XXX: malloc_destroy_zone(zone_);
2977 apr_pool_destroy(pool_);
2981 - (void) _readCydia:(NSNumber *)fd { _pooled
2982 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2983 std::istream is(&ib);
2986 static Pcre finish_r("^finish:([^:]*)$");
2988 while (std::getline(is, line)) {
2989 const char *data(line.c_str());
2990 size_t size = line.size();
2991 lprintf("C:%s\n", data);
2993 if (finish_r(data, size)) {
2994 NSString *finish = finish_r[1];
2995 int index = [Finishes_ indexOfObject:finish];
2996 if (index != INT_MAX && index > Finish_)
3004 - (void) _readStatus:(NSNumber *)fd { _pooled
3005 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3006 std::istream is(&ib);
3009 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3010 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3012 while (std::getline(is, line)) {
3013 const char *data(line.c_str());
3014 size_t size(line.size());
3015 lprintf("S:%s\n", data);
3017 if (conffile_r(data, size)) {
3018 [delegate_ setConfigurationData:conffile_r[1]];
3019 } else if (strncmp(data, "status: ", 8) == 0) {
3020 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3021 [delegate_ setProgressTitle:string];
3022 } else if (pmstatus_r(data, size)) {
3023 std::string type([pmstatus_r[1] UTF8String]);
3024 NSString *id = pmstatus_r[2];
3026 float percent([pmstatus_r[3] floatValue]);
3027 [delegate_ setProgressPercent:(percent / 100)];
3029 NSString *string = pmstatus_r[4];
3031 if (type == "pmerror")
3032 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3033 withObject:[NSArray arrayWithObjects:string, id, nil]
3036 else if (type == "pmstatus") {
3037 [delegate_ setProgressTitle:string];
3038 } else if (type == "pmconffile")
3039 [delegate_ setConfigurationData:string];
3041 lprintf("E:unknown pmstatus\n");
3043 lprintf("E:unknown status\n");
3049 - (void) _readOutput:(NSNumber *)fd { _pooled
3050 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3051 std::istream is(&ib);
3054 while (std::getline(is, line)) {
3055 lprintf("O:%s\n", line.c_str());
3056 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3066 - (Package *) packageWithName:(NSString *)name {
3067 @synchronized ([Database class]) {
3068 if (static_cast<pkgDepCache *>(cache_) == NULL)
3070 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3071 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3074 - (Database *) init {
3075 if ((self = [super init]) != nil) {
3082 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3083 apr_pool_create(&pool_, NULL);
3085 packages_ = [[NSMutableArray alloc] init];
3089 _assert(pipe(fds) != -1);
3092 _config->Set("APT::Keep-Fds::", cydiafd_);
3093 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3096 detachNewThreadSelector:@selector(_readCydia:)
3098 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3101 _assert(pipe(fds) != -1);
3105 detachNewThreadSelector:@selector(_readStatus:)
3107 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3110 _assert(pipe(fds) != -1);
3111 _assert(dup2(fds[0], 0) != -1);
3112 _assert(close(fds[0]) != -1);
3114 input_ = fdopen(fds[1], "a");
3116 _assert(pipe(fds) != -1);
3117 _assert(dup2(fds[1], 1) != -1);
3118 _assert(close(fds[1]) != -1);
3121 detachNewThreadSelector:@selector(_readOutput:)
3123 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3128 - (pkgCacheFile &) cache {
3132 - (pkgDepCache::Policy *) policy {
3136 - (pkgRecords *) records {
3140 - (pkgProblemResolver *) resolver {
3144 - (pkgAcquire &) fetcher {
3148 - (pkgSourceList &) list {
3152 - (NSArray *) packages {
3156 - (NSArray *) sources {
3157 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3158 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3159 [sources addObject:i->second];
3163 - (NSArray *) issues {
3164 if (cache_->BrokenCount() == 0)
3167 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3169 for (Package *package in packages_) {
3170 if (![package broken])
3172 pkgCache::PkgIterator pkg([package iterator]);
3174 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3175 [entry addObject:[package name]];
3176 [issues addObject:entry];
3178 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3182 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3183 pkgCache::DepIterator start;
3184 pkgCache::DepIterator end;
3185 dep.GlobOr(start, end); // ++dep
3187 if (!cache_->IsImportantDep(end))
3189 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3192 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3193 [entry addObject:failure];
3194 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3196 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3197 if (Package *package = [self packageWithName:name])
3198 name = [package name];
3199 [failure addObject:name];
3201 pkgCache::PkgIterator target(start.TargetPkg());
3202 if (target->ProvidesList != 0)
3203 [failure addObject:@"?"];
3205 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3207 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3208 else if (!cache_[target].CandidateVerIter(cache_).end())
3209 [failure addObject:@"-"];
3210 else if (target->ProvidesList == 0)
3211 [failure addObject:@"!"];
3213 [failure addObject:@"%"];
3217 if (start.TargetVer() != 0)
3218 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3229 - (bool) popErrorWithTitle:(NSString *)title {
3231 std::string message;
3233 while (!_error->empty()) {
3235 bool warning(!_error->PopMessage(error));
3239 size_t size(error.size());
3240 if (size == 0 || error[size - 1] != '\n')
3242 error.resize(size - 1);
3244 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3246 if (!message.empty())
3251 if (fatal && !message.empty())
3252 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3257 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3258 return [self popErrorWithTitle:title] || !success;
3261 - (void) reloadData { _pooled
3262 @synchronized ([Database class]) {
3263 @synchronized (self) {
3267 [packages_ removeAllObjects];
3293 apr_pool_clear(pool_);
3294 NSRecycleZone(zone_);
3296 int chk(creat("/tmp/cydia.chk", 0644));
3300 NSString *title(UCLocalize("DATABASE"));
3303 if (!cache_.Open(progress_, true)) { pop:
3305 bool warning(!_error->PopMessage(error));
3306 lprintf("cache_.Open():[%s]\n", error.c_str());
3308 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3309 [delegate_ repairWithSelector:@selector(configure)];
3310 else if (error == "The package lists or status file could not be parsed or opened.")
3311 [delegate_ repairWithSelector:@selector(update)];
3312 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3313 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3314 // else if (error == "The list of sources could not be read.")
3316 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3325 unlink("/tmp/cydia.chk");
3327 now_ = [[NSDate date] retain];
3329 policy_ = new pkgDepCache::Policy();
3330 records_ = new pkgRecords(cache_);
3331 resolver_ = new pkgProblemResolver(cache_);
3332 fetcher_ = new pkgAcquire(&status_);
3335 list_ = new pkgSourceList();
3336 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3339 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3340 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3344 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3347 if (cache_->BrokenCount() != 0) {
3348 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3351 if (cache_->BrokenCount() != 0) {
3352 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3356 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3362 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3363 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3364 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3365 // XXX: this could be more intelligent
3366 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3367 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3369 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3376 /*std::vector<Package *> packages;
3377 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3378 [packages_ release];
3383 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3384 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3385 //packages.push_back(package);
3386 [packages_ addObject:package];
3390 /*if (packages.empty())
3391 packages_ = [[NSArray alloc] init];
3393 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3396 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3397 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3398 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3406 /*if (!packages.empty())
3407 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3408 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3410 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3412 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3414 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3420 - (void) configure {
3421 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3422 system([dpkg UTF8String]);
3426 // XXX: I don't remember this condition
3431 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3433 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3435 if ([self popErrorWithTitle:title])
3439 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3442 public pkgArchiveCleaner
3445 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3450 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3457 fetcher_->Shutdown();
3459 pkgRecords records(cache_);
3461 lock_ = new FileFd();
3462 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3464 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3466 if ([self popErrorWithTitle:title])
3470 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3473 manager_ = (_system->CreatePM(cache_));
3474 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3481 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3483 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3485 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3487 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3488 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3491 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3496 bool failed = false;
3497 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3498 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3500 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3503 std::string uri = (*item)->DescURI();
3504 std::string error = (*item)->ErrorText;
3506 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3509 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3510 withObject:[NSArray arrayWithObjects:
3511 [NSString stringWithUTF8String:error.c_str()],
3523 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3525 if (_error->PendingError()) {
3530 if (result == pkgPackageManager::Failed) {
3535 if (result != pkgPackageManager::Completed) {
3540 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3542 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3544 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3545 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3548 if (![before isEqualToArray:after])
3553 NSString *title(UCLocalize("UPGRADE"));
3554 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3560 [self updateWithStatus:status_];
3563 - (void) setVisible {
3564 for (Package *package in packages_)
3565 [package setVisible];
3568 - (void) updateWithStatus:(Status &)status {
3569 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3570 NSString *title(UCLocalize("REFRESHING_DATA"));
3573 if (!list.ReadMainList())
3574 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3577 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3578 if ([self popErrorWithTitle:title])
3581 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3582 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */;
3584 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3588 - (void) setDelegate:(id)delegate {
3589 delegate_ = delegate;
3590 status_.setDelegate(delegate);
3591 progress_.setDelegate(delegate);
3594 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3595 SourceMap::const_iterator i(sources_.find(file->ID));
3596 return i == sources_.end() ? nil : i->second;
3602 /* Confirmation Controller {{{ */
3603 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3604 if (!iterator.end())
3605 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3606 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3608 pkgCache::PkgIterator package(dep.TargetPkg());
3611 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3619 /* Web Scripting {{{ */
3620 @interface CydiaObject : NSObject {
3625 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3628 @implementation CydiaObject
3631 [indirect_ release];
3635 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3636 if ((self = [super init]) != nil) {
3637 indirect_ = [indirect retain];
3641 - (void) setDelegate:(id)delegate {
3642 delegate_ = delegate;
3645 + (NSArray *) _attributeKeys {
3646 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3649 - (NSArray *) attributeKeys {
3650 return [[self class] _attributeKeys];
3653 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3654 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3657 - (NSString *) device {
3658 return [[UIDevice currentDevice] uniqueIdentifier];
3661 #if 0 // XXX: implement!
3662 - (NSString *) mac {
3663 if (![indirect_ promptForSensitive:@"Mac Address"])
3667 - (NSString *) serial {
3668 if (![indirect_ promptForSensitive:@"Serial #"])
3672 - (NSString *) firewire {
3673 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3677 - (NSString *) imei {
3678 if (![indirect_ promptForSensitive:@"IMEI"])
3683 + (NSString *) webScriptNameForSelector:(SEL)selector {
3684 if (selector == @selector(close))
3686 else if (selector == @selector(getInstalledPackages))
3687 return @"getInstalledPackages";
3688 else if (selector == @selector(getPackageById:))
3689 return @"getPackageById";
3690 else if (selector == @selector(installPackages:))
3691 return @"installPackages";
3692 else if (selector == @selector(setAutoPopup:))
3693 return @"setAutoPopup";
3694 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3695 return @"setButtonImage";
3696 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3697 return @"setButtonTitle";
3698 else if (selector == @selector(setFinishHook:))
3699 return @"setFinishHook";
3700 else if (selector == @selector(setPopupHook:))
3701 return @"setPopupHook";
3702 else if (selector == @selector(setSpecial:))
3703 return @"setSpecial";
3704 else if (selector == @selector(setToken:))
3706 else if (selector == @selector(setViewportWidth:))
3707 return @"setViewportWidth";
3708 else if (selector == @selector(supports:))
3710 else if (selector == @selector(stringWithFormat:arguments:))
3712 else if (selector == @selector(localizedStringForKey:value:table:))
3714 else if (selector == @selector(du:))
3716 else if (selector == @selector(statfs:))
3722 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3723 return [self webScriptNameForSelector:selector] == nil;
3726 - (BOOL) supports:(NSString *)feature {
3727 return [feature isEqualToString:@"window.open"];
3730 - (NSArray *) getInstalledPackages {
3731 NSArray *packages([[Database sharedInstance] packages]);
3732 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3733 for (Package *package in packages)
3734 if ([package installed] != nil)
3735 [installed addObject:package];
3739 - (Package *) getPackageById:(NSString *)id {
3740 Package *package([[Database sharedInstance] packageWithName:id]);
3745 - (NSArray *) statfs:(NSString *)path {
3748 if (path == nil || statfs([path UTF8String], &stat) == -1)
3751 return [NSArray arrayWithObjects:
3752 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3753 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3754 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3758 - (NSNumber *) du:(NSString *)path {
3759 NSNumber *value(nil);
3762 _assert(pipe(fds) != -1);
3764 pid_t pid(ExecFork());
3766 _assert(dup2(fds[1], 1) != -1);
3767 _assert(close(fds[0]) != -1);
3768 _assert(close(fds[1]) != -1);
3769 /* XXX: this should probably not use du */
3770 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3775 _assert(close(fds[1]) != -1);
3777 if (FILE *du = fdopen(fds[0], "r")) {
3779 while (fgets(line, sizeof(line), du) != NULL) {
3780 size_t length(strlen(line));
3781 while (length != 0 && line[length - 1] == '\n')
3782 line[--length] = '\0';
3783 if (char *tab = strchr(line, '\t')) {
3785 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3790 } else _assert(close(fds[0]));
3794 if (waitpid(pid, &status, 0) == -1)
3797 else _assert(false);
3806 - (void) installPackages:(NSArray *)packages {
3807 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3810 - (void) setAutoPopup:(BOOL)popup {
3811 [indirect_ setAutoPopup:popup];
3814 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3815 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3818 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3819 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3822 - (void) setSpecial:(id)function {
3823 [indirect_ setSpecial:function];
3826 - (void) setToken:(NSString *)token {
3829 Token_ = [token retain];
3831 [Metadata_ setObject:Token_ forKey:@"Token"];
3835 - (void) setFinishHook:(id)function {
3836 [indirect_ setFinishHook:function];
3839 - (void) setPopupHook:(id)function {
3840 [indirect_ setPopupHook:function];
3843 - (void) setViewportWidth:(float)width {
3844 [indirect_ setViewportWidth:width];
3847 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3848 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3849 unsigned count([arguments count]);
3851 for (unsigned i(0); i != count; ++i)
3852 values[i] = [arguments objectAtIndex:i];
3853 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3856 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3857 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3859 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3861 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3867 /* Cydia Browser Controller {{{ */
3868 @interface CYBrowserController : BrowserController {
3869 CydiaObject *cydia_;
3874 @implementation CYBrowserController
3881 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3884 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3885 [super webView:sender didClearWindowObject:window forFrame:frame];
3887 WebDataSource *source([frame dataSource]);
3888 NSURLResponse *response([source response]);
3889 NSURL *url([response URL]);
3890 NSString *scheme([url scheme]);
3892 NSHTTPURLResponse *http;
3893 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3894 http = (NSHTTPURLResponse *) response;
3898 NSDictionary *headers([http allHeaderFields]);
3899 NSString *host([url host]);
3900 [self setHeaders:headers forHost:host];
3903 [host isEqualToString:@"cydia.saurik.com"] ||
3904 [host hasSuffix:@".cydia.saurik.com"] ||
3905 [scheme isEqualToString:@"file"]
3907 [window setValue:cydia_ forKey:@"cydia"];
3910 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3911 if (System_ != NULL)
3912 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3913 if (Machine_ != NULL)
3914 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3916 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3918 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3921 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3922 NSMutableURLRequest *copy = [request mutableCopy];
3923 [self _setMoreHeaders:copy];
3927 - (void) setDelegate:(id)delegate {
3928 [super setDelegate:delegate];
3929 [cydia_ setDelegate:delegate];
3933 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3934 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3936 WebView *webview([document_ webView]);
3938 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3940 NSString *application = package == nil ? @"Cydia" : [NSString
3941 stringWithFormat:@"Cydia/%@",
3946 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3948 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3949 if (Product_ != nil)
3950 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3952 [webview setApplicationNameForUserAgent:application];
3959 /* Confirmation {{{ */
3960 @protocol ConfirmationControllerDelegate
3961 - (void) cancelAndClear:(bool)clear;
3962 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3966 @interface ConfirmationController : CYBrowserController {
3967 _transient Database *database_;
3968 UIAlertView *essential_;
3975 - (id) initWithDatabase:(Database *)database;
3979 @implementation ConfirmationController
3986 if (essential_ != nil)
3987 [essential_ release];
3991 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3992 NSString *context([alert context]);
3994 if ([context isEqualToString:@"remove"]) {
3995 if (button == [alert cancelButtonIndex]) {
3996 [self dismissModalViewControllerAnimated:YES];
3997 } else if (button == [alert firstOtherButtonIndex]) {
4000 [delegate_ confirmWithNavigationController:[self navigationController]];
4003 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4004 } else if ([context isEqualToString:@"unable"]) {
4005 [self dismissModalViewControllerAnimated:YES];
4006 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4008 [super alertView:alert clickedButtonAtIndex:button];
4012 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4013 [self dismissModalViewControllerAnimated:YES];
4014 [delegate_ cancelAndClear:NO];
4019 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4020 [super webView:sender didClearWindowObject:window forFrame:frame];
4021 [window setValue:changes_ forKey:@"changes"];
4022 [window setValue:issues_ forKey:@"issues"];
4023 [window setValue:sizes_ forKey:@"sizes"];
4024 [window setValue:self forKey:@"queue"];
4027 - (id) initWithDatabase:(Database *)database {
4028 if ((self = [super init]) != nil) {
4029 database_ = database;
4031 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4033 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4034 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4035 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4036 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4037 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4041 pkgDepCache::Policy *policy([database_ policy]);
4043 pkgCacheFile &cache([database_ cache]);
4044 NSArray *packages = [database_ packages];
4045 for (Package *package in packages) {
4046 pkgCache::PkgIterator iterator = [package iterator];
4047 pkgDepCache::StateCache &state(cache[iterator]);
4049 NSString *name([package name]);
4051 if (state.NewInstall())
4052 [installing addObject:name];
4053 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4054 [reinstalling addObject:name];
4055 else if (state.Upgrade())
4056 [upgrading addObject:name];
4057 else if (state.Downgrade())
4058 [downgrading addObject:name];
4059 else if (state.Delete()) {
4060 if ([package essential])
4062 [removing addObject:name];
4065 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4066 substrate_ |= DepSubstrate(iterator.CurrentVer());
4071 else if (Advanced_) {
4072 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4074 essential_ = [[UIAlertView alloc]
4075 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4076 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4078 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4079 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4082 [essential_ setContext:@"remove"];
4084 essential_ = [[UIAlertView alloc]
4085 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4086 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4088 cancelButtonTitle:UCLocalize("OKAY")
4089 otherButtonTitles:nil
4092 [essential_ setContext:@"unable"];
4095 changes_ = [[NSArray alloc] initWithObjects:
4103 issues_ = [database_ issues];
4105 issues_ = [issues_ retain];
4107 sizes_ = [[NSArray alloc] initWithObjects:
4108 SizeString([database_ fetcher].FetchNeeded()),
4109 SizeString([database_ fetcher].PartialPresent()),
4112 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4114 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
4115 initWithTitle:UCLocalize("CANCEL")
4116 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4117 style:UIBarButtonItemStylePlain
4119 action:@selector(cancelButtonClicked)
4121 [[self navigationItem] setLeftBarButtonItem:leftItem];
4126 - (void) applyRightButton {
4127 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
4128 initWithTitle:UCLocalize("CONFIRM")
4129 style:UIBarButtonItemStylePlain
4131 action:@selector(confirmButtonClicked)
4133 #if !AlwaysReload && !IgnoreInstall
4134 if (issues_ == nil && ![self isLoading]) [[self navigationItem] setRightBarButtonItem:rightItem];
4135 else [super applyRightButton];
4137 [[self navigationItem] setRightBarButtonItem:nil];
4139 [rightItem release];
4142 - (void) cancelButtonClicked {
4143 [self dismissModalViewControllerAnimated:YES];
4144 [delegate_ cancelAndClear:YES];
4148 - (void) confirmButtonClicked {
4152 if (essential_ != nil)
4157 [delegate_ confirmWithNavigationController:[self navigationController]];
4165 /* Progress Data {{{ */
4166 @interface ProgressData : NSObject {
4172 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4179 @implementation ProgressData
4181 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4182 if ((self = [super init]) != nil) {
4183 selector_ = selector;
4203 /* Progress Controller {{{ */
4204 @interface ProgressController : CYViewController <
4205 ConfigurationDelegate,
4208 _transient Database *database_;
4209 UIProgressBar *progress_;
4210 UITextView *output_;
4211 UITextLabel *status_;
4212 UIPushButton *close_;
4214 SHA1SumValue springlist_;
4215 SHA1SumValue notifyconf_;
4219 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4221 - (void) _retachThread;
4222 - (void) _detachNewThreadData:(ProgressData *)data;
4223 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4229 @protocol ProgressControllerDelegate
4230 - (void) progressControllerIsComplete:(ProgressController *)sender;
4233 @implementation ProgressController
4236 [database_ setDelegate:nil];
4237 [progress_ release];
4246 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4247 if ((self = [super init]) != nil) {
4248 database_ = database;
4249 [database_ setDelegate:self];
4250 delegate_ = delegate;
4252 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4254 progress_ = [[UIProgressBar alloc] init];
4255 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4256 [progress_ setStyle:0];
4258 status_ = [[UITextLabel alloc] init];
4259 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4260 [status_ setColor:[UIColor whiteColor]];
4261 [status_ setBackgroundColor:[UIColor clearColor]];
4262 [status_ setCentersHorizontally:YES];
4263 //[status_ setFont:font];
4265 output_ = [[UITextView alloc] init];
4267 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4268 //[output_ setTextFont:@"Courier New"];
4269 [output_ setFont:[[output_ font] fontWithSize:12]];
4270 [output_ setTextColor:[UIColor whiteColor]];
4271 [output_ setBackgroundColor:[UIColor clearColor]];
4272 [output_ setMarginTop:0];
4273 [output_ setAllowsRubberBanding:YES];
4274 [output_ setEditable:NO];
4275 [[self view] addSubview:output_];
4277 close_ = [[UIPushButton alloc] init];
4278 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4279 [close_ setAutosizesToFit:NO];
4280 [close_ setDrawsShadow:YES];
4281 [close_ setStretchBackground:YES];
4282 [close_ setEnabled:YES];
4283 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4284 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4285 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4286 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4290 - (void) positionViews {
4291 CGRect bounds = [[self view] bounds];
4292 CGSize prgsize = [UIProgressBar defaultSize];
4295 (bounds.size.width - prgsize.width) / 2,
4296 bounds.size.height - prgsize.height - 64
4299 float closewidth = bounds.size.width - 20;
4300 if (closewidth > 300) closewidth = 300;
4302 [progress_ setFrame:prgrect];
4303 [status_ setFrame:CGRectMake(
4305 bounds.size.height - prgsize.height - 94,
4306 bounds.size.width - 20,
4309 [output_ setFrame:CGRectMake(
4312 bounds.size.width - 20,
4313 bounds.size.height - 106
4315 [close_ setFrame:CGRectMake(
4316 (bounds.size.width - closewidth) / 2,
4317 bounds.size.height - prgsize.height - 94,
4323 - (void) viewWillAppear:(BOOL)animated {
4324 [super viewDidAppear:animated];
4325 [[self navigationItem] setHidesBackButton:YES];
4326 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4328 [self positionViews];
4331 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4332 [self positionViews];
4335 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4336 NSString *context([alert context]);
4338 if ([context isEqualToString:@"conffile"]) {
4339 FILE *input = [database_ input];
4340 if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
4341 else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
4346 - (void) closeButtonPushed {
4349 UpdateExternalStatus(0);
4353 [self dismissModalViewControllerAnimated:YES];
4357 [delegate_ terminateWithSuccess];
4358 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4359 [delegate_ suspendWithAnimation:YES];
4361 [delegate_ suspend];*/
4365 system("launchctl stop com.apple.SpringBoard");
4369 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4378 - (void) _retachThread {
4379 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4381 [[self view] addSubview:close_];
4382 [progress_ removeFromSuperview];
4383 [status_ removeFromSuperview];
4385 [database_ popErrorWithTitle:title_];
4386 [delegate_ progressControllerIsComplete:self];
4390 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4393 MMap mmap(file, MMap::ReadOnly);
4395 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4396 if (!(notifyconf_ == sha1.Result()))
4403 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4406 MMap mmap(file, MMap::ReadOnly);
4408 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4409 if (!(springlist_ == sha1.Result()))
4415 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4416 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4417 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4418 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4419 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4422 system("su -c /usr/bin/uicache mobile");
4424 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4426 [delegate_ setStatusBarShowsProgress:NO];
4429 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4430 [[data target] performSelector:[data selector] withObject:[data object]];
4433 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4436 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4437 UpdateExternalStatus(1);
4444 title_ = [title retain];
4446 [[self navigationItem] setTitle:title_];
4448 [status_ setText:nil];
4449 [output_ setText:@""];
4450 [progress_ setProgress:0];
4452 [close_ removeFromSuperview];
4453 [[self view] addSubview:progress_];
4454 [[self view] addSubview:status_];
4456 [delegate_ setStatusBarShowsProgress:YES];
4461 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4464 MMap mmap(file, MMap::ReadOnly);
4466 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4467 notifyconf_ = sha1.Result();
4473 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4476 MMap mmap(file, MMap::ReadOnly);
4478 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4479 springlist_ = sha1.Result();
4484 detachNewThreadSelector:@selector(_detachNewThreadData:)
4486 withObject:[[ProgressData alloc]
4487 initWithSelector:selector
4494 - (void) repairWithSelector:(SEL)selector {
4496 detachNewThreadSelector:selector
4499 title:UCLocalize("REPAIRING")
4503 - (void) setConfigurationData:(NSString *)data {
4505 performSelectorOnMainThread:@selector(_setConfigurationData:)
4511 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4512 CYActionSheet *sheet([[[CYActionSheet alloc]
4514 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4515 defaultButtonIndex:0
4518 [sheet setMessage:error];
4519 [sheet yieldToPopupAlertAnimated:YES];
4523 - (void) setProgressTitle:(NSString *)title {
4525 performSelectorOnMainThread:@selector(_setProgressTitle:)
4531 - (void) setProgressPercent:(float)percent {
4533 performSelectorOnMainThread:@selector(_setProgressPercent:)
4534 withObject:[NSNumber numberWithFloat:percent]
4539 - (void) startProgress {
4542 - (void) addProgressOutput:(NSString *)output {
4544 performSelectorOnMainThread:@selector(_addProgressOutput:)
4550 - (bool) isCancelling:(size_t)received {
4554 - (void) _setConfigurationData:(NSString *)data {
4555 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4557 if (!conffile_r(data)) {
4558 lprintf("E:invalid conffile\n");
4562 NSString *ofile = conffile_r[1];
4563 //NSString *nfile = conffile_r[2];
4565 UIAlertView *alert = [[[UIAlertView alloc]
4566 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4567 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4569 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4570 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4571 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4575 [alert setContext:@"conffile"];
4579 - (void) _setProgressTitle:(NSString *)title {
4580 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4581 for (size_t i(0), e([words count]); i != e; ++i) {
4582 NSString *word([words objectAtIndex:i]);
4583 if (Package *package = [database_ packageWithName:word])
4584 [words replaceObjectAtIndex:i withObject:[package name]];
4587 [status_ setText:[words componentsJoinedByString:@" "]];
4590 - (void) _setProgressPercent:(NSNumber *)percent {
4591 [progress_ setProgress:[percent floatValue]];
4594 - (void) _addProgressOutput:(NSString *)output {
4595 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4596 CGSize size = [output_ contentSize];
4597 CGRect rect = {{0, size.height}, {size.width, 0}};
4598 [output_ scrollRectToVisible:rect animated:YES];
4601 - (BOOL) isRunning {
4608 /* Cell Content View {{{ */
4609 @protocol ContentDelegate
4610 - (void) drawContentRect:(CGRect)rect;
4613 @interface ContentView : UIView {
4614 _transient id<ContentDelegate> delegate_;
4619 @implementation ContentView
4620 - (id) initWithFrame:(CGRect)frame {
4621 if ((self = [super initWithFrame:frame]) != nil) {
4622 /* Fix landscape stretching. */
4623 [self setNeedsDisplayOnBoundsChange:YES];
4627 - (void) setDelegate:(id<ContentDelegate>)delegate {
4628 delegate_ = delegate;
4631 - (void) drawRect:(CGRect)rect {
4632 [super drawRect:rect];
4633 [delegate_ drawContentRect:rect];
4637 /* Package Cell {{{ */
4638 @interface PackageCell : UITableViewCell <
4643 NSString *description_;
4649 ContentView *content_;
4655 - (PackageCell *) init;
4656 - (void) setPackage:(Package *)package;
4658 + (int) heightForPackage:(Package *)package;
4659 - (void) drawContentRect:(CGRect)rect;
4663 @implementation PackageCell
4665 - (void) clearPackage {
4676 if (description_ != nil) {
4677 [description_ release];
4681 if (source_ != nil) {
4686 if (badge_ != nil) {
4691 if (placard_ != nil) {
4701 [self clearPackage];
4708 return faded_ ? [self selectionPercent] : fade_;
4711 - (PackageCell *) init {
4712 CGRect frame(CGRectMake(0, 0, 320, 74));
4713 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4714 UIView *content([self contentView]);
4715 CGRect bounds([content bounds]);
4717 content_ = [[ContentView alloc] initWithFrame:bounds];
4718 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4719 [content addSubview:content_];
4721 [content_ setDelegate:self];
4722 [content_ setOpaque:YES];
4723 if ([self respondsToSelector:@selector(selectionPercent)])
4728 - (void) _setBackgroundColor {
4730 if (NSString *mode = [package_ mode]) {
4731 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4732 color = remove ? RemovingColor_ : InstallingColor_;
4734 color = [UIColor whiteColor];
4736 [content_ setBackgroundColor:color];
4737 [self setNeedsDisplay];
4740 - (void) setPackage:(Package *)package {
4741 [self clearPackage];
4744 Source *source = [package source];
4746 icon_ = [[package icon] retain];
4747 name_ = [[package name] retain];
4750 description_ = [package longDescription];
4751 if (description_ == nil)
4752 description_ = [package shortDescription];
4753 if (description_ != nil)
4754 description_ = [description_ retain];
4756 commercial_ = [package isCommercial];
4758 package_ = [package retain];
4760 NSString *label = nil;
4761 bool trusted = false;
4763 if (source != nil) {
4764 label = [source label];
4765 trusted = [source trusted];
4766 } else if ([[package id] isEqualToString:@"firmware"])
4767 label = UCLocalize("APPLE");
4769 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4771 NSString *from(label);
4773 NSString *section = [package simpleSection];
4774 if (section != nil && ![section isEqualToString:label]) {
4775 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4776 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4779 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4780 source_ = [from retain];
4782 if (NSString *purpose = [package primaryPurpose])
4783 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4784 badge_ = [badge_ retain];
4786 if ([package installed] != nil)
4787 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4788 placard_ = [placard_ retain];
4790 [self _setBackgroundColor];
4791 [content_ setNeedsDisplay];
4794 - (void) drawContentRect:(CGRect)rect {
4795 bool selected([self isSelected]);
4796 float width([self bounds].size.width);
4799 CGContextRef context(UIGraphicsGetCurrentContext());
4800 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4801 CGContextFillRect(context, rect);
4806 rect.size = [icon_ size];
4808 rect.size.width /= 2;
4809 rect.size.height /= 2;
4811 rect.origin.x = 25 - rect.size.width / 2;
4812 rect.origin.y = 25 - rect.size.height / 2;
4814 [icon_ drawInRect:rect];
4817 if (badge_ != nil) {
4818 CGSize size = [badge_ size];
4820 [badge_ drawAtPoint:CGPointMake(
4821 36 - size.width / 2,
4822 36 - size.height / 2
4830 UISetColor(commercial_ ? Purple_ : Black_);
4831 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4832 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4835 UISetColor(commercial_ ? Purplish_ : Gray_);
4836 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4838 if (placard_ != nil)
4839 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4842 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4843 //[self _setBackgroundColor];
4844 [super setSelected:selected animated:fade];
4845 [content_ setNeedsDisplay];
4848 + (int) heightForPackage:(Package *)package {
4854 /* Section Cell {{{ */
4855 @interface SectionCell : UITableViewCell <
4863 ContentView *content_;
4868 - (void) setSection:(Section *)section editing:(BOOL)editing;
4872 @implementation SectionCell
4874 - (void) clearSection {
4875 if (basic_ != nil) {
4880 if (section_ != nil) {
4890 if (count_ != nil) {
4897 [self clearSection];
4905 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4906 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4907 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4908 switch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4909 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4911 UIView *content([self contentView]);
4912 CGRect bounds([content bounds]);
4914 content_ = [[ContentView alloc] initWithFrame:bounds];
4915 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4916 [content addSubview:content_];
4917 [content_ setBackgroundColor:[UIColor whiteColor]];
4919 [content_ setDelegate:self];
4923 - (void) onSwitch:(id)sender {
4924 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4925 if (metadata == nil) {
4926 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4927 [Sections_ setObject:metadata forKey:basic_];
4931 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4934 - (void) setSection:(Section *)section editing:(BOOL)editing {
4935 if (editing != editing_) {
4937 [switch_ removeFromSuperview];
4939 [self addSubview:switch_];
4943 [self clearSection];
4945 if (section == nil) {
4946 name_ = [UCLocalize("ALL_PACKAGES") retain];
4949 basic_ = [section name];
4951 basic_ = [basic_ retain];
4953 section_ = [section localized];
4954 if (section_ != nil)
4955 section_ = [section_ retain];
4957 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4958 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4961 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4964 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4965 [content_ setNeedsDisplay];
4968 - (void) setFrame:(CGRect)frame {
4969 [super setFrame:frame];
4971 CGRect rect([switch_ frame]);
4972 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4975 - (void) drawContentRect:(CGRect)rect {
4976 BOOL selected = [self isSelected];
4978 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4986 float width(rect.size.width);
4990 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4992 CGSize size = [count_ sizeWithFont:Font14_];
4996 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5002 /* File Table {{{ */
5003 @interface FileTable : CYViewController <
5004 UITableViewDataSource,
5007 _transient Database *database_;
5010 NSMutableArray *files_;
5014 - (id) initWithDatabase:(Database *)database;
5015 - (void) setPackage:(Package *)package;
5019 @implementation FileTable
5022 if (package_ != nil)
5031 - (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
5032 return files_ == nil ? 0 : [files_ count];
5035 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5039 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5040 static NSString *reuseIdentifier = @"Cell";
5042 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5044 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5045 [cell setFont:[UIFont systemFontOfSize:16]];
5047 [cell setText:[files_ objectAtIndex:indexPath.row]];
5048 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5053 - (id) initWithDatabase:(Database *)database {
5054 if ((self = [super init]) != nil) {
5055 database_ = database;
5057 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5059 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5061 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5062 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5063 [list_ setRowHeight:24.0f];
5064 [[self view] addSubview:list_];
5066 [list_ setDataSource:self];
5067 [list_ setDelegate:self];
5071 - (void) setPackage:(Package *)package {
5072 if (package_ != nil) {
5073 [package_ autorelease];
5082 [files_ removeAllObjects];
5084 if (package != nil) {
5085 package_ = [package retain];
5086 name_ = [[package id] retain];
5088 if (NSArray *files = [package files])
5089 [files_ addObjectsFromArray:files];
5091 if ([files_ count] != 0) {
5092 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5093 [files_ removeObjectAtIndex:0];
5094 [files_ sortUsingSelector:@selector(compareByPath:)];
5096 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5097 [stack addObject:@"/"];
5099 for (int i(0), e([files_ count]); i != e; ++i) {
5100 NSString *file = [files_ objectAtIndex:i];
5101 while (![file hasPrefix:[stack lastObject]])
5102 [stack removeLastObject];
5103 NSString *directory = [stack lastObject];
5104 [stack addObject:[file stringByAppendingString:@"/"]];
5105 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5106 ([stack count] - 2) * 3, "",
5107 [file substringFromIndex:[directory length]]
5116 - (void) reloadData {
5117 [self setPackage:[database_ packageWithName:name_]];
5122 /* Package Controller {{{ */
5123 @interface PackageController : CYBrowserController <
5124 UIActionSheetDelegate
5126 _transient Database *database_;
5130 NSMutableArray *buttons_;
5133 - (id) initWithDatabase:(Database *)database;
5134 - (void) setPackage:(Package *)package;
5138 @implementation PackageController
5141 if (package_ != nil)
5150 if ([self retainCount] == 1)
5151 [delegate_ setPackageController:self];
5155 /* XXX: this is not safe at all... localization of /fail/ */
5156 - (void) _clickButtonWithName:(NSString *)name {
5157 if ([name isEqualToString:UCLocalize("CLEAR")])
5158 [delegate_ clearPackage:package_];
5159 else if ([name isEqualToString:UCLocalize("INSTALL")])
5160 [delegate_ installPackage:package_];
5161 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5162 [delegate_ installPackage:package_];
5163 else if ([name isEqualToString:UCLocalize("REMOVE")])
5164 [delegate_ removePackage:package_];
5165 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5166 [delegate_ installPackage:package_];
5167 else _assert(false);
5170 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5171 NSString *context([sheet context]);
5173 if ([context isEqualToString:@"modify"]) {
5174 if (button != [sheet cancelButtonIndex]) {
5175 NSString *buttonName = [buttons_ objectAtIndex:button];
5176 [self _clickButtonWithName:buttonName];
5179 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5183 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
5184 return [super webView:sender didFinishLoadForFrame:frame];
5187 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5188 [super webView:sender didClearWindowObject:window forFrame:frame];
5189 [window setValue:package_ forKey:@"package"];
5192 - (bool) _allowJavaScriptPanel {
5197 - (void) _customButtonClicked {
5198 int count([buttons_ count]);
5203 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5205 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5206 [buttons addObjectsFromArray:buttons_];
5208 UIActionSheet *sheet = [[[UIActionSheet alloc]
5211 cancelButtonTitle:nil
5212 destructiveButtonTitle:nil
5213 otherButtonTitles:nil
5216 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5218 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5219 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5221 [sheet setContext:@"modify"];
5223 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5227 // We don't want to allow non-commercial packages to do custom things to the install button,
5228 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5229 - (void) customButtonClicked {
5231 [super customButtonClicked];
5233 [self _customButtonClicked];
5236 - (void) reloadButtonClicked {
5237 // Don't reload a package view by clicking the button.
5240 - (void) applyLoadingTitle {
5241 // Don't show "Loading" as the title. Ever.
5244 - (UIBarButtonItem *) rightButton {
5245 int count = [buttons_ count];
5246 return [[[UIBarButtonItem alloc]
5247 initWithTitle:count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0]
5248 style:UIBarButtonItemStylePlain
5250 action:@selector(customButtonClicked)
5255 - (id) initWithDatabase:(Database *)database {
5256 if ((self = [super init]) != nil) {
5257 database_ = database;
5258 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5259 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5263 - (void) setPackage:(Package *)package {
5264 if (package_ != nil) {
5265 [package_ autorelease];
5274 [buttons_ removeAllObjects];
5276 if (package != nil) {
5279 package_ = [package retain];
5280 name_ = [[package id] retain];
5281 commercial_ = [package isCommercial];
5283 if ([package_ mode] != nil)
5284 [buttons_ addObject:UCLocalize("CLEAR")];
5285 if ([package_ source] == nil);
5286 else if ([package_ upgradableAndEssential:NO])
5287 [buttons_ addObject:UCLocalize("UPGRADE")];
5288 else if ([package_ uninstalled])
5289 [buttons_ addObject:UCLocalize("INSTALL")];
5291 [buttons_ addObject:UCLocalize("REINSTALL")];
5292 if (![package_ uninstalled])
5293 [buttons_ addObject:UCLocalize("REMOVE")];
5295 if (special_ != NULL) {
5296 CGRect frame([document_ frame]);
5297 frame.size.height = 0;
5298 [document_ setFrame:frame];
5300 if ([scroller_ respondsToSelector:@selector(scrollPointVisibleAtTopLeft:)])
5301 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5303 [scroller_ scrollRectToVisible:CGRectZero animated:NO];
5306 [[[document_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5308 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5310 [self setFinishHook:nil];
5311 [self setPopupHook:nil];
5314 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5315 [super callFunction:special_];
5320 - (bool) isLoading {
5321 return commercial_ ? [super isLoading] : false;
5324 - (void) reloadData {
5325 [self setPackage:[database_ packageWithName:name_]];
5330 /* Package Table {{{ */
5331 @interface PackageTable : UIView <
5332 UITableViewDataSource,
5335 _transient Database *database_;
5336 NSMutableArray *packages_;
5337 NSMutableArray *sections_;
5339 NSMutableArray *index_;
5340 NSMutableDictionary *indices_;
5346 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5348 - (void) setDelegate:(id)delegate;
5350 - (void) reloadData;
5351 - (void) resetCursor;
5353 - (UITableView *) list;
5355 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5357 - (void) deselectWithAnimation:(BOOL)animated;
5361 @implementation PackageTable
5364 [packages_ release];
5365 [sections_ release];
5373 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5374 NSInteger count([sections_ count]);
5375 return count == 0 ? 1 : count;
5378 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5379 if ([sections_ count] == 0)
5381 return [[sections_ objectAtIndex:section] name];
5384 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5385 if ([sections_ count] == 0)
5387 return [[sections_ objectAtIndex:section] count];
5390 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5391 Section *section([sections_ objectAtIndex:[path section]]);
5392 NSInteger row([path row]);
5393 Package *package([packages_ objectAtIndex:([section row] + row)]);
5397 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5398 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5400 cell = [[[PackageCell alloc] init] autorelease];
5401 [cell setPackage:[self packageAtIndexPath:path]];
5405 - (void) deselectWithAnimation:(BOOL)animated {
5406 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5409 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5410 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5413 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5414 Package *package([self packageAtIndexPath:path]);
5415 package = [database_ packageWithName:[package id]];
5416 [target_ performSelector:action_ withObject:package];
5420 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5421 return [packages_ count] > 20 ? index_ : nil;
5424 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5428 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5429 if ((self = [super initWithFrame:frame]) != nil) {
5430 database_ = database;
5435 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5436 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5438 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5439 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5441 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5442 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5443 [list_ setRowHeight:73.0f];
5444 [self addSubview:list_];
5446 [list_ setDataSource:self];
5447 [list_ setDelegate:self];
5451 - (void) setDelegate:(id)delegate {
5452 delegate_ = delegate;
5455 - (bool) hasPackage:(Package *)package {
5459 - (void) reloadData {
5460 NSArray *packages = [database_ packages];
5462 [packages_ removeAllObjects];
5463 [sections_ removeAllObjects];
5465 _profile(PackageTable$reloadData$Filter)
5466 for (Package *package in packages)
5467 if ([self hasPackage:package])
5468 [packages_ addObject:package];
5471 [index_ removeAllObjects];
5472 [indices_ removeAllObjects];
5474 Section *section = nil;
5476 _profile(PackageTable$reloadData$Section)
5477 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5481 _profile(PackageTable$reloadData$Section$Package)
5482 package = [packages_ objectAtIndex:offset];
5483 index = [package index];
5486 if (section == nil || [section index] != index) {
5487 _profile(PackageTable$reloadData$Section$Allocate)
5488 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5491 [index_ addObject:[section name]];
5492 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5494 _profile(PackageTable$reloadData$Section$Add)
5495 [sections_ addObject:section];
5499 [section addToCount];
5503 _profile(PackageTable$reloadData$List)
5508 - (void) resetCursor {
5509 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5512 - (UITableView *) list {
5516 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5517 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5522 /* Filtered Package Table {{{ */
5523 @interface FilteredPackageTable : PackageTable {
5529 - (void) setObject:(id)object;
5530 - (void) setObject:(id)object forFilter:(SEL)filter;
5532 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5536 @implementation FilteredPackageTable
5544 - (void) setFilter:(SEL)filter {
5547 /* XXX: this is an unsafe optimization of doomy hell */
5548 Method method(class_getInstanceMethod([Package class], filter));
5549 _assert(method != NULL);
5550 imp_ = method_getImplementation(method);
5551 _assert(imp_ != NULL);
5554 - (void) setObject:(id)object {
5560 object_ = [object retain];
5563 - (void) setObject:(id)object forFilter:(SEL)filter {
5564 [self setFilter:filter];
5565 [self setObject:object];
5568 - (bool) hasPackage:(Package *)package {
5569 _profile(FilteredPackageTable$hasPackage)
5570 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5574 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5575 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5576 [self setFilter:filter];
5577 object_ = [object retain];
5585 /* Filtered Package Controller {{{ */
5586 @interface FilteredPackageController : CYViewController {
5587 _transient Database *database_;
5588 FilteredPackageTable *packages_;
5592 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5596 @implementation FilteredPackageController
5599 [packages_ release];
5605 - (void) viewDidAppear:(BOOL)animated {
5606 [super viewDidAppear:animated];
5607 [packages_ deselectWithAnimation:animated];
5610 - (void) didSelectPackage:(Package *)package {
5611 PackageController *view([delegate_ packageController]);
5612 [view setPackage:package];
5613 [view setDelegate:delegate_];
5614 [[self navigationController] pushViewController:view animated:YES];
5617 - (id) title { return title_; }
5619 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5620 if ((self = [super init]) != nil) {
5621 database_ = database;
5622 title_ = [title copy];
5623 [[self navigationItem] setTitle:title_];
5625 packages_ = [[FilteredPackageTable alloc]
5626 initWithFrame:[[self view] bounds]
5629 action:@selector(didSelectPackage:)
5634 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5635 [[self view] addSubview:packages_];
5639 - (void) reloadData {
5640 [packages_ reloadData];
5643 - (void) setDelegate:(id)delegate {
5644 [super setDelegate:delegate];
5645 [packages_ setDelegate:delegate];
5652 /* Add Source Controller {{{ */
5653 @interface AddSourceController : CYViewController {
5654 _transient Database *database_;
5657 - (id) initWithDatabase:(Database *)database;
5661 @implementation AddSourceController
5663 - (id) initWithDatabase:(Database *)database {
5664 if ((self = [super init]) != nil) {
5665 database_ = database;
5671 /* Source Cell {{{ */
5672 @interface SourceCell : UITableViewCell <
5677 NSString *description_;
5679 ContentView *content_;
5682 - (void) setSource:(Source *)source;
5686 @implementation SourceCell
5688 - (void) clearSource {
5691 [description_ release];
5700 - (void) setSource:(Source *)source {
5704 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5706 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5707 icon_ = [icon_ retain];
5709 origin_ = [[source name] retain];
5710 label_ = [[source uri] retain];
5711 description_ = [[source description] retain];
5713 [content_ setNeedsDisplay];
5722 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5723 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5724 UIView *content([self contentView]);
5725 CGRect bounds([content bounds]);
5727 content_ = [[ContentView alloc] initWithFrame:bounds];
5728 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5729 [content_ setBackgroundColor:[UIColor whiteColor]];
5730 [content addSubview:content_];
5732 [content_ setDelegate:self];
5733 [content_ setOpaque:YES];
5737 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5738 [super setSelected:selected animated:animated];
5739 [content_ setNeedsDisplay];
5742 - (void) drawContentRect:(CGRect)rect {
5743 bool selected([self isSelected]);
5744 float width(rect.size.width);
5747 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5754 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5758 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5762 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5767 /* Source Table {{{ */
5768 @interface SourceTable : CYViewController <
5769 UITableViewDataSource,
5772 _transient Database *database_;
5774 NSMutableArray *sources_;
5778 UIProgressHUD *hud_;
5781 //NSURLConnection *installer_;
5782 NSURLConnection *trivial_;
5783 NSURLConnection *trivial_bz2_;
5784 NSURLConnection *trivial_gz_;
5785 //NSURLConnection *automatic_;
5790 - (id) initWithDatabase:(Database *)database;
5792 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5796 @implementation SourceTable
5798 - (void) _deallocConnection:(NSURLConnection *)connection {
5799 if (connection != nil) {
5800 [connection cancel];
5801 //[connection setDelegate:nil];
5802 [connection release];
5814 //[self _deallocConnection:installer_];
5815 [self _deallocConnection:trivial_];
5816 [self _deallocConnection:trivial_gz_];
5817 [self _deallocConnection:trivial_bz2_];
5818 //[self _deallocConnection:automatic_];
5825 - (void) viewDidAppear:(BOOL)animated {
5826 [super viewDidAppear:animated];
5827 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5830 - (int) numberOfSectionsInTableView:(UITableView *)tableView {
5831 return offset_ == 0 ? 1 : 2;
5834 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(int)section {
5835 switch (section + (offset_ == 0 ? 1 : 0)) {
5836 case 0: return UCLocalize("ENTERED_BY_USER");
5837 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5843 - (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
5844 int count = [sources_ count];
5846 case 0: return (offset_ == 0 ? count : offset_);
5847 case 1: return count - offset_;
5853 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5855 switch (indexPath.section) {
5856 case 0: idx = indexPath.row; break;
5857 case 1: idx = indexPath.row + offset_; break;
5861 return [sources_ objectAtIndex:idx];
5864 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5865 Source *source = [self sourceAtIndexPath:indexPath];
5866 return [source description] == nil ? 56 : 73;
5869 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5870 static NSString *cellIdentifier = @"SourceCell";
5872 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5873 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5874 [cell setSource:[self sourceAtIndexPath:indexPath]];
5879 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5880 return UITableViewCellAccessoryDisclosureIndicator;
5883 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5884 Source *source = [self sourceAtIndexPath:indexPath];
5886 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5887 initWithDatabase:database_
5888 title:[source label]
5889 filter:@selector(isVisibleInSource:)
5893 [packages setDelegate:delegate_];
5895 [[self navigationController] pushViewController:packages animated:YES];
5898 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5899 Source *source = [self sourceAtIndexPath:indexPath];
5900 return [source record] != nil;
5903 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5904 Source *source = [self sourceAtIndexPath:indexPath];
5905 [Sources_ removeObjectForKey:[source key]];
5906 [delegate_ syncData];
5910 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5913 @"./", @"Distribution",
5914 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5916 [delegate_ syncData];
5919 - (NSString *) getWarning {
5920 NSString *href(href_);
5921 NSRange colon([href rangeOfString:@"://"]);
5922 if (colon.location != NSNotFound)
5923 href = [href substringFromIndex:(colon.location + 3)];
5924 href = [href stringByAddingPercentEscapes];
5925 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5926 href = [href stringByCachingURLWithCurrentCDN];
5928 NSURL *url([NSURL URLWithString:href]);
5930 NSStringEncoding encoding;
5931 NSError *error(nil);
5933 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5934 return [warning length] == 0 ? nil : warning;
5938 - (void) _endConnection:(NSURLConnection *)connection {
5939 NSURLConnection **field = NULL;
5940 if (connection == trivial_)
5942 else if (connection == trivial_bz2_)
5943 field = &trivial_bz2_;
5944 else if (connection == trivial_gz_)
5945 field = &trivial_gz_;
5946 _assert(field != NULL);
5947 [connection release];
5952 trivial_bz2_ == nil &&
5958 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5961 UIAlertView *alert = [[[UIAlertView alloc]
5962 initWithTitle:UCLocalize("SOURCE_WARNING")
5965 cancelButtonTitle:UCLocalize("CANCEL")
5966 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5969 [alert setContext:@"warning"];
5970 [alert setNumberOfRows:1];
5974 } else if (error_ != nil) {
5975 UIAlertView *alert = [[[UIAlertView alloc]
5976 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5977 message:[error_ localizedDescription]
5979 cancelButtonTitle:UCLocalize("OK")
5980 otherButtonTitles:nil
5983 [alert setContext:@"urlerror"];
5986 UIAlertView *alert = [[[UIAlertView alloc]
5987 initWithTitle:UCLocalize("NOT_REPOSITORY")
5988 message:UCLocalize("NOT_REPOSITORY_EX")
5990 cancelButtonTitle:UCLocalize("OK")
5991 otherButtonTitles:nil
5994 [alert setContext:@"trivial"];
5998 [delegate_ setStatusBarShowsProgress:NO];
5999 [delegate_ removeProgressHUD:hud_];
6009 if (error_ != nil) {
6016 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6017 switch ([response statusCode]) {
6023 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6024 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6026 error_ = [error retain];
6027 [self _endConnection:connection];
6030 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6031 [self _endConnection:connection];
6034 - (id)title { return UCLocalize("SOURCES"); }
6036 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6037 NSMutableURLRequest *request = [NSMutableURLRequest
6038 requestWithURL:[NSURL URLWithString:href]
6039 cachePolicy:NSURLRequestUseProtocolCachePolicy
6040 timeoutInterval:120.0
6043 [request setHTTPMethod:method];
6045 if (Machine_ != NULL)
6046 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6047 if (UniqueID_ != nil)
6048 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6050 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6052 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6055 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6056 NSString *context([alert context]);
6058 if ([context isEqualToString:@"source"]) {
6061 NSString *href = [[alert textField] text];
6063 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6065 if (![href hasSuffix:@"/"])
6066 href_ = [href stringByAppendingString:@"/"];
6069 href_ = [href_ retain];
6071 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6072 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6073 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6074 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6078 hud_ = [[delegate_ addProgressHUD] retain];
6079 [hud_ setText:UCLocalize("VERIFYING_URL")];
6088 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6089 } else if ([context isEqualToString:@"trivial"])
6090 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6091 else if ([context isEqualToString:@"urlerror"])
6092 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6093 else if ([context isEqualToString:@"warning"]) {
6108 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6112 - (id) initWithDatabase:(Database *)database {
6113 if ((self = [super init]) != nil) {
6114 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6115 [self updateButtonsForEditingStatus:NO animated:NO];
6117 database_ = database;
6118 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6120 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6121 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6122 [[self view] addSubview:list_];
6124 [list_ setDataSource:self];
6125 [list_ setDelegate:self];
6131 - (void) reloadData {
6133 if (!list.ReadMainList())
6136 [sources_ removeAllObjects];
6137 [sources_ addObjectsFromArray:[database_ sources]];
6139 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6142 int count([sources_ count]);
6144 for (int i = 0; i != count; i++) {
6145 if ([[sources_ objectAtIndex:i] record] == nil) break;
6149 [list_ setEditing:NO];
6150 [self updateButtonsForEditingStatus:NO animated:NO];
6154 - (void) addButtonClicked {
6155 /*[book_ pushPage:[[[AddSourceController alloc]
6160 UIAlertView *alert = [[[UIAlertView alloc]
6161 initWithTitle:UCLocalize("ENTER_APT_URL")
6164 cancelButtonTitle:UCLocalize("CANCEL")
6165 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6168 [alert setContext:@"source"];
6169 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6171 [alert setNumberOfRows:1];
6172 [alert addTextFieldWithValue:@"http://" label:@""];
6174 UITextInputTraits *traits = [[alert textField] textInputTraits];
6175 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6176 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6177 [traits setKeyboardType:UIKeyboardTypeURL];
6178 // XXX: UIReturnKeyDone
6179 [traits setReturnKeyType:UIReturnKeyNext];
6184 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6185 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
6186 initWithTitle:UCLocalize("ADD")
6187 style:UIBarButtonItemStylePlain
6189 action:@selector(addButtonClicked)
6191 [[self navigationItem] setLeftBarButtonItem:editing ? leftItem : [[self navigationItem] backBarButtonItem] animated:animated];
6194 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6195 initWithTitle:editing ? UCLocalize("DONE") : UCLocalize("EDIT")
6196 style:editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6198 action:@selector(editButtonClicked)
6200 [[self navigationItem] setRightBarButtonItem:rightItem animated:animated];
6201 [rightItem release];
6203 if (IsWildcat_ && !editing) {
6204 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6205 initWithTitle:UCLocalize("SETTINGS")
6206 style:UIBarButtonItemStylePlain
6208 action:@selector(settingsButtonClicked)
6210 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6211 [settingsItem release];
6215 - (void) settingsButtonClicked {
6216 [delegate_ showSettings];
6219 - (void) editButtonClicked {
6220 [list_ setEditing:![list_ isEditing] animated:YES];
6222 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6228 /* Installed Controller {{{ */
6229 @interface InstalledController : FilteredPackageController {
6233 - (id) initWithDatabase:(Database *)database;
6235 - (void) updateRoleButton;
6236 - (void) queueStatusDidChange;
6240 @implementation InstalledController
6246 - (id) title { return UCLocalize("INSTALLED"); }
6248 - (id) initWithDatabase:(Database *)database {
6249 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6250 [self updateRoleButton];
6251 [self queueStatusDidChange];
6256 - (void) queueButtonClicked {
6261 - (void) queueStatusDidChange {
6264 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6265 initWithTitle:UCLocalize("QUEUE")
6266 style:UIBarButtonItemStyleDone
6268 action:@selector(queueButtonClicked)
6270 if (Queuing_) [[self navigationItem] setLeftBarButtonItem:queueItem];
6271 else [[self navigationItem] setLeftBarButtonItem:nil];
6272 [queueItem release];
6277 - (void) reloadData {
6278 [packages_ reloadData];
6281 - (void) updateRoleButton {
6282 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6283 initWithTitle:expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")
6284 style:expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6286 action:@selector(roleButtonClicked)
6288 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) [[self navigationItem] setRightBarButtonItem:rightItem];
6289 [rightItem release];
6292 - (void) roleButtonClicked {
6293 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6294 [packages_ reloadData];
6297 [self updateRoleButton];
6300 - (void) setDelegate:(id)delegate {
6301 [super setDelegate:delegate];
6302 [packages_ setDelegate:delegate];
6308 /* Home Controller {{{ */
6309 @interface HomeController : CYBrowserController {
6314 @implementation HomeController
6316 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6317 [super _setMoreHeaders:request];
6319 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6320 if (UniqueID_ != nil)
6321 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6324 - (void) aboutButtonClicked {
6325 UIAlertView *alert = [[[UIAlertView alloc] init] autorelease];
6326 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6327 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6328 [alert setCancelButtonIndex:0];
6331 @"Copyright (C) 2008-2010\n"
6332 "Jay Freeman (saurik)\n"
6333 "saurik@saurik.com\n"
6334 "http://www.saurik.com/"
6340 - (void) viewWillAppear:(BOOL)animated {
6341 [super viewWillAppear:animated];
6342 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6345 - (void) viewWillDisappear:(BOOL)animated {
6346 [super viewWillDisappear:animated];
6347 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6351 if ((self = [super init]) != nil) {
6352 UIBarButtonItem *aboutItem = [[UIBarButtonItem alloc]
6353 initWithTitle:UCLocalize("ABOUT")
6354 style:UIBarButtonItemStylePlain
6356 action:@selector(aboutButtonClicked)
6358 [[self navigationItem] setLeftBarButtonItem:aboutItem];
6359 [aboutItem release];
6365 /* Manage Controller {{{ */
6366 @interface ManageController : CYBrowserController {
6369 - (void) queueStatusDidChange;
6372 @implementation ManageController
6375 if ((self = [super init]) != nil) {
6376 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6378 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6379 initWithTitle:UCLocalize("SETTINGS")
6380 style:UIBarButtonItemStylePlain
6382 action:@selector(settingsButtonClicked)
6384 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6385 [settingsItem release];
6387 [self queueStatusDidChange];
6391 - (void) settingsButtonClicked {
6392 [delegate_ showSettings];
6396 - (void) queueButtonClicked {
6400 - (void) applyLoadingTitle {
6401 // No "Loading" title.
6404 - (void) applyRightButton {
6409 - (void) queueStatusDidChange {
6411 if (!IsWildcat_ && Queuing_) {
6412 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6413 initWithTitle:UCLocalize("QUEUE")
6414 style:UIBarButtonItemStyleDone
6416 action:@selector(queueButtonClicked)
6418 [[self navigationItem] setRightBarButtonItem:queueItem];
6420 [queueItem release];
6422 [[self navigationItem] setRightBarButtonItem:nil];
6427 - (bool) isLoading {
6434 /* Refresh Bar {{{ */
6435 @interface RefreshBar : UINavigationBar {
6436 UIProgressIndicator *indicator_;
6437 UITextLabel *prompt_;
6438 UIProgressBar *progress_;
6439 UINavigationButton *cancel_;
6444 @implementation RefreshBar
6446 - (void) positionViews {
6447 CGRect frame = [cancel_ frame];
6448 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6449 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6450 [cancel_ setFrame:frame];
6452 CGSize prgsize = {75, 100};
6454 [self frame].size.width - prgsize.width - 10,
6455 ([self frame].size.height - prgsize.height) / 2
6457 [progress_ setFrame:prgrect];
6459 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6460 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6461 CGRect indrect = {{indoffset, indoffset}, indsize};
6462 [indicator_ setFrame:indrect];
6464 CGSize prmsize = {215, indsize.height + 4};
6466 indoffset * 2 + indsize.width,
6467 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6469 [prompt_ setFrame:prmrect];
6472 - (void)setFrame:(CGRect)frame {
6473 [super setFrame:frame];
6475 [self positionViews];
6478 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6479 if ((self = [super initWithFrame:frame])) {
6480 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6482 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6483 [self setBarStyle:UIBarStyleBlack];
6485 UIBarStyle barstyle([self _barStyle:NO]);
6486 bool ugly(barstyle == UIBarStyleDefault);
6488 UIProgressIndicatorStyle style = ugly ?
6489 UIProgressIndicatorStyleMediumBrown :
6490 UIProgressIndicatorStyleMediumWhite;
6492 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6493 [indicator_ setStyle:style];
6494 [indicator_ startAnimation];
6495 [self addSubview:indicator_];
6497 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6498 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6499 [prompt_ setBackgroundColor:[UIColor clearColor]];
6500 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6501 [self addSubview:prompt_];
6503 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6504 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6505 [progress_ setStyle:0];
6506 [self addSubview:progress_];
6508 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6509 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6510 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6511 [cancel_ setBarStyle:barstyle];
6513 [self positionViews];
6518 [cancel_ removeFromSuperview];
6522 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6523 [progress_ setProgress:0];
6524 [self addSubview:cancel_];
6528 [cancel_ removeFromSuperview];
6531 - (void) setPrompt:(NSString *)prompt {
6532 [prompt_ setText:prompt];
6535 - (void) setProgress:(float)progress {
6536 [progress_ setProgress:progress];
6542 @class CYNavigationController;
6544 /* Cydia Tab Bar Controller {{{ */
6545 @interface CYTabBarController : UITabBarController {
6546 Database *database_;
6551 @implementation CYTabBarController
6553 /* XXX: some logic should probably go here related to
6554 freeing the view controllers on tab change */
6556 - (void) reloadData {
6557 size_t count([[self viewControllers] count]);
6558 for (size_t i(0); i != count; ++i) {
6559 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6564 - (id) initWithDatabase:(Database *)database {
6565 if ((self = [super init]) != nil) {
6566 database_ = database;
6573 /* Cydia Navigation Controller {{{ */
6574 @interface CYNavigationController : UINavigationController {
6575 _transient Database *database_;
6579 - (id) initWithDatabase:(Database *)database;
6580 - (void) reloadData;
6585 @implementation CYNavigationController
6587 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6588 // Inherit autorotation settings for modal parents.
6589 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6590 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6592 return [super shouldAutorotateToInterfaceOrientation:orientation];
6600 - (void) reloadData {
6601 size_t count([[self viewControllers] count]);
6602 for (size_t i(0); i != count; ++i) {
6603 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6608 - (void) setDelegate:(id)delegate {
6609 delegate_ = delegate;
6612 - (id) initWithDatabase:(Database *)database {
6613 if ((self = [super init]) != nil) {
6614 database_ = database;
6620 /* Cydia:// Protocol {{{ */
6621 @interface CydiaURLProtocol : NSURLProtocol {
6626 @implementation CydiaURLProtocol
6628 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6629 NSURL *url([request URL]);
6632 NSString *scheme([[url scheme] lowercaseString]);
6633 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6638 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6642 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6643 id<NSURLProtocolClient> client([self client]);
6645 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6647 NSData *data(UIImagePNGRepresentation(icon));
6649 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6650 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6651 [client URLProtocol:self didLoadData:data];
6652 [client URLProtocolDidFinishLoading:self];
6656 - (void) startLoading {
6657 id<NSURLProtocolClient> client([self client]);
6658 NSURLRequest *request([self request]);
6660 NSURL *url([request URL]);
6661 NSString *href([url absoluteString]);
6663 NSString *path([href substringFromIndex:8]);
6664 NSRange slash([path rangeOfString:@"/"]);
6667 if (slash.location == NSNotFound) {
6671 command = [path substringToIndex:slash.location];
6672 path = [path substringFromIndex:(slash.location + 1)];
6675 Database *database([Database sharedInstance]);
6677 if ([command isEqualToString:@"package-icon"]) {
6680 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6681 Package *package([database packageWithName:path]);
6684 UIImage *icon([package icon]);
6685 [self _returnPNGWithImage:icon forRequest:request];
6686 } else if ([command isEqualToString:@"source-icon"]) {
6689 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6690 NSString *source(Simplify(path));
6691 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6693 icon = [UIImage applicationImageNamed:@"unknown.png"];
6694 [self _returnPNGWithImage:icon forRequest:request];
6695 } else if ([command isEqualToString:@"uikit-image"]) {
6698 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6699 UIImage *icon(_UIImageWithName(path));
6700 [self _returnPNGWithImage:icon forRequest:request];
6701 } else if ([command isEqualToString:@"section-icon"]) {
6704 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6705 NSString *section(Simplify(path));
6706 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6708 icon = [UIImage applicationImageNamed:@"unknown.png"];
6709 [self _returnPNGWithImage:icon forRequest:request];
6711 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6715 - (void) stopLoading {
6721 /* Sections Controller {{{ */
6722 @interface SectionsController : CYViewController <
6723 UITableViewDataSource,
6726 _transient Database *database_;
6727 NSMutableArray *sections_;
6728 NSMutableArray *filtered_;
6734 - (id) initWithDatabase:(Database *)database;
6735 - (void) reloadData;
6738 - (void) editButtonClicked;
6742 @implementation SectionsController
6745 [list_ setDataSource:nil];
6746 [list_ setDelegate:nil];
6748 [sections_ release];
6749 [filtered_ release];
6751 [accessory_ release];
6755 - (void) viewDidAppear:(BOOL)animated {
6756 [super viewDidAppear:animated];
6757 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6760 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6761 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6765 - (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
6766 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6769 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6773 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6774 static NSString *reuseIdentifier = @"SectionCell";
6776 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6777 if (cell == nil) cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6778 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6783 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6784 Section *section = [self sectionAtIndexPath:indexPath];
6785 NSString *name = [section name];
6788 if ([indexPath row] == 0) {
6791 title = UCLocalize("ALL_PACKAGES");
6794 name = [NSString stringWithString:name];
6795 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6798 title = UCLocalize("NO_SECTION");
6802 FilteredPackageController *table = [[[FilteredPackageController alloc]
6803 initWithDatabase:database_
6805 filter:@selector(isVisibleInSection:)
6809 [table setDelegate:delegate_];
6811 [[self navigationController] pushViewController:table animated:YES];
6814 - (id) title { return UCLocalize("SECTIONS"); }
6816 - (id) initWithDatabase:(Database *)database {
6817 if ((self = [super init]) != nil) {
6818 database_ = database;
6820 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6822 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6823 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6825 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6826 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6827 [list_ setRowHeight:45.0f];
6828 [[self view] addSubview:list_];
6830 [list_ setDataSource:self];
6831 [list_ setDelegate:self];
6837 - (void) reloadData {
6838 NSArray *packages = [database_ packages];
6840 [sections_ removeAllObjects];
6841 [filtered_ removeAllObjects];
6844 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6845 SectionMap sections;
6846 sections.resize(64);
6848 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6852 for (Package *package in packages) {
6853 NSString *name([package section]);
6854 NSString *key(name == nil ? @"" : name);
6859 _profile(SectionsView$reloadData$Section)
6860 section = §ions[key];
6861 if (*section == nil) {
6862 _profile(SectionsView$reloadData$Section$Allocate)
6863 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6868 [*section addToCount];
6870 _profile(SectionsView$reloadData$Filter)
6871 if (![package valid] || ![package visible])
6875 [*section addToRow];
6879 _profile(SectionsView$reloadData$Section)
6880 section = [sections objectForKey:key];
6881 if (section == nil) {
6882 _profile(SectionsView$reloadData$Section$Allocate)
6883 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6884 [sections setObject:section forKey:key];
6889 [section addToCount];
6891 _profile(SectionsView$reloadData$Filter)
6892 if (![package valid] || ![package visible])
6902 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6903 [sections_ addObject:i->second];
6905 [sections_ addObjectsFromArray:[sections allValues]];
6908 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6910 for (Section *section in sections_) {
6911 size_t count([section row]);
6915 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6916 [section setCount:count];
6917 [filtered_ addObject:section];
6920 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6921 initWithTitle:[sections_ count] == 0 ? nil : UCLocalize("EDIT")
6922 style:UIBarButtonItemStylePlain
6924 action:@selector(editButtonClicked)
6926 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] != nil];
6927 [rightItem release];
6933 - (void) resetView {
6935 [self editButtonClicked];
6938 - (void) editButtonClicked {
6939 if ((editing_ = !editing_))
6942 [delegate_ updateData];
6944 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6945 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6946 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6949 - (UIView *) accessoryView {
6955 /* Changes Controller {{{ */
6956 @interface ChangesController : CYViewController <
6957 UITableViewDataSource,
6960 _transient Database *database_;
6961 NSMutableArray *packages_;
6962 NSMutableArray *sections_;
6965 BOOL hasSentFirstLoad_;
6968 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6969 - (void) reloadData;
6973 @implementation ChangesController
6976 [list_ setDelegate:nil];
6977 [list_ setDataSource:nil];
6979 [packages_ release];
6980 [sections_ release];
6985 - (void) viewDidAppear:(BOOL)animated {
6986 [super viewDidAppear:animated];
6987 if (!hasSentFirstLoad_) {
6988 hasSentFirstLoad_ = YES;
6989 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6991 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6995 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6996 NSInteger count([sections_ count]);
6997 return count == 0 ? 1 : count;
7000 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7001 if ([sections_ count] == 0)
7003 return [[sections_ objectAtIndex:section] name];
7006 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7007 if ([sections_ count] == 0)
7009 return [[sections_ objectAtIndex:section] count];
7012 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7013 Section *section([sections_ objectAtIndex:[path section]]);
7014 NSInteger row([path row]);
7015 return [packages_ objectAtIndex:([section row] + row)];
7018 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7019 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7021 cell = [[[PackageCell alloc] init] autorelease];
7022 [cell setPackage:[self packageAtIndexPath:path]];
7026 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7027 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7030 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7031 Package *package([self packageAtIndexPath:path]);
7032 PackageController *view([delegate_ packageController]);
7033 [view setDelegate:delegate_];
7034 [view setPackage:package];
7035 [[self navigationController] pushViewController:view animated:YES];
7039 - (void) refreshButtonClicked {
7040 [delegate_ beginUpdate];
7041 [[self navigationItem] setLeftBarButtonItem:nil];
7044 - (void) upgradeButtonClicked {
7045 [delegate_ distUpgrade];
7048 - (id) title { return UCLocalize("CHANGES"); }
7050 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7051 if ((self = [super init]) != nil) {
7052 database_ = database;
7053 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7055 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
7056 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7058 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7059 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7060 [list_ setRowHeight:73.0f];
7061 [[self view] addSubview:list_];
7063 [list_ setDataSource:self];
7064 [list_ setDelegate:self];
7066 delegate_ = delegate;
7070 - (void) _reloadPackages:(NSArray *)packages {
7072 for (Package *package in packages)
7074 [package uninstalled] && [package valid] && [package visible] ||
7075 [package upgradableAndEssential:YES]
7077 [packages_ addObject:package];
7080 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7084 - (void) reloadData {
7085 NSArray *packages = [database_ packages];
7087 [packages_ removeAllObjects];
7088 [sections_ removeAllObjects];
7090 UIProgressHUD *hud([delegate_ addProgressHUD]);
7092 [hud setText:@"Loading Changes"];
7093 NSLog(@"HUD:%@::%@", delegate_, hud);
7094 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7095 [delegate_ removeProgressHUD:hud];
7097 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7098 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7099 Section *section = nil;
7103 bool unseens = false;
7105 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7107 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7108 Package *package = [packages_ objectAtIndex:offset];
7110 BOOL uae = [package upgradableAndEssential:YES];
7116 _profile(ChangesController$reloadData$Remember)
7117 seen = [package seen];
7120 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7125 name = UCLocalize("UNKNOWN");
7127 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7131 _profile(ChangesController$reloadData$Allocate)
7132 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7133 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7134 [sections_ addObject:section];
7138 [section addToCount];
7139 } else if ([package ignored])
7140 [ignored addToCount];
7143 [upgradable addToCount];
7148 CFRelease(formatter);
7151 Section *last = [sections_ lastObject];
7152 size_t count = [last count];
7153 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7154 [sections_ removeLastObject];
7157 if ([ignored count] != 0)
7158 [sections_ insertObject:ignored atIndex:0];
7160 [sections_ insertObject:upgradable atIndex:0];
7164 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7165 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7166 style:UIBarButtonItemStylePlain
7168 action:@selector(upgradeButtonClicked)
7170 if (upgrades_ > 0) [[self navigationItem] setRightBarButtonItem:rightItem];
7171 [rightItem release];
7173 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
7174 initWithTitle:UCLocalize("REFRESH")
7175 style:UIBarButtonItemStylePlain
7177 action:@selector(refreshButtonClicked)
7179 if (![delegate_ updating]) [[self navigationItem] setLeftBarButtonItem:leftItem];
7185 /* Search Controller {{{ */
7186 @interface SearchController : FilteredPackageController <
7189 UISearchBar *search_;
7192 - (id) initWithDatabase:(Database *)database;
7193 - (void) reloadData;
7197 @implementation SearchController
7204 - (void) searchBarSearchButtonClicked:(id)searchBar {
7205 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7206 [search_ resignFirstResponder];
7210 - (void) searchBar:(id)searchBar textDidChange:(NSString *)text {
7211 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7215 - (id) title { return nil; }
7217 - (id) initWithDatabase:(Database *)database {
7218 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7221 - (void)viewDidAppear:(BOOL)animated {
7222 [super viewDidAppear:animated];
7224 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7225 [search_ layoutSubviews];
7226 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7227 UITextField *textField = [search_ searchField];
7228 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7229 [search_ setDelegate:self];
7230 [textField setEnablesReturnKeyAutomatically:NO];
7231 [[self navigationItem] setTitleView:textField];
7235 - (void) _reloadData {
7238 - (void) reloadData {
7239 _profile(SearchController$reloadData)
7240 [packages_ reloadData];
7243 [packages_ resetCursor];
7246 - (void) didSelectPackage:(Package *)package {
7247 [search_ resignFirstResponder];
7248 [super didSelectPackage:package];
7253 /* Settings Controller {{{ */
7254 @interface SettingsController : CYViewController <
7255 UITableViewDataSource,
7258 _transient Database *database_;
7261 UITableView *table_;
7262 id subscribedSwitch_;
7264 UITableViewCell *subscribedCell_;
7265 UITableViewCell *ignoredCell_;
7268 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7272 @implementation SettingsController
7276 if (package_ != nil)
7279 [subscribedSwitch_ release];
7280 [ignoredSwitch_ release];
7281 [subscribedCell_ release];
7282 [ignoredCell_ release];
7287 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7288 if (package_ == nil)
7294 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7295 if (package_ == nil)
7301 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7302 return UCLocalize("SHOW_ALL_CHANGES_EX");
7305 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7306 if (package_ == nil)
7309 NSMutableDictionary *metadata([package_ metadata]);
7312 if (NSNumber *number = [metadata objectForKey:key])
7313 before = [number boolValue];
7317 if (value != before) {
7318 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7320 [delegate_ updateData];
7324 - (void) onSubscribed:(id)control {
7325 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7328 - (void) onIgnored:(id)control {
7329 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
7332 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7333 if (package_ == nil)
7336 switch ([indexPath row]) {
7337 case 0: return subscribedCell_;
7338 case 1: return ignoredCell_;
7346 - (id) title { return UCLocalize("SETTINGS"); }
7348 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7349 if ((self = [super init])) {
7350 database_ = database;
7351 name_ = [package retain];
7353 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7355 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7356 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7357 [table_ setAllowsSelection:NO];
7358 [[self view] addSubview:table_];
7360 subscribedSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7361 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7362 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7364 ignoredSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7365 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7366 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7368 subscribedCell_ = [[UITableViewCell alloc] init];
7369 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7370 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7372 ignoredCell_ = [[UITableViewCell alloc] init];
7373 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7374 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7376 [table_ setDataSource:self];
7377 [table_ setDelegate:self];
7382 - (void) reloadData {
7383 if (package_ != nil)
7384 [package_ autorelease];
7385 package_ = [database_ packageWithName:name_];
7386 if (package_ != nil) {
7388 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7389 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7392 [table_ reloadData];
7398 /* Signature Controller {{{ */
7399 @interface SignatureController : CYBrowserController {
7400 _transient Database *database_;
7404 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7408 @implementation SignatureController
7415 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7417 [super webView:sender didClearWindowObject:window forFrame:frame];
7420 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7421 if ((self = [super init]) != nil) {
7422 database_ = database;
7423 package_ = [package retain];
7428 - (void) reloadData {
7429 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7434 /* Role Controller {{{ */
7435 @interface RoleController : CYViewController <
7436 UITableViewDataSource,
7439 _transient Database *database_;
7441 UITableView *table_;
7442 UISegmentedControl *segment_;
7446 - (void) showDoneButton;
7447 - (void) resizeSegmentedControl;
7451 @implementation RoleController
7455 [container_ release];
7460 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7461 if ((self = [super init])) {
7462 database_ = database;
7463 roledelegate_ = delegate;
7465 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7467 NSArray *items = [NSArray arrayWithObjects:
7469 UCLocalize("HACKER"),
7470 UCLocalize("DEVELOPER"),
7472 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7473 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7474 [container_ addSubview:segment_];
7477 if ([Role_ isEqualToString:@"User"]) index = 0;
7478 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7479 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7481 [segment_ setSelectedSegmentIndex:index];
7482 [self showDoneButton];
7485 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7486 [self resizeSegmentedControl];
7488 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7489 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7490 [table_ setDelegate:self];
7491 [table_ setDataSource:self];
7492 [[self view] addSubview:table_];
7493 [table_ reloadData];
7497 - (void) resizeSegmentedControl {
7498 CGFloat width = [[self view] frame].size.width;
7499 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7502 - (void) viewWillAppear:(BOOL)animated {
7503 [super viewWillAppear:animated];
7505 [self resizeSegmentedControl];
7508 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7509 [self resizeSegmentedControl];
7512 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7513 [self resizeSegmentedControl];
7517 NSString *role(nil);
7519 switch ([segment_ selectedSegmentIndex]) {
7520 case 0: role = @"User"; break;
7521 case 1: role = @"Hacker"; break;
7522 case 2: role = @"Developer"; break;
7527 if (![role isEqualToString:Role_]) {
7528 bool rolling(Role_ == nil);
7531 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7535 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7540 [roledelegate_ loadData];
7542 [roledelegate_ updateData];
7546 - (void) segmentChanged:(UISegmentedControl *)control {
7547 [self showDoneButton];
7550 - (void) doneButtonClicked {
7552 [[self navigationController] dismissModalViewControllerAnimated:YES];
7555 - (void) showDoneButton {
7556 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7557 initWithTitle:UCLocalize("DONE")
7558 style:UIBarButtonItemStyleDone
7560 action:@selector(doneButtonClicked)
7562 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] == nil];
7563 [rightItem release];
7566 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7567 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7571 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7575 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7576 return nil; // This method is required by the protocol.
7579 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7581 return UCLocalize("ROLE_EX");
7583 return [NSString stringWithFormat:
7584 @"%@: %@\n%@: %@\n%@: %@",
7585 UCLocalize("USER"), UCLocalize("USER_EX"),
7586 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7587 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7592 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7593 if (section == 3) return 44.0f;
7597 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7598 if (section == 3) return container_;
7605 /* Cydia Container {{{ */
7606 @interface CYContainer : UIViewController <ProgressDelegate> {
7607 _transient Database *database_;
7608 RefreshBar *refreshbar_;
7613 UITabBarController *root_;
7616 - (void) setTabBarController:(UITabBarController *)controller;
7618 - (void) dropBar:(BOOL)animated;
7619 - (void) beginUpdate;
7620 - (void) raiseBar:(BOOL)animated;
7624 @implementation CYContainer
7626 // NOTE: UIWindow only sends the top controller these messages,
7627 // So we have to forward them on.
7629 - (void) viewDidAppear:(BOOL)animated {
7630 [super viewDidAppear:animated];
7631 [root_ viewDidAppear:animated];
7634 - (void) viewWillAppear:(BOOL)animated {
7635 [super viewWillAppear:animated];
7636 [root_ viewWillAppear:animated];
7639 - (void) viewDidDisappear:(BOOL)animated {
7640 [super viewDidDisappear:animated];
7641 [root_ viewDidDisappear:animated];
7644 - (void) viewWillDisappear:(BOOL)animated {
7645 [super viewWillDisappear:animated];
7646 [root_ viewWillDisappear:animated];
7649 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7653 - (void) setTabBarController:(UITabBarController *)controller {
7655 [[self view] addSubview:[root_ view]];
7658 - (void) setUpdate:(NSDate *)date {
7662 - (void) beginUpdate {
7664 [refreshbar_ start];
7669 detachNewThreadSelector:@selector(performUpdate)
7675 - (void) performUpdate { _pooled
7677 status.setDelegate(self);
7678 [database_ updateWithStatus:status];
7681 performSelectorOnMainThread:@selector(completeUpdate)
7687 - (void) completeUpdate {
7690 [self raiseBar:YES];
7692 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7695 - (void) cancelUpdate {
7696 [refreshbar_ cancel];
7697 [self completeUpdate];
7700 - (void) cancelPressed {
7701 [self cancelUpdate];
7708 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7709 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7712 - (void) startProgress {
7715 - (void) setProgressTitle:(NSString *)title {
7717 performSelectorOnMainThread:@selector(_setProgressTitle:)
7723 - (bool) isCancelling:(size_t)received {
7727 - (void) setProgressPercent:(float)percent {
7729 performSelectorOnMainThread:@selector(_setProgressPercent:)
7730 withObject:[NSNumber numberWithFloat:percent]
7735 - (void) addProgressOutput:(NSString *)output {
7737 performSelectorOnMainThread:@selector(_addProgressOutput:)
7743 - (void) _setProgressTitle:(NSString *)title {
7744 [refreshbar_ setPrompt:title];
7747 - (void) _setProgressPercent:(NSNumber *)percent {
7748 [refreshbar_ setProgress:[percent floatValue]];
7751 - (void) _addProgressOutput:(NSString *)output {
7754 - (void) setUpdateDelegate:(id)delegate {
7755 updatedelegate_ = delegate;
7758 - (void) dropBar:(BOOL)animated {
7759 if (dropped_) return;
7762 [[self view] addSubview:refreshbar_];
7764 if (animated) [UIView beginAnimations:nil context:NULL];
7765 CGRect barframe = [refreshbar_ frame];
7766 CGRect viewframe = [[root_ view] frame];
7767 viewframe.origin.y += barframe.size.height;
7768 viewframe.size.height -= barframe.size.height;
7769 [[root_ view] setFrame:viewframe];
7770 if (animated) [UIView commitAnimations];
7772 // Ensure bar has the proper width for our view, it might have changed
7773 barframe.size.width = viewframe.size.width;
7774 [refreshbar_ setFrame:barframe];
7776 // XXX: fix Apple's layout bug
7777 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7780 - (void) raiseBar:(BOOL)animated {
7781 if (!dropped_) return;
7784 [refreshbar_ removeFromSuperview];
7786 if (animated) [UIView beginAnimations:nil context:NULL];
7787 CGRect barframe = [refreshbar_ frame];
7788 CGRect viewframe = [[root_ view] frame];
7789 viewframe.origin.y -= barframe.size.height;
7790 viewframe.size.height += barframe.size.height;
7791 [[root_ view] setFrame:viewframe];
7792 if (animated) [UIView commitAnimations];
7794 // XXX: fix Apple's layout bug
7795 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7798 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7799 // XXX: fix Apple's layout bug
7800 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7803 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7809 // XXX: fix Apple's layout bug
7810 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7814 [refreshbar_ release];
7818 - (id) initWithDatabase: (Database *)database {
7819 if ((self = [super init]) != nil) {
7820 database_ = database;
7822 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7824 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7841 @interface Cydia : UIApplication <
7842 ConfirmationControllerDelegate,
7843 ProgressControllerDelegate,
7847 CYContainer *container_;
7851 NSMutableArray *essential_;
7852 NSMutableArray *broken_;
7854 Database *database_;
7858 UIKeyboard *keyboard_;
7859 UIProgressHUD *hud_;
7861 SectionsController *sections_;
7862 ChangesController *changes_;
7863 ManageController *manage_;
7864 SearchController *search_;
7865 SourceTable *sources_;
7866 InstalledController *installed_;
7869 #if RecyclePackageViews
7870 NSMutableArray *details_;
7876 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7877 - (void) setPage:(CYViewController *)page;
7882 static _finline void _setHomePage(Cydia *self) {
7883 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7886 @implementation Cydia
7888 - (void) beginUpdate {
7889 [container_ beginUpdate];
7893 return [container_ updating];
7896 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7901 if ([broken_ count] != 0) {
7902 int count = [broken_ count];
7904 UIAlertView *alert = [[[UIAlertView alloc]
7905 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7906 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7908 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7909 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
7912 [alert setContext:@"fixhalf"];
7914 } else if (!Ignored_ && [essential_ count] != 0) {
7915 int count = [essential_ count];
7917 UIAlertView *alert = [[[UIAlertView alloc]
7918 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7919 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
7921 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
7922 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
7925 [alert setContext:@"upgrade"];
7930 - (void) _saveConfig {
7933 NSString *error(nil);
7934 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7936 NSError *error(nil);
7937 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7938 NSLog(@"failure to save metadata data: %@", error);
7941 NSLog(@"failure to serialize metadata: %@", error);
7949 - (void) _updateData {
7952 /* XXX: this is just stupid */
7953 if (tag_ != 1 && sections_ != nil)
7954 [sections_ reloadData];
7955 if (tag_ != 2 && changes_ != nil)
7956 [changes_ reloadData];
7957 if (tag_ != 4 && search_ != nil)
7958 [search_ reloadData];
7960 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
7963 - (int)indexOfTabWithTag:(int)tag {
7965 for (UINavigationController *controller in [tabbar_ viewControllers]) {
7966 if ([[controller tabBarItem] tag] == tag) return i;
7973 - (void) _refreshIfPossible {
7974 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
7976 Reachability* reachability = [Reachability reachabilityWithHostName:@"cydia.saurik.com"];
7977 NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
7979 if (loaded_ || ManualRefresh || remoteHostStatus == NotReachable) loaded:
7980 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
7984 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
7986 if (update != nil) {
7987 NSTimeInterval interval([update timeIntervalSinceNow]);
7988 if (interval <= 0 && interval > -(15*60))
7992 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
7998 - (void) refreshIfPossible {
7999 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8002 - (void) _reloadData {
8003 UIProgressHUD *hud([self addProgressHUD]);
8004 [hud setText:(loaded_ ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
8006 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8009 [self removeProgressHUD:hud];
8013 [essential_ removeAllObjects];
8014 [broken_ removeAllObjects];
8016 NSArray *packages([database_ packages]);
8017 for (Package *package in packages) {
8019 [broken_ addObject:package];
8020 if ([package upgradableAndEssential:NO]) {
8021 if ([package essential])
8022 [essential_ addObject:package];
8028 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8029 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:badge];
8030 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:YES];
8032 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8033 [self setApplicationBadge:badge];
8035 [self setApplicationBadgeString:badge];
8037 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:nil];
8038 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:NO];
8040 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8041 [self removeApplicationBadge];
8042 else // XXX: maybe use setApplicationBadgeString also?
8043 [self setApplicationIconBadgeNumber:0];
8048 [self refreshIfPossible];
8051 - (void) updateData {
8052 [database_ setVisible];
8061 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8062 _assert(file != NULL);
8064 for (NSString *key in [Sources_ allKeys]) {
8065 NSDictionary *source([Sources_ objectForKey:key]);
8067 fprintf(file, "%s %s %s\n",
8068 [[source objectForKey:@"Type"] UTF8String],
8069 [[source objectForKey:@"URI"] UTF8String],
8070 [[source objectForKey:@"Distribution"] UTF8String]
8078 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8079 UINavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8080 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8081 [container_ presentModalViewController:navigation animated:YES];
8084 detachNewThreadSelector:@selector(update_)
8087 title:UCLocalize("UPDATING_SOURCES")
8091 - (void) reloadData {
8092 @synchronized (self) {
8098 pkgProblemResolver *resolver = [database_ resolver];
8100 resolver->InstallProtect();
8101 if (!resolver->Resolve(true))
8105 - (CGRect) popUpBounds {
8106 return [[tabbar_ view] bounds];
8110 if (![database_ prepare])
8113 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8114 [page setDelegate:self];
8115 id confirm_ = [[CYNavigationController alloc] initWithRootViewController:page];
8116 [confirm_ setDelegate:self];
8118 if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8119 [container_ presentModalViewController:confirm_ animated:YES];
8125 @synchronized (self) {
8130 - (void) clearPackage:(Package *)package {
8131 @synchronized (self) {
8138 - (void) installPackages:(NSArray *)packages {
8139 @synchronized (self) {
8140 for (Package *package in packages)
8147 - (void) installPackage:(Package *)package {
8148 @synchronized (self) {
8155 - (void) removePackage:(Package *)package {
8156 @synchronized (self) {
8163 - (void) distUpgrade {
8164 @synchronized (self) {
8165 if (![database_ upgrade])
8172 @synchronized (self) {
8177 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8178 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8180 if (navigation != nil) {
8181 [navigation pushViewController:progress animated:YES];
8183 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8184 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8185 [container_ presentModalViewController:navigation animated:YES];
8189 detachNewThreadSelector:@selector(perform)
8192 title:UCLocalize("RUNNING")
8196 - (void) progressControllerIsComplete:(ProgressController *)progress {
8200 - (void) setPage:(CYViewController *)page {
8201 [page setDelegate:self];
8203 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8204 [navController setViewControllers:[NSArray arrayWithObject:page] animated:NO];
8205 for (CYNavigationController *page in [tabbar_ viewControllers]) {
8206 if (page != navController) [page setViewControllers:nil];
8210 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8211 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8212 [browser loadURL:url];
8216 - (SectionsController *) sectionsController {
8217 if (sections_ == nil)
8218 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8222 - (ChangesController *) changesController {
8223 if (changes_ == nil)
8224 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8228 - (ManageController *) manageController {
8229 if (manage_ == nil) {
8230 manage_ = (ManageController *) [[self
8231 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8232 withClass:[ManageController class]
8234 if (!IsWildcat_) queueDelegate_ = manage_;
8239 - (SearchController *) searchController {
8241 search_ = [[SearchController alloc] initWithDatabase:database_];
8245 - (SourceTable *) sourcesController {
8246 if (sources_ == nil)
8247 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8251 - (InstalledController *) installedController {
8252 if (installed_ == nil) {
8253 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8254 if (IsWildcat_) queueDelegate_ = installed_;
8259 - (void) tabBarController:(id)tabBarController didSelectViewController:(UIViewController *)viewController {
8260 int tag = [[viewController tabBarItem] tag];
8262 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8264 } else if (tag_ == 1) {
8265 [[self sectionsController] resetView];
8269 case kCydiaTag: _setHomePage(self); break;
8271 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8272 case kChangesTag: [self setPage:[self changesController]]; break;
8273 case kManageTag: [self setPage:[self manageController]]; break;
8274 case kInstalledTag: [self setPage:[self installedController]]; break;
8275 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8276 case kSearchTag: [self setPage:[self searchController]]; break;
8284 - (void) showSettings {
8285 RoleController *role = [[RoleController alloc] initWithDatabase:database_ delegate:self];
8286 CYNavigationController *nav = [[CYNavigationController alloc] initWithRootViewController:role];
8287 if (IsWildcat_) [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8288 [container_ presentModalViewController:nav animated:YES];
8291 - (void) setPackageController:(PackageController *)view {
8293 [view setPackage:nil];
8294 #if RecyclePackageViews
8295 if ([details_ count] < 3)
8296 [details_ addObject:view];
8301 - (PackageController *) _packageController {
8302 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8305 - (PackageController *) packageController {
8306 #if RecyclePackageViews
8307 PackageController *view;
8308 size_t count([details_ count]);
8311 view = [self _packageController];
8313 [details_ addObject:[self _packageController]];
8315 view = [[[details_ lastObject] retain] autorelease];
8316 [details_ removeLastObject];
8323 return [self _packageController];
8327 - (void) cancelAndClear:(bool)clear {
8328 @synchronized (self) {
8330 /* XXX: clear marks instead of reloading data */
8331 /*pkgCacheFile &cache([database_ cache]);
8332 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
8333 if (!cache[iterator].Keep()) cache->MarkKeep(iterator, false, false);
8339 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kManageTag] != -1 ? [self indexOfTabWithTag:kManageTag] : [self indexOfTabWithTag:kInstalledTag]] tabBarItem] setBadgeValue:nil];
8340 [queueDelegate_ queueStatusDidChange];*/
8345 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kManageTag] != -1 ? [self indexOfTabWithTag:kManageTag] : [self indexOfTabWithTag:kInstalledTag]] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8346 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8348 [queueDelegate_ queueStatusDidChange];
8353 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8354 NSString *context([alert context]);
8356 if ([context isEqualToString:@"fixhalf"]) {
8357 if (button == [alert firstOtherButtonIndex]) {
8358 @synchronized (self) {
8359 for (Package *broken in broken_) {
8362 NSString *id = [broken id];
8363 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8364 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8365 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8366 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8372 } else if (button == [alert cancelButtonIndex]) {
8373 [broken_ removeAllObjects];
8377 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8378 } else if ([context isEqualToString:@"upgrade"]) {
8379 if (button == [alert firstOtherButtonIndex]) {
8380 @synchronized (self) {
8381 for (Package *essential in essential_)
8382 [essential install];
8387 } else if (button == [alert firstOtherButtonIndex] + 1) {
8389 } else if (button == [alert cancelButtonIndex]) {
8393 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8397 - (void) system:(NSString *)command { _pooled
8398 system([command UTF8String]);
8401 - (void) applicationWillSuspend {
8403 [super applicationWillSuspend];
8406 - (void) applicationSuspend:(__GSEvent *)event {
8407 // FIXME: This needs to be fixed, but we no longer have a progress_.
8408 // What's the best solution?
8409 if (hud_ == nil)// && ![progress_ isRunning])
8410 [super applicationSuspend:event];
8413 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8415 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8418 - (void) _setSuspended:(BOOL)value {
8420 [super _setSuspended:value];
8423 - (UIProgressHUD *) addProgressHUD {
8424 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8425 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8427 [window_ setUserInteractionEnabled:NO];
8429 [[container_ view] addSubview:hud];
8433 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8435 [hud removeFromSuperview];
8436 [window_ setUserInteractionEnabled:YES];
8439 - (CYViewController *) pageForPackage:(NSString *)name {
8440 if (Package *package = [database_ packageWithName:name]) {
8441 PackageController *view([self packageController]);
8442 [view setPackage:package];
8445 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8446 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8447 return [self _pageForURL:url withClass:[CYBrowserController class]];
8451 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8455 NSString *href([url absoluteString]);
8456 if ([href hasPrefix:@"apptapp://package/"])
8457 return [self pageForPackage:[href substringFromIndex:18]];
8459 NSString *scheme([[url scheme] lowercaseString]);
8460 if (![scheme isEqualToString:@"cydia"])
8462 NSString *path([url absoluteString]);
8463 if ([path length] < 8)
8465 path = [path substringFromIndex:8];
8466 if (![path hasPrefix:@"/"])
8467 path = [@"/" stringByAppendingString:path];
8469 if ([path isEqualToString:@"/add-source"])
8470 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8471 else if ([path isEqualToString:@"/storage"])
8472 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8473 else if ([path isEqualToString:@"/sources"])
8474 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8475 else if ([path isEqualToString:@"/packages"])
8476 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8477 else if ([path hasPrefix:@"/url/"])
8478 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8479 else if ([path hasPrefix:@"/launch/"])
8480 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8481 else if ([path hasPrefix:@"/package-settings/"])
8482 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8483 else if ([path hasPrefix:@"/package-signature/"])
8484 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8485 else if ([path hasPrefix:@"/package/"])
8486 return [self pageForPackage:[path substringFromIndex:9]];
8487 else if ([path hasPrefix:@"/files/"]) {
8488 NSString *name = [path substringFromIndex:7];
8490 if (Package *package = [database_ packageWithName:name]) {
8491 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8492 [files setPackage:package];
8500 - (void) applicationOpenURL:(NSURL *)url {
8501 [super applicationOpenURL:url];
8503 if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
8504 [self setPage:page];
8506 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8510 - (void) applicationWillResignActive:(UIApplication *)application {
8511 // Stop refreshing if you get a phone call or lock the device.
8512 if ([container_ updating]) [container_ cancelUpdate];
8514 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8515 [super applicationWillResignActive:application];
8518 - (void) applicationDidFinishLaunching:(id)unused {
8519 [CYBrowserController _initialize];
8521 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8523 Font12_ = [[UIFont systemFontOfSize:12] retain];
8524 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8525 Font14_ = [[UIFont systemFontOfSize:14] retain];
8526 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8527 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8531 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8532 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8534 UIScreen *screen([UIScreen mainScreen]);
8536 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8537 [window_ orderFront:self];
8538 [window_ makeKey:self];
8539 [window_ setHidden:NO];
8541 database_ = [Database sharedInstance];
8544 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8545 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8546 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8547 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8548 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8549 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8550 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8551 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8552 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8555 [self setIdleTimerDisabled:YES];
8557 hud_ = [self addProgressHUD];
8558 [hud_ setText:@"Reorganizing:\n\nWill Automatically\nClose When Done"];
8559 [self setStatusBarShowsProgress:YES];
8561 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8563 [self setStatusBarShowsProgress:NO];
8564 [self removeProgressHUD:hud_];
8567 if (ExecFork() == 0) {
8568 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8569 perror("launchctl stop");
8577 NSMutableArray *items([NSMutableArray arrayWithObjects:
8578 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8579 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8580 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8581 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8585 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8586 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8588 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8591 NSMutableArray *controllers([NSMutableArray array]);
8593 for (UITabBarItem *item in items) {
8594 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8595 [controller setTabBarItem:item];
8596 [controllers addObject:controller];
8599 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8600 [tabbar_ setViewControllers:controllers];
8601 [tabbar_ setDelegate:self];
8602 [tabbar_ setSelectedIndex:0];
8604 container_ = [[CYContainer alloc] initWithDatabase:database_];
8605 [container_ setUpdateDelegate:self];
8606 [container_ setTabBarController:tabbar_];
8607 [window_ addSubview:[container_ view]];
8609 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8614 [self showSettings];
8618 [UIKeyboard initImplementationNow];
8622 #if RecyclePackageViews
8623 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8624 [details_ addObject:[self _packageController]];
8625 [details_ addObject:[self _packageController]];
8633 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8634 if (item != nil && IsWildcat_) {
8635 [sheet showFromBarButtonItem:item animated:YES];
8637 [sheet showInView:window_];
8644 id Alloc_(id self, SEL selector) {
8645 id object = alloc_(self, selector);
8646 lprintf("[%s]A-%p\n", self->isa->name, object);
8651 id Dealloc_(id self, SEL selector) {
8652 id object = dealloc_(self, selector);
8653 lprintf("[%s]D-%p\n", self->isa->name, object);
8657 Class $WebDefaultUIKitDelegate;
8659 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8660 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8661 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8662 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8665 static NSNumber *shouldPlayKeyboardSounds;
8669 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8671 case 1104: // Keyboard Button Clicked
8672 case 1105: // Keyboard Delete Repeated
8673 if (shouldPlayKeyboardSounds == nil) {
8674 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8675 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8678 if (![shouldPlayKeyboardSounds boolValue])
8682 _UIHardware$_playSystemSound$(self, _cmd, sound);
8686 int main(int argc, char *argv[]) { _pooled
8689 if (Class $UIDevice = objc_getClass("UIDevice")) {
8690 UIDevice *device([$UIDevice currentDevice]);
8691 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8695 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8697 /* Library Hacks {{{ */
8698 class_addMethod(objc_getClass("WebScriptObject"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &WebScriptObject$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8699 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8701 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8702 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8703 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8704 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8705 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8708 $UIHardware = objc_getClass("UIHardware");
8709 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8710 if (UIHardware$_playSystemSound$ != NULL) {
8711 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8712 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8715 /* Set Locale {{{ */
8716 Locale_ = CFLocaleCopyCurrent();
8717 Languages_ = [NSLocale preferredLanguages];
8718 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8719 //NSLog(@"%@", [Languages_ description]);
8722 if (Languages_ == nil || [Languages_ count] == 0)
8723 // XXX: consider just setting to C and then falling through?
8726 lang = [[Languages_ objectAtIndex:0] UTF8String];
8727 setenv("LANG", lang, true);
8730 //std::setlocale(LC_ALL, lang);
8731 NSLog(@"Setting Language: %s", lang);
8734 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8736 /* Parse Arguments {{{ */
8737 bool substrate(false);
8743 for (int argi(1); argi != argc; ++argi)
8744 if (strcmp(argv[argi], "--") == 0) {
8746 argv[argi] = argv[0];
8752 for (int argi(1); argi != arge; ++argi)
8753 if (strcmp(args[argi], "--substrate") == 0)
8756 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8760 App_ = [[NSBundle mainBundle] bundlePath];
8761 Home_ = NSHomeDirectory();
8767 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8768 alloc_ = alloc->method_imp;
8769 alloc->method_imp = (IMP) &Alloc_;*/
8771 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8772 dealloc_ = dealloc->method_imp;
8773 dealloc->method_imp = (IMP) &Dealloc_;*/
8775 /* System Information {{{ */
8779 size = sizeof(maxproc);
8780 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8781 perror("sysctlbyname(\"kern.maxproc\", ?)");
8782 else if (maxproc < 64) {
8784 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8785 perror("sysctlbyname(\"kern.maxproc\", #)");
8788 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8789 char *osversion = new char[size];
8790 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8791 perror("sysctlbyname(\"kern.osversion\", ?)");
8793 System_ = [NSString stringWithUTF8String:osversion];
8795 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8796 char *machine = new char[size];
8797 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8798 perror("sysctlbyname(\"hw.machine\", ?)");
8802 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8803 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8804 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8805 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8809 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8810 NSData *data((NSData *) ecid);
8811 size_t length([data length]);
8812 uint8_t bytes[length];
8813 [data getBytes:bytes];
8814 char string[length * 2 + 1];
8815 for (size_t i(0); i != length; ++i)
8816 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8817 ChipID_ = [NSString stringWithUTF8String:string];
8821 IOObjectRelease(service);
8825 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8827 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8828 Build_ = [system objectForKey:@"ProductBuildVersion"];
8829 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8830 Product_ = [info objectForKey:@"SafariProductVersion"];
8831 Safari_ = [info objectForKey:@"CFBundleVersion"];
8834 /* Load Database {{{ */
8836 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8838 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8841 if (Metadata_ == NULL)
8842 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8844 Settings_ = [Metadata_ objectForKey:@"Settings"];
8846 Packages_ = [Metadata_ objectForKey:@"Packages"];
8847 Sections_ = [Metadata_ objectForKey:@"Sections"];
8848 Sources_ = [Metadata_ objectForKey:@"Sources"];
8850 Token_ = [Metadata_ objectForKey:@"Token"];
8853 if (Settings_ != nil)
8854 Role_ = [Settings_ objectForKey:@"Role"];
8856 if (Packages_ == nil) {
8857 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8858 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8861 if (Sections_ == nil) {
8862 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8863 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8866 if (Sources_ == nil) {
8867 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8868 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8873 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8876 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8878 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
8879 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
8880 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8881 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8882 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8883 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8885 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
8887 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8888 unlink("/tmp/.cydia.fw");
8890 } else if (access("/User", F_OK) != 0 || version < 2) {
8893 system("/usr/libexec/cydia/firmware.sh");
8897 _assert([[NSFileManager defaultManager]
8898 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8899 withIntermediateDirectories:YES
8904 if (access("/tmp/cydia.chk", F_OK) == 0) {
8905 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8906 _assert(errno == ENOENT);
8907 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8908 _assert(errno == ENOENT);
8911 /* APT Initialization {{{ */
8912 _assert(pkgInitConfig(*_config));
8913 _assert(pkgInitSystem(*_config, _system));
8916 _config->Set("APT::Acquire::Translation", lang);
8917 _config->Set("Acquire::http::Timeout", 15);
8918 _config->Set("Acquire::http::MaxParallel", 3);
8920 /* Color Choices {{{ */
8921 space_ = CGColorSpaceCreateDeviceRGB();
8923 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8924 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8925 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8926 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8927 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8928 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8929 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8930 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8931 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8933 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8934 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8936 /* UIKit Configuration {{{ */
8937 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8938 if ($GSFontSetUseLegacyFontMetrics != NULL)
8939 $GSFontSetUseLegacyFontMetrics(YES);
8941 // XXX: I have a feeling this was important
8942 //UIKeyboardDisableAutomaticAppearance();
8945 Colon_ = UCLocalize("COLON_DELIMITED");
8946 Error_ = UCLocalize("ERROR");
8947 Warning_ = UCLocalize("WARNING");
8950 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
8952 CGColorSpaceRelease(space_);