1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2010 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "UICaboodle/UCPlatform.h"
45 #include "UICaboodle/UCLocalize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
111 #include <mach-o/nlist.h>
121 #include <ext/hash_map>
123 #include "UICaboodle/BrowserView.h"
125 #include "substrate.h"
132 #define _timestamp ({ \
134 gettimeofday(&tv, NULL); \
135 tv.tv_sec * 1000000 + tv.tv_usec; \
138 typedef std::vector<class ProfileTime *> TimeList;
148 ProfileTime(const char *name) :
152 times_.push_back(this);
155 void AddTime(uint64_t time) {
162 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
174 ProfileTimer(ProfileTime &time) :
181 time_.AddTime(_timestamp - start_);
186 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
188 std::cerr << "========" << std::endl;
191 #define _profile(name) { \
192 static ProfileTime name(#name); \
193 ProfileTimer _ ## name(name);
198 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
200 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
202 void NSLogPoint(const char *fix, const CGPoint &point) {
203 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
206 void NSLogRect(const char *fix, const CGRect &rect) {
207 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
210 static _finline NSString *CydiaURL(NSString *path) {
212 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
213 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
214 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
215 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
216 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
217 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
220 static _finline void UpdateExternalStatus(uint64_t newStatus) {
222 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
223 notify_set_state(notify_token, newStatus);
224 notify_cancel(notify_token);
226 notify_post("com.saurik.Cydia.status");
229 /* [NSObject yieldToSelector:(withObject:)] {{{*/
230 @interface NSObject (Cydia)
231 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
232 - (id) yieldToSelector:(SEL)selector;
235 @implementation NSObject (Cydia)
240 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
241 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
242 id object([[context objectAtIndex:1] nonretainedObjectValue]);
243 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
245 /* XXX: deal with exceptions */
246 id value([self performSelector:selector withObject:object]);
248 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
249 [context removeAllObjects];
250 if ([signature methodReturnLength] != 0 && value != nil)
251 [context addObject:value];
256 performSelectorOnMainThread:@selector(doNothing)
262 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
263 /*return [self performSelector:selector withObject:object];*/
265 volatile bool stopped(false);
267 NSMutableArray *context([NSMutableArray arrayWithObjects:
268 [NSValue valueWithPointer:selector],
269 [NSValue valueWithNonretainedObject:object],
270 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
273 NSThread *thread([[[NSThread alloc]
275 selector:@selector(_yieldToContext:)
281 NSRunLoop *loop([NSRunLoop currentRunLoop]);
282 NSDate *future([NSDate distantFuture]);
284 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
286 return [context count] == 0 ? nil : [context objectAtIndex:0];
289 - (id) yieldToSelector:(SEL)selector {
290 return [self yieldToSelector:selector withObject:nil];
296 @interface CYActionSheet : UIAlertView {
300 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
303 @implementation CYActionSheet
305 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
306 if ((self = [super init])) {
307 [self setTitle:title];
308 [self setDelegate:self];
309 for (NSString *button in buttons) [self addButtonWithTitle:button];
310 [self setCancelButtonIndex:index];
314 - (void) _updateFrameForDisplay {
315 [super _updateFrameForDisplay];
316 if ([self cancelButtonIndex] == -1) {
317 NSArray *buttons = [self buttons];
318 if ([buttons count]) {
319 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
320 for (UIThreePartButton *button in buttons)
321 [button setBackground:background forState:0];
326 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
327 button_ = buttonIndex + 1;
331 [self dismissWithClickedButtonIndex:-1 animated:YES];
334 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
335 [self setRunsModal:YES];
343 /* NSForcedOrderingSearch doesn't work on the iPhone */
344 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
345 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
346 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
348 /* Information Dictionaries {{{ */
349 @interface NSMutableArray (Cydia)
350 - (void) addInfoDictionary:(NSDictionary *)info;
353 @implementation NSMutableArray (Cydia)
355 - (void) addInfoDictionary:(NSDictionary *)info {
356 [self addObject:info];
361 @interface NSMutableDictionary (Cydia)
362 - (void) addInfoDictionary:(NSDictionary *)info;
365 @implementation NSMutableDictionary (Cydia)
367 - (void) addInfoDictionary:(NSDictionary *)info {
368 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
374 #define lprintf(args...) fprintf(stderr, args)
377 #define TraceLogging (1 && !ForRelease)
378 #define HistogramInsertionSort (0 && !ForRelease)
379 #define ProfileTimes (0 && !ForRelease)
380 #define ForSaurik (0 && !ForRelease)
381 #define LogBrowser (0 && !ForRelease)
382 #define TrackResize (0 && !ForRelease)
383 #define ManualRefresh (0 && !ForRelease)
384 #define ShowInternals (0 && !ForRelease)
385 #define IgnoreInstall (0 && !ForRelease)
386 #define RecycleWebViews 0
387 #define RecyclePackageViews (1 && ForRelease)
388 #define AlwaysReload (1 && !ForRelease)
392 #define _trace(args...)
397 #define _profile(name) {
400 #define PrintTimes() do {} while (false)
404 typedef uint32_t (*SKRadixFunction)(id, void *);
406 @interface NSMutableArray (Radix)
407 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
408 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
416 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
417 struct RadixItem_ *lhs(swap), *rhs(swap + count);
419 static const size_t width = 32;
420 static const size_t bits = 11;
421 static const size_t slots = 1 << bits;
422 static const size_t passes = (width + (bits - 1)) / bits;
424 size_t *hist(new size_t[slots]);
426 for (size_t pass(0); pass != passes; ++pass) {
427 memset(hist, 0, sizeof(size_t) * slots);
429 for (size_t i(0); i != count; ++i) {
430 uint32_t key(lhs[i].key);
432 key &= _not(uint32_t) >> width - bits;
437 for (size_t i(0); i != slots; ++i) {
438 size_t local(offset);
443 for (size_t i(0); i != count; ++i) {
444 uint32_t key(lhs[i].key);
446 key &= _not(uint32_t) >> width - bits;
447 rhs[hist[key]++] = lhs[i];
450 RadixItem_ *tmp(lhs);
457 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
458 for (size_t i(0); i != count; ++i)
459 [values addObject:[self objectAtIndex:lhs[i].index]];
460 [self setArray:values];
465 @implementation NSMutableArray (Radix)
467 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
468 size_t count([self count]);
473 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
474 [invocation setSelector:selector];
475 [invocation setArgument:&object atIndex:2];
477 /* XXX: this is an unsafe optimization of doomy hell */
478 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
479 _assert(method != NULL);
480 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
481 _assert(imp != NULL);
484 struct RadixItem_ *swap(new RadixItem_[count * 2]);
486 for (size_t i(0); i != count; ++i) {
487 RadixItem_ &item(swap[i]);
490 id object([self objectAtIndex:i]);
493 [invocation setTarget:object];
495 [invocation getReturnValue:&item.key];
497 item.key = imp(object, selector, object);
501 RadixSort_(self, count, swap);
504 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
505 size_t count([self count]);
506 struct RadixItem_ *swap(new RadixItem_[count * 2]);
508 for (size_t i(0); i != count; ++i) {
509 RadixItem_ &item(swap[i]);
512 id object([self objectAtIndex:i]);
513 item.key = function(object, argument);
516 RadixSort_(self, count, swap);
521 /* Insertion Sort {{{ */
523 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
524 const char *ptr = (const char *)list;
526 CFIndex half = count / 2;
527 const char *probe = ptr + elementSize * half;
528 CFComparisonResult cr = comparator(element, probe, context);
529 if (0 == cr) return (probe - (const char *)list) / elementSize;
530 ptr = (cr < 0) ? ptr : probe + elementSize;
531 count = (cr < 0) ? half : (half + (count & 1) - 1);
533 return (ptr - (const char *)list) / elementSize;
536 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
537 const char *ptr = (const char *)list;
539 CFIndex half = count / 2;
540 const char *probe = ptr + elementSize * half;
541 CFComparisonResult cr = comparator(element, probe, context);
542 if (0 == cr) return (probe - (const char *)list) / elementSize;
543 ptr = (cr < 0) ? ptr : probe + elementSize;
544 count = (cr < 0) ? half : (half + (count & 1) - 1);
546 return (ptr - (const char *)list) / elementSize;
549 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
550 if (range.length == 0)
552 const void **values(new const void *[range.length]);
553 CFArrayGetValues(array, range, values);
555 #if HistogramInsertionSort
556 uint32_t total(0), *offsets(new uint32_t[range.length]);
559 for (CFIndex index(1); index != range.length; ++index) {
560 const void *value(values[index]);
561 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
562 CFIndex correct(index);
563 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
566 if (correct != index) {
567 size_t offset(index - correct);
568 #if HistogramInsertionSort
572 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
574 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
575 values[correct] = value;
579 CFArrayReplaceValues(array, range, values, range.length);
582 #if HistogramInsertionSort
583 for (CFIndex index(0); index != range.length; ++index)
584 if (offsets[index] != 0)
585 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
586 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
593 /* Apple Bug Fixes {{{ */
594 @implementation UIWebDocumentView (Cydia)
596 - (void) _setScrollerOffset:(CGPoint)offset {
597 UIScroller *scroller([self _scroller]);
599 CGSize size([scroller contentSize]);
600 CGSize bounds([scroller bounds].size);
603 max.x = size.width - bounds.width;
604 max.y = size.height - bounds.height;
612 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
613 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
615 [scroller setOffset:offset];
621 @implementation WebScriptObject (NSFastEnumeration)
623 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(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;
638 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
639 size_t length([self length] - state->state);
642 else if (length > count)
644 for (size_t i(0); i != length; ++i)
645 objects[i] = [self item:state->state++];
646 state->itemsPtr = objects;
647 state->mutationsPtr = (unsigned long *) self;
651 /* Cydia NSString Additions {{{ */
652 @interface NSString (Cydia)
653 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
654 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
655 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
656 - (NSComparisonResult) compareByPath:(NSString *)other;
657 - (NSString *) stringByCachingURLWithCurrentCDN;
658 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
661 @implementation NSString (Cydia)
663 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
664 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
667 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
668 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
669 memcpy(data, bytes, length);
670 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
673 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
674 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
677 - (NSComparisonResult) compareByPath:(NSString *)other {
678 NSString *prefix = [self commonPrefixWithString:other options:0];
679 size_t length = [prefix length];
681 NSRange lrange = NSMakeRange(length, [self length] - length);
682 NSRange rrange = NSMakeRange(length, [other length] - length);
684 lrange = [self rangeOfString:@"/" options:0 range:lrange];
685 rrange = [other rangeOfString:@"/" options:0 range:rrange];
687 NSComparisonResult value;
689 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
690 value = NSOrderedSame;
691 else if (lrange.location == NSNotFound)
692 value = NSOrderedAscending;
693 else if (rrange.location == NSNotFound)
694 value = NSOrderedDescending;
696 value = NSOrderedSame;
698 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
699 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
700 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
701 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
703 NSComparisonResult result = [lpath compare:rpath];
704 return result == NSOrderedSame ? value : result;
707 - (NSString *) stringByCachingURLWithCurrentCDN {
709 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
710 withString:@"://cache.cydia.saurik.com/"
714 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
715 return [(id)CFURLCreateStringByAddingPercentEscapes(
720 kCFStringEncodingUTF8
727 /* C++ NSString Wrapper Cache {{{ */
734 _finline void clear_() {
735 if (cache_ != NULL) {
742 _finline bool empty() const {
746 _finline size_t size() const {
750 _finline char *data() const {
754 _finline void clear() {
759 _finline CYString() :
766 _finline ~CYString() {
770 void operator =(const CYString &rhs) {
774 if (rhs.cache_ == nil)
777 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
780 void set(apr_pool_t *pool, const char *data, size_t size) {
786 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
787 memcpy(temp, data, size);
794 _finline void set(apr_pool_t *pool, const char *data) {
795 set(pool, data, data == NULL ? 0 : strlen(data));
798 _finline void set(apr_pool_t *pool, const std::string &rhs) {
799 set(pool, rhs.data(), rhs.size());
802 bool operator ==(const CYString &rhs) const {
803 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
806 operator CFStringRef() {
807 if (cache_ == NULL) {
810 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
812 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
816 _finline operator id() {
817 return (NSString *) static_cast<CFStringRef>(*this);
821 /* C++ NSString Algorithm Adapters {{{ */
823 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
826 struct NSStringMapHash :
827 std::unary_function<NSString *, size_t>
829 _finline size_t operator ()(NSString *value) const {
830 return CFStringHashNSString((CFStringRef) value);
834 struct NSStringMapLess :
835 std::binary_function<NSString *, NSString *, bool>
837 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
838 return [lhs compare:rhs] == NSOrderedAscending;
842 struct NSStringMapEqual :
843 std::binary_function<NSString *, NSString *, bool>
845 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
846 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
847 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
848 //[lhs isEqualToString:rhs];
853 /* Perl-Compatible RegEx {{{ */
863 Pcre(const char *regex) :
868 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
871 lprintf("%d:%s\n", offset, error);
875 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
876 matches_ = new int[(capture_ + 1) * 3];
884 NSString *operator [](size_t match) {
885 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
888 bool operator ()(NSString *data) {
889 // XXX: length is for characters, not for bytes
890 return operator ()([data UTF8String], [data length]);
893 bool operator ()(const char *data, size_t size) {
895 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
899 /* Mime Addresses {{{ */
900 @interface Address : NSObject {
906 - (NSString *) address;
908 - (void) setAddress:(NSString *)address;
910 + (Address *) addressWithString:(NSString *)string;
911 - (Address *) initWithString:(NSString *)string;
914 @implementation Address
923 - (NSString *) name {
927 - (NSString *) address {
931 - (void) setAddress:(NSString *)address {
933 [address_ autorelease];
937 address_ = [address retain];
940 + (Address *) addressWithString:(NSString *)string {
941 return [[[Address alloc] initWithString:string] autorelease];
944 + (NSArray *) _attributeKeys {
945 return [NSArray arrayWithObjects:@"address", @"name", nil];
948 - (NSArray *) attributeKeys {
949 return [[self class] _attributeKeys];
952 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
953 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
956 - (Address *) initWithString:(NSString *)string {
957 if ((self = [super init]) != nil) {
958 const char *data = [string UTF8String];
959 size_t size = [string length];
961 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
963 if (address_r(data, size)) {
964 name_ = [address_r[1] retain];
965 address_ = [address_r[2] retain];
967 name_ = [string retain];
975 /* CoreGraphics Primitives {{{ */
986 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
989 Set(space, red, green, blue, alpha);
994 CGColorRelease(color_);
1001 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1003 float color[] = {red, green, blue, alpha};
1004 color_ = CGColorCreate(space, (CGFloat *) color);
1007 operator CGColorRef() {
1013 /* Random Global Variables {{{ */
1014 static const int PulseInterval_ = 50000;
1015 static const int ButtonBarWidth_ = 60;
1016 static const int ButtonBarHeight_ = 48;
1017 static const float KeyboardTime_ = 0.3f;
1020 static NSArray *Finishes_;
1022 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1023 #define NotifyConfig_ "/etc/notify.conf"
1025 static bool Queuing_;
1027 static CYColor Blue_;
1028 static CYColor Blueish_;
1029 static CYColor Black_;
1030 static CYColor Off_;
1031 static CYColor White_;
1032 static CYColor Gray_;
1033 static CYColor Green_;
1034 static CYColor Purple_;
1035 static CYColor Purplish_;
1037 static UIColor *InstallingColor_;
1038 static UIColor *RemovingColor_;
1040 static NSString *App_;
1041 static NSString *Home_;
1043 static BOOL Advanced_;
1044 static BOOL Ignored_;
1046 static UIFont *Font12_;
1047 static UIFont *Font12Bold_;
1048 static UIFont *Font14_;
1049 static UIFont *Font18Bold_;
1050 static UIFont *Font22Bold_;
1052 static const char *Machine_ = NULL;
1053 static NSString *System_ = nil;
1054 static NSString *SerialNumber_ = nil;
1055 static NSString *ChipID_ = nil;
1056 static NSString *Token_ = nil;
1057 static NSString *UniqueID_ = nil;
1058 static NSString *Build_ = nil;
1059 static NSString *Product_ = nil;
1060 static NSString *Safari_ = nil;
1062 static CFLocaleRef Locale_;
1063 static NSArray *Languages_;
1064 static CGColorSpaceRef space_;
1066 static NSDictionary *SectionMap_;
1067 static NSMutableDictionary *Metadata_;
1068 static _transient NSMutableDictionary *Settings_;
1069 static _transient NSString *Role_;
1070 static _transient NSMutableDictionary *Packages_;
1071 static _transient NSMutableDictionary *Sections_;
1072 static _transient NSMutableDictionary *Sources_;
1073 static bool Changed_;
1074 static NSDate *now_;
1076 static bool IsWildcat_;
1079 static NSMutableArray *Documents_;
1083 /* Display Helpers {{{ */
1084 inline float Interpolate(float begin, float end, float fraction) {
1085 return (end - begin) * fraction + begin;
1088 /* XXX: localize this! */
1089 NSString *SizeString(double size) {
1090 bool negative = size < 0;
1095 while (size > 1024) {
1100 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1102 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1105 static _finline CFStringRef CFCString(const char *value) {
1106 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1109 const char *StripVersion_(const char *version) {
1110 const char *colon(strchr(version, ':'));
1112 version = colon + 1;
1116 CFStringRef StripVersion(const char *version) {
1117 const char *colon(strchr(version, ':'));
1119 version = colon + 1;
1120 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1122 return CFCString(version);
1125 NSString *LocalizeSection(NSString *section) {
1126 static Pcre title_r("^(.*?) \\((.*)\\)$");
1127 if (title_r(section)) {
1128 NSString *parent(title_r[1]);
1129 NSString *child(title_r[2]);
1131 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1132 LocalizeSection(parent),
1133 LocalizeSection(child)
1137 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1140 NSString *Simplify(NSString *title) {
1141 const char *data = [title UTF8String];
1142 size_t size = [title length];
1144 static Pcre square_r("^\\[(.*)\\]$");
1145 if (square_r(data, size))
1146 return Simplify(square_r[1]);
1148 static Pcre paren_r("^\\((.*)\\)$");
1149 if (paren_r(data, size))
1150 return Simplify(paren_r[1]);
1152 static Pcre title_r("^(.*?) \\((.*)\\)$");
1153 if (title_r(data, size))
1154 return Simplify(title_r[1]);
1160 NSString *GetLastUpdate() {
1161 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1164 return UCLocalize("NEVER_OR_UNKNOWN");
1166 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1167 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1169 CFRelease(formatter);
1171 return [(NSString *) formatted autorelease];
1174 bool isSectionVisible(NSString *section) {
1175 NSDictionary *metadata([Sections_ objectForKey:section]);
1176 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1177 return hidden == nil || ![hidden boolValue];
1182 /* Delegate Prototypes {{{ */
1186 @interface NSObject (ProgressDelegate)
1189 @protocol ProgressDelegate
1190 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1191 - (void) setProgressTitle:(NSString *)title;
1192 - (void) setProgressPercent:(float)percent;
1193 - (void) startProgress;
1194 - (void) addProgressOutput:(NSString *)output;
1195 - (bool) isCancelling:(size_t)received;
1198 @protocol ConfigurationDelegate
1199 - (void) repairWithSelector:(SEL)selector;
1200 - (void) setConfigurationData:(NSString *)data;
1203 @class PackageController;
1205 @protocol CydiaDelegate
1206 - (void) setPackageController:(PackageController *)view;
1207 - (void) clearPackage:(Package *)package;
1208 - (void) installPackage:(Package *)package;
1209 - (void) installPackages:(NSArray *)packages;
1210 - (void) removePackage:(Package *)package;
1211 - (void) beginUpdate;
1213 - (void) distUpgrade;
1215 - (void) updateData;
1217 - (void) showSettings;
1218 - (UIProgressHUD *) addProgressHUD;
1219 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1220 - (CYViewController *) pageForPackage:(NSString *)name;
1221 - (PackageController *) packageController;
1222 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1226 /* Status Delegation {{{ */
1228 public pkgAcquireStatus
1231 _transient NSObject<ProgressDelegate> *delegate_;
1239 void setDelegate(id delegate) {
1240 delegate_ = delegate;
1243 NSObject<ProgressDelegate> *getDelegate() const {
1247 virtual bool MediaChange(std::string media, std::string drive) {
1251 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1254 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1255 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1256 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1259 virtual void Done(pkgAcquire::ItemDesc &item) {
1262 virtual void Fail(pkgAcquire::ItemDesc &item) {
1264 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1265 item.Owner->Status == pkgAcquire::Item::StatDone
1269 std::string &error(item.Owner->ErrorText);
1273 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1274 NSArray *fields([description componentsSeparatedByString:@" "]);
1275 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1277 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1278 withObject:[NSArray arrayWithObjects:
1279 [NSString stringWithUTF8String:error.c_str()],
1286 virtual bool Pulse(pkgAcquire *Owner) {
1287 bool value = pkgAcquireStatus::Pulse(Owner);
1290 double(CurrentBytes + CurrentItems) /
1291 double(TotalBytes + TotalItems)
1294 [delegate_ setProgressPercent:percent];
1295 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1298 virtual void Start() {
1299 [delegate_ startProgress];
1302 virtual void Stop() {
1306 /* Progress Delegation {{{ */
1311 _transient id<ProgressDelegate> delegate_;
1315 virtual void Update() {
1316 /*if (abs(Percent - percent_) > 2)
1317 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1321 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1322 [delegate_ setProgressPercent:(Percent / 100)];*/
1332 void setDelegate(id delegate) {
1333 delegate_ = delegate;
1336 id getDelegate() const {
1340 virtual void Done() {
1342 //[delegate_ setProgressPercent:1];
1347 /* Database Interface {{{ */
1348 typedef std::map< unsigned long, _H<Source> > SourceMap;
1350 @interface Database : NSObject {
1356 pkgCacheFile cache_;
1357 pkgDepCache::Policy *policy_;
1358 pkgRecords *records_;
1359 pkgProblemResolver *resolver_;
1360 pkgAcquire *fetcher_;
1362 SPtr<pkgPackageManager> manager_;
1363 pkgSourceList *list_;
1366 NSMutableArray *packages_;
1368 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1377 + (Database *) sharedInstance;
1380 - (void) _readCydia:(NSNumber *)fd;
1381 - (void) _readStatus:(NSNumber *)fd;
1382 - (void) _readOutput:(NSNumber *)fd;
1386 - (Package *) packageWithName:(NSString *)name;
1388 - (pkgCacheFile &) cache;
1389 - (pkgDepCache::Policy *) policy;
1390 - (pkgRecords *) records;
1391 - (pkgProblemResolver *) resolver;
1392 - (pkgAcquire &) fetcher;
1393 - (pkgSourceList &) list;
1394 - (NSArray *) packages;
1395 - (NSArray *) sources;
1396 - (void) reloadData;
1404 - (void) setVisible;
1406 - (void) updateWithStatus:(Status &)status;
1408 - (void) setDelegate:(id)delegate;
1409 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1412 /* Delegate Helpers {{{ */
1413 @implementation NSObject (ProgressDelegate)
1415 - (void) _setProgressErrorPackage:(NSArray *)args {
1416 [self performSelector:@selector(setProgressError:forPackage:)
1417 withObject:[args objectAtIndex:0]
1418 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1422 - (void) _setProgressErrorTitle:(NSArray *)args {
1423 [self performSelector:@selector(setProgressError:withTitle:)
1424 withObject:[args objectAtIndex:0]
1425 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1429 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1430 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1431 withObject:[NSArray arrayWithObjects:error, title, nil]
1436 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1437 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1439 [self performSelector:@selector(setProgressError:withTitle:)
1441 withObject:(package == nil ? id : [package name])
1448 /* Source Class {{{ */
1449 @interface Source : NSObject {
1450 CYString depiction_;
1451 CYString description_;
1457 CYString distribution_;
1462 NSString *authority_;
1464 CYString defaultIcon_;
1466 NSDictionary *record_;
1470 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1472 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1474 - (NSString *) depictionForPackage:(NSString *)package;
1475 - (NSString *) supportForPackage:(NSString *)package;
1477 - (NSDictionary *) record;
1481 - (NSString *) distribution;
1482 - (NSString *) type;
1484 - (NSString *) host;
1486 - (NSString *) name;
1487 - (NSString *) description;
1488 - (NSString *) label;
1489 - (NSString *) origin;
1490 - (NSString *) version;
1492 - (NSString *) defaultIcon;
1496 @implementation Source
1500 distribution_.clear();
1503 description_.clear();
1509 defaultIcon_.clear();
1511 if (record_ != nil) {
1521 if (authority_ != nil) {
1522 [authority_ release];
1532 + (NSArray *) _attributeKeys {
1533 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1536 - (NSArray *) attributeKeys {
1537 return [[self class] _attributeKeys];
1540 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1541 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1544 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1547 trusted_ = index->IsTrusted();
1549 uri_.set(pool, index->GetURI());
1550 distribution_.set(pool, index->GetDist());
1551 type_.set(pool, index->GetType());
1553 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1554 if (dindex != NULL) {
1556 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1559 pkgTagFile tags(&fd);
1561 pkgTagSection section;
1568 {"default-icon", &defaultIcon_},
1569 {"depiction", &depiction_},
1570 {"description", &description_},
1572 {"origin", &origin_},
1573 {"support", &support_},
1574 {"version", &version_},
1577 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1578 const char *start, *end;
1580 if (section.Find(names[i].name_, start, end)) {
1581 CYString &value(*names[i].value_);
1582 value.set(pool, start, end - start);
1588 record_ = [Sources_ objectForKey:[self key]];
1590 record_ = [record_ retain];
1592 NSURL *url([NSURL URLWithString:uri_]);
1596 host_ = [[host_ lowercaseString] retain];
1601 authority_ = [url path];
1603 if (authority_ != nil)
1604 authority_ = [authority_ retain];
1607 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1608 if ((self = [super init]) != nil) {
1609 [self setMetaIndex:index inPool:pool];
1613 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1614 NSDictionary *lhr = [self record];
1615 NSDictionary *rhr = [source record];
1618 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1620 NSString *lhs = [self name];
1621 NSString *rhs = [source name];
1623 if ([lhs length] != 0 && [rhs length] != 0) {
1624 unichar lhc = [lhs characterAtIndex:0];
1625 unichar rhc = [rhs characterAtIndex:0];
1627 if (isalpha(lhc) && !isalpha(rhc))
1628 return NSOrderedAscending;
1629 else if (!isalpha(lhc) && isalpha(rhc))
1630 return NSOrderedDescending;
1633 return [lhs compare:rhs options:LaxCompareOptions_];
1636 - (NSString *) depictionForPackage:(NSString *)package {
1637 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1640 - (NSString *) supportForPackage:(NSString *)package {
1641 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1644 - (NSDictionary *) record {
1652 - (NSString *) uri {
1656 - (NSString *) distribution {
1657 return distribution_;
1660 - (NSString *) type {
1664 - (NSString *) key {
1665 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1668 - (NSString *) host {
1672 - (NSString *) name {
1673 return origin_.empty() ? authority_ : origin_;
1676 - (NSString *) description {
1677 return description_;
1680 - (NSString *) label {
1681 return label_.empty() ? authority_ : label_;
1684 - (NSString *) origin {
1688 - (NSString *) version {
1692 - (NSString *) defaultIcon {
1693 return defaultIcon_;
1698 /* Relationship Class {{{ */
1699 @interface Relationship : NSObject {
1704 - (NSString *) type;
1706 - (NSString *) name;
1710 @implementation Relationship
1718 - (NSString *) type {
1726 - (NSString *) name {
1733 /* Package Class {{{ */
1734 @interface Package : NSObject {
1738 pkgCache::VerIterator version_;
1739 pkgCache::PkgIterator iterator_;
1740 _transient Database *database_;
1741 pkgCache::VerFileIterator file_;
1748 NSString *section$_;
1755 CYString installed_;
1761 CYString depiction_;
1772 NSMutableArray *tags_;
1775 NSArray *relationships_;
1777 NSMutableDictionary *metadata_;
1778 _transient NSDate *firstSeen_;
1779 _transient NSDate *lastSeen_;
1783 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1784 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1786 - (pkgCache::PkgIterator) iterator;
1789 - (NSString *) section;
1790 - (NSString *) simpleSection;
1792 - (NSString *) longSection;
1793 - (NSString *) shortSection;
1797 - (Address *) maintainer;
1799 - (NSString *) longDescription;
1800 - (NSString *) shortDescription;
1803 - (NSMutableDictionary *) metadata;
1805 - (BOOL) subscribed;
1808 - (NSString *) latest;
1809 - (NSString *) installed;
1810 - (BOOL) uninstalled;
1813 - (BOOL) upgradableAndEssential:(BOOL)essential;
1816 - (BOOL) unfiltered;
1820 - (BOOL) halfConfigured;
1821 - (BOOL) halfInstalled;
1823 - (NSString *) mode;
1825 - (void) setVisible;
1828 - (NSString *) name;
1830 - (NSString *) homepage;
1831 - (NSString *) depiction;
1832 - (Address *) author;
1834 - (NSString *) support;
1836 - (NSArray *) files;
1837 - (NSArray *) relationships;
1838 - (NSArray *) warnings;
1839 - (NSArray *) applications;
1841 - (Source *) source;
1842 - (NSString *) role;
1844 - (BOOL) matches:(NSString *)text;
1846 - (bool) hasSupportingRole;
1847 - (BOOL) hasTag:(NSString *)tag;
1848 - (NSString *) primaryPurpose;
1849 - (NSArray *) purposes;
1850 - (bool) isCommercial;
1852 - (CYString &) cyname;
1854 - (uint32_t) compareBySection:(NSArray *)sections;
1856 - (uint32_t) compareForChanges;
1861 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1862 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1863 - (bool) isInstalledAndVisible:(NSNumber *)number;
1864 - (bool) isVisibleInSection:(NSString *)section;
1865 - (bool) isVisibleInSource:(Source *)source;
1869 uint32_t PackageChangesRadix(Package *self, void *) {
1874 uint32_t timestamp : 30;
1875 uint32_t ignored : 1;
1876 uint32_t upgradable : 1;
1880 bool upgradable([self upgradableAndEssential:YES]);
1881 value.bits.upgradable = upgradable ? 1 : 0;
1884 value.bits.timestamp = 0;
1885 value.bits.ignored = [self ignored] ? 0 : 1;
1886 value.bits.upgradable = 1;
1888 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1889 value.bits.ignored = 0;
1890 value.bits.upgradable = 0;
1893 return _not(uint32_t) - value.key;
1896 _finline static void Stifle(uint8_t &value) {
1899 uint32_t PackagePrefixRadix(Package *self, void *context) {
1900 size_t offset(reinterpret_cast<size_t>(context));
1901 CYString &name([self cyname]);
1903 size_t size(name.size());
1906 char *text(name.data());
1909 if (!isdigit(text[0]))
1913 while (size != digits && isdigit(text[digits]))
1923 if (offset == 0 && zeros != 0) {
1924 memset(data, '0', zeros);
1925 memcpy(data + zeros, text, 4 - zeros);
1927 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1928 if (size <= offset - zeros)
1931 text += offset - zeros;
1932 size -= offset - zeros;
1935 memcpy(data, text, 4);
1937 memcpy(data, text, size);
1938 memset(data + size, 0, 4 - size);
1941 for (size_t i(0); i != 4; ++i)
1942 if (isalpha(data[i]))
1947 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1949 /* XXX: ntohl may be more honest */
1950 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1953 CYString &(*PackageName)(Package *self, SEL sel);
1955 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1956 _profile(PackageNameCompare)
1957 CYString &lhi(PackageName(lhs, @selector(cyname)));
1958 CYString &rhi(PackageName(rhs, @selector(cyname)));
1959 CFStringRef lhn(lhi), rhn(rhi);
1962 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1963 else if (rhn == NULL)
1964 return NSOrderedDescending;
1966 _profile(PackageNameCompare$NumbersLast)
1967 if (!lhi.empty() && !rhi.empty()) {
1968 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1969 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1970 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1971 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1972 return lha ? NSOrderedAscending : NSOrderedDescending;
1976 CFIndex length = CFStringGetLength(lhn);
1978 _profile(PackageNameCompare$Compare)
1979 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1984 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1985 return PackageNameCompare(*lhs, *rhs, context);
1988 struct PackageNameOrdering :
1989 std::binary_function<Package *, Package *, bool>
1991 _finline bool operator ()(Package *lhs, Package *rhs) const {
1992 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1996 @implementation Package
1998 - (NSString *) description {
1999 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2005 if (section$_ != nil)
2006 [section$_ release];
2011 if (sponsor$_ != nil)
2012 [sponsor$_ release];
2013 if (author$_ != nil)
2020 if (relationships_ != nil)
2021 [relationships_ release];
2022 if (metadata_ != nil)
2023 [metadata_ release];
2028 + (NSString *) webScriptNameForSelector:(SEL)selector {
2029 if (selector == @selector(hasTag:))
2035 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2036 return [self webScriptNameForSelector:selector] == nil;
2039 + (NSArray *) _attributeKeys {
2040 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];
2043 - (NSArray *) attributeKeys {
2044 return [[self class] _attributeKeys];
2047 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2048 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2058 _profile(Package$parse)
2059 pkgRecords::Parser *parser;
2061 _profile(Package$parse$Lookup)
2062 parser = &[database_ records]->Lookup(file_);
2067 _profile(Package$parse$Find)
2073 {"depiction", &depiction_},
2074 {"homepage", &homepage_},
2075 {"website", &website},
2077 {"support", &support_},
2078 {"sponsor", &sponsor_},
2079 {"author", &author_},
2082 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2083 const char *start, *end;
2085 if (parser->Find(names[i].name_, start, end)) {
2086 CYString &value(*names[i].value_);
2087 _profile(Package$parse$Value)
2088 value.set(pool_, start, end - start);
2094 _profile(Package$parse$Tagline)
2095 const char *start, *end;
2096 if (parser->ShortDesc(start, end)) {
2097 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2100 while (stop != start && stop[-1] == '\r')
2102 tagline_.set(pool_, start, stop - start);
2106 _profile(Package$parse$Retain)
2107 if (homepage_.empty())
2108 homepage_ = website;
2109 if (homepage_ == depiction_)
2115 - (void) setVisible {
2116 visible_ = required_ && [self unfiltered];
2119 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2120 if ((self = [super init]) != nil) {
2121 _profile(Package$initWithVersion)
2122 @synchronized (database) {
2123 era_ = [database era];
2127 iterator_ = version.ParentPkg();
2128 database_ = database;
2130 _profile(Package$initWithVersion$Latest)
2131 latest_ = (NSString *) StripVersion(version_.VerStr());
2134 pkgCache::VerIterator current;
2135 _profile(Package$initWithVersion$Versions)
2136 current = iterator_.CurrentVer();
2138 installed_.set(pool_, StripVersion_(current.VerStr()));
2140 if (!version_.end())
2141 file_ = version_.FileList();
2143 pkgCache &cache([database_ cache]);
2144 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2148 _profile(Package$initWithVersion$Name)
2149 id_.set(pool_, iterator_.Name());
2150 name_.set(pool, iterator_.Display());
2154 _profile(Package$initWithVersion$Source)
2155 source_ = [database_ getSource:file_.File()];
2164 _profile(Package$initWithVersion$Tags)
2165 pkgCache::TagIterator tag(iterator_.TagList());
2167 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2169 const char *name(tag.Name());
2170 [tags_ addObject:(NSString *)CFCString(name)];
2171 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2172 role_ = (NSString *) CFCString(name + 6);
2173 if (required_ && strncmp(name, "require::", 9) == 0 && (
2178 } while (!tag.end());
2182 bool changed(false);
2183 NSString *key([id_ lowercaseString]);
2185 _profile(Package$initWithVersion$Metadata)
2186 metadata_ = [Packages_ objectForKey:key];
2188 if (metadata_ == nil) {
2191 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2192 firstSeen_, @"FirstSeen",
2193 latest_, @"LastVersion",
2198 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2199 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2201 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2202 subscribed_ = [subscribed boolValue];
2204 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2206 if (firstSeen_ == nil) {
2207 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2208 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2212 if (version == nil) {
2213 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2215 } else if (![version isEqualToString:latest_]) {
2216 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2218 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2223 metadata_ = [metadata_ retain];
2226 [Packages_ setObject:metadata_ forKey:key];
2231 _profile(Package$initWithVersion$Section)
2232 section_.set(pool_, iterator_.Section());
2235 obsolete_ = [self hasTag:@"cydia::obsolete"];
2236 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2238 } _end } return self;
2241 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2242 @synchronized ([Database class]) {
2243 pkgCache::VerIterator version;
2245 _profile(Package$packageWithIterator$GetCandidateVer)
2246 version = [database policy]->GetCandidateVer(iterator);
2252 return [[[Package alloc]
2253 initWithVersion:version
2260 - (pkgCache::PkgIterator) iterator {
2264 - (NSString *) section {
2265 if (section$_ == nil) {
2266 if (section_.empty())
2269 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2270 NSString *name(section_);
2273 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2274 if (NSString *rename = [value objectForKey:@"Rename"]) {
2279 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2283 - (NSString *) simpleSection {
2284 if (NSString *section = [self section])
2285 return Simplify(section);
2290 - (NSString *) longSection {
2291 return LocalizeSection([self section]);
2294 - (NSString *) shortSection {
2295 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2298 - (NSString *) uri {
2301 pkgIndexFile *index;
2302 pkgCache::PkgFileIterator file(file_.File());
2303 if (![database_ list].FindIndex(file, index))
2305 return [NSString stringWithUTF8String:iterator_->Path];
2306 //return [NSString stringWithUTF8String:file.Site()];
2307 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2311 - (Address *) maintainer {
2314 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2315 const std::string &maintainer(parser->Maintainer());
2316 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2320 return version_.end() ? 0 : version_->InstalledSize;
2323 - (NSString *) longDescription {
2326 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2327 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2329 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2330 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2331 if ([lines count] < 2)
2334 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2335 for (size_t i(1), e([lines count]); i != e; ++i) {
2336 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2337 [trimmed addObject:trim];
2340 return [trimmed componentsJoinedByString:@"\n"];
2343 - (NSString *) shortDescription {
2348 _profile(Package$index)
2349 CFStringRef name((CFStringRef) [self name]);
2350 if (CFStringGetLength(name) == 0)
2352 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2353 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2355 return toupper(character);
2359 - (NSMutableDictionary *) metadata {
2364 if (subscribed_ && lastSeen_ != nil)
2369 - (BOOL) subscribed {
2374 NSDictionary *metadata([self metadata]);
2375 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2376 return [ignored boolValue];
2381 - (NSString *) latest {
2385 - (NSString *) installed {
2389 - (BOOL) uninstalled {
2390 return installed_.empty();
2394 return !version_.end();
2397 - (BOOL) upgradableAndEssential:(BOOL)essential {
2398 _profile(Package$upgradableAndEssential)
2399 pkgCache::VerIterator current(iterator_.CurrentVer());
2401 return essential && essential_ && visible_;
2403 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2407 - (BOOL) essential {
2412 return [database_ cache][iterator_].InstBroken();
2415 - (BOOL) unfiltered {
2416 NSString *section([self section]);
2417 return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
2425 unsigned char current(iterator_->CurrentState);
2426 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2429 - (BOOL) halfConfigured {
2430 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2433 - (BOOL) halfInstalled {
2434 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2438 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2439 return state.Mode != pkgDepCache::ModeKeep;
2442 - (NSString *) mode {
2443 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2445 switch (state.Mode) {
2446 case pkgDepCache::ModeDelete:
2447 if ((state.iFlags & pkgDepCache::Purge) != 0)
2451 case pkgDepCache::ModeKeep:
2452 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2453 return @"REINSTALL";
2454 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2458 case pkgDepCache::ModeInstall:
2459 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2460 return @"REINSTALL";
2461 else*/ switch (state.Status) {
2463 return @"DOWNGRADE";
2469 return @"NEW_INSTALL";
2480 - (NSString *) name {
2481 return name_.empty() ? id_ : name_;
2484 - (UIImage *) icon {
2485 NSString *section = [self simpleSection];
2489 if ([icon_ hasPrefix:@"file:///"])
2490 // XXX: correct escaping
2491 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2492 if (icon == nil) if (section != nil)
2493 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2494 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2495 if ([dicon hasPrefix:@"file:///"])
2496 // XXX: correct escaping
2497 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2499 icon = [UIImage applicationImageNamed:@"unknown.png"];
2503 - (NSString *) homepage {
2507 - (NSString *) depiction {
2508 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2511 - (Address *) sponsor {
2512 if (sponsor$_ == nil) {
2513 if (sponsor_.empty())
2515 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2519 - (Address *) author {
2520 if (author$_ == nil) {
2521 if (author_.empty())
2523 author$_ = [[Address addressWithString:author_] retain];
2527 - (NSString *) support {
2528 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2531 - (NSArray *) files {
2532 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2533 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2536 fin.open([path UTF8String]);
2541 while (std::getline(fin, line))
2542 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2547 - (NSArray *) relationships {
2548 return relationships_;
2551 - (NSArray *) warnings {
2552 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2553 const char *name(iterator_.Name());
2555 size_t length(strlen(name));
2556 if (length < 2) invalid:
2557 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2558 else for (size_t i(0); i != length; ++i)
2560 /* XXX: technically this is not allowed */
2561 (name[i] < 'A' || name[i] > 'Z') &&
2562 (name[i] < 'a' || name[i] > 'z') &&
2563 (name[i] < '0' || name[i] > '9') &&
2564 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2567 if (strcmp(name, "cydia") != 0) {
2570 bool _private = false;
2573 bool repository = [[self section] isEqualToString:@"Repositories"];
2575 if (NSArray *files = [self files])
2576 for (NSString *file in files)
2577 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2579 else if (!user && [file isEqualToString:@"/User"])
2581 else if (!_private && [file isEqualToString:@"/private"])
2583 else if (!stash && [file isEqualToString:@"/var/stash"])
2586 /* XXX: this is not sensitive enough. only some folders are valid. */
2587 if (cydia && !repository)
2588 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2590 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2592 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2594 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2597 return [warnings count] == 0 ? nil : warnings;
2600 - (NSArray *) applications {
2601 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2603 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2605 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2606 if (NSArray *files = [self files])
2607 for (NSString *file in files)
2608 if (application_r(file)) {
2609 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2610 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2611 if ([id isEqualToString:me])
2614 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2616 display = application_r[1];
2618 NSString *bundle([file stringByDeletingLastPathComponent]);
2619 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2620 if (icon == nil || [icon length] == 0)
2622 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2624 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2625 [applications addObject:application];
2627 [application addObject:id];
2628 [application addObject:display];
2629 [application addObject:url];
2632 return [applications count] == 0 ? nil : applications;
2635 - (Source *) source {
2637 @synchronized (database_) {
2638 if ([database_ era] != era_ || file_.end())
2641 source_ = [database_ getSource:file_.File()];
2653 - (NSString *) role {
2657 - (BOOL) matches:(NSString *)text {
2663 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2664 if (range.location != NSNotFound)
2667 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2668 if (range.location != NSNotFound)
2671 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2672 if (range.location != NSNotFound)
2678 - (bool) hasSupportingRole {
2681 if ([role_ isEqualToString:@"enduser"])
2683 if ([Role_ isEqualToString:@"User"])
2685 if ([role_ isEqualToString:@"hacker"])
2687 if ([Role_ isEqualToString:@"Hacker"])
2689 if ([role_ isEqualToString:@"developer"])
2691 if ([Role_ isEqualToString:@"Developer"])
2696 - (BOOL) hasTag:(NSString *)tag {
2697 return tags_ == nil ? NO : [tags_ containsObject:tag];
2700 - (NSString *) primaryPurpose {
2701 for (NSString *tag in tags_)
2702 if ([tag hasPrefix:@"purpose::"])
2703 return [tag substringFromIndex:9];
2707 - (NSArray *) purposes {
2708 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2709 for (NSString *tag in tags_)
2710 if ([tag hasPrefix:@"purpose::"])
2711 [purposes addObject:[tag substringFromIndex:9]];
2712 return [purposes count] == 0 ? nil : purposes;
2715 - (bool) isCommercial {
2716 return [self hasTag:@"cydia::commercial"];
2719 - (CYString &) cyname {
2720 return name_.empty() ? id_ : name_;
2723 - (uint32_t) compareBySection:(NSArray *)sections {
2724 NSString *section([self section]);
2725 for (size_t i(0), e([sections count]); i != e; ++i) {
2726 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2730 return _not(uint32_t);
2733 - (uint32_t) compareForChanges {
2738 uint32_t timestamp : 30;
2739 uint32_t ignored : 1;
2740 uint32_t upgradable : 1;
2744 bool upgradable([self upgradableAndEssential:YES]);
2745 value.bits.upgradable = upgradable ? 1 : 0;
2748 value.bits.timestamp = 0;
2749 value.bits.ignored = [self ignored] ? 0 : 1;
2750 value.bits.upgradable = 1;
2752 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2753 value.bits.ignored = 0;
2754 value.bits.upgradable = 0;
2757 return _not(uint32_t) - value.key;
2761 pkgProblemResolver *resolver = [database_ resolver];
2762 resolver->Clear(iterator_);
2763 resolver->Protect(iterator_);
2767 pkgProblemResolver *resolver = [database_ resolver];
2768 resolver->Clear(iterator_);
2769 resolver->Protect(iterator_);
2770 pkgCacheFile &cache([database_ cache]);
2771 cache->MarkInstall(iterator_, false);
2772 pkgDepCache::StateCache &state((*cache)[iterator_]);
2773 if (!state.Install())
2774 cache->SetReInstall(iterator_, true);
2778 pkgProblemResolver *resolver = [database_ resolver];
2779 resolver->Clear(iterator_);
2780 resolver->Protect(iterator_);
2781 resolver->Remove(iterator_);
2782 [database_ cache]->MarkDelete(iterator_, true);
2785 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2786 _profile(Package$isUnfilteredAndSearchedForBy)
2789 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2790 value &= [self unfiltered];
2793 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2794 value &= [self matches:search];
2801 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2802 if ([search length] == 0)
2805 _profile(Package$isUnfilteredAndSelectedForBy)
2808 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2809 value &= [self unfiltered];
2812 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2813 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2820 - (bool) isInstalledAndVisible:(NSNumber *)number {
2821 return (![number boolValue] || [self visible]) && ![self uninstalled];
2824 - (bool) isVisibleInSection:(NSString *)name {
2825 NSString *section = [self section];
2830 section == nil && [name length] == 0 ||
2831 [name isEqualToString:section]
2835 - (bool) isVisibleInSource:(Source *)source {
2836 return [self source] == source && [self visible];
2841 /* Section Class {{{ */
2842 @interface Section : NSObject {
2847 NSString *localized_;
2850 - (NSComparisonResult) compareByLocalized:(Section *)section;
2851 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2852 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2853 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2854 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2855 - (NSString *) name;
2862 - (void) addToCount;
2864 - (void) setCount:(size_t)count;
2865 - (NSString *) localized;
2869 @implementation Section
2873 if (localized_ != nil)
2874 [localized_ release];
2878 - (NSComparisonResult) compareByLocalized:(Section *)section {
2879 NSString *lhs(localized_);
2880 NSString *rhs([section localized]);
2882 /*if ([lhs length] != 0 && [rhs length] != 0) {
2883 unichar lhc = [lhs characterAtIndex:0];
2884 unichar rhc = [rhs characterAtIndex:0];
2886 if (isalpha(lhc) && !isalpha(rhc))
2887 return NSOrderedAscending;
2888 else if (!isalpha(lhc) && isalpha(rhc))
2889 return NSOrderedDescending;
2892 return [lhs compare:rhs options:LaxCompareOptions_];
2895 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2896 if ((self = [self initWithName:name localize:NO]) != nil) {
2897 if (localized != nil)
2898 localized_ = [localized retain];
2902 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2903 return [self initWithName:name row:0 localize:localize];
2906 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2907 if ((self = [super init]) != nil) {
2908 name_ = [name retain];
2912 localized_ = [LocalizeSection(name_) retain];
2916 /* XXX: localize the index thingees */
2917 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2918 if ((self = [super init]) != nil) {
2919 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2925 - (NSString *) name {
2945 - (void) addToCount {
2949 - (void) setCount:(size_t)count {
2953 - (NSString *) localized {
2960 static NSString *Colon_;
2961 static NSString *Error_;
2962 static NSString *Warning_;
2964 /* Database Implementation {{{ */
2965 @implementation Database
2967 + (Database *) sharedInstance {
2968 static Database *instance;
2969 if (instance == nil)
2970 instance = [[Database alloc] init];
2980 NSRecycleZone(zone_);
2981 // XXX: malloc_destroy_zone(zone_);
2982 apr_pool_destroy(pool_);
2986 - (void) _readCydia:(NSNumber *)fd { _pooled
2987 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2988 std::istream is(&ib);
2991 static Pcre finish_r("^finish:([^:]*)$");
2993 while (std::getline(is, line)) {
2994 const char *data(line.c_str());
2995 size_t size = line.size();
2996 lprintf("C:%s\n", data);
2998 if (finish_r(data, size)) {
2999 NSString *finish = finish_r[1];
3000 int index = [Finishes_ indexOfObject:finish];
3001 if (index != INT_MAX && index > Finish_)
3009 - (void) _readStatus:(NSNumber *)fd { _pooled
3010 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3011 std::istream is(&ib);
3014 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3015 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3017 while (std::getline(is, line)) {
3018 const char *data(line.c_str());
3019 size_t size(line.size());
3020 lprintf("S:%s\n", data);
3022 if (conffile_r(data, size)) {
3023 [delegate_ setConfigurationData:conffile_r[1]];
3024 } else if (strncmp(data, "status: ", 8) == 0) {
3025 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3026 [delegate_ setProgressTitle:string];
3027 } else if (pmstatus_r(data, size)) {
3028 std::string type([pmstatus_r[1] UTF8String]);
3029 NSString *id = pmstatus_r[2];
3031 float percent([pmstatus_r[3] floatValue]);
3032 [delegate_ setProgressPercent:(percent / 100)];
3034 NSString *string = pmstatus_r[4];
3036 if (type == "pmerror")
3037 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3038 withObject:[NSArray arrayWithObjects:string, id, nil]
3041 else if (type == "pmstatus") {
3042 [delegate_ setProgressTitle:string];
3043 } else if (type == "pmconffile")
3044 [delegate_ setConfigurationData:string];
3046 lprintf("E:unknown pmstatus\n");
3048 lprintf("E:unknown status\n");
3054 - (void) _readOutput:(NSNumber *)fd { _pooled
3055 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3056 std::istream is(&ib);
3059 while (std::getline(is, line)) {
3060 lprintf("O:%s\n", line.c_str());
3061 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3071 - (Package *) packageWithName:(NSString *)name {
3072 @synchronized ([Database class]) {
3073 if (static_cast<pkgDepCache *>(cache_) == NULL)
3075 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3076 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3080 if ((self = [super init]) != nil) {
3087 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3088 apr_pool_create(&pool_, NULL);
3090 packages_ = [[NSMutableArray alloc] init];
3094 _assert(pipe(fds) != -1);
3097 _config->Set("APT::Keep-Fds::", cydiafd_);
3098 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3101 detachNewThreadSelector:@selector(_readCydia:)
3103 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3106 _assert(pipe(fds) != -1);
3110 detachNewThreadSelector:@selector(_readStatus:)
3112 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3115 _assert(pipe(fds) != -1);
3116 _assert(dup2(fds[0], 0) != -1);
3117 _assert(close(fds[0]) != -1);
3119 input_ = fdopen(fds[1], "a");
3121 _assert(pipe(fds) != -1);
3122 _assert(dup2(fds[1], 1) != -1);
3123 _assert(close(fds[1]) != -1);
3126 detachNewThreadSelector:@selector(_readOutput:)
3128 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3133 - (pkgCacheFile &) cache {
3137 - (pkgDepCache::Policy *) policy {
3141 - (pkgRecords *) records {
3145 - (pkgProblemResolver *) resolver {
3149 - (pkgAcquire &) fetcher {
3153 - (pkgSourceList &) list {
3157 - (NSArray *) packages {
3161 - (NSArray *) sources {
3162 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3163 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3164 [sources addObject:i->second];
3168 - (NSArray *) issues {
3169 if (cache_->BrokenCount() == 0)
3172 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3174 for (Package *package in packages_) {
3175 if (![package broken])
3177 pkgCache::PkgIterator pkg([package iterator]);
3179 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3180 [entry addObject:[package name]];
3181 [issues addObject:entry];
3183 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3187 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3188 pkgCache::DepIterator start;
3189 pkgCache::DepIterator end;
3190 dep.GlobOr(start, end); // ++dep
3192 if (!cache_->IsImportantDep(end))
3194 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3197 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3198 [entry addObject:failure];
3199 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3201 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3202 if (Package *package = [self packageWithName:name])
3203 name = [package name];
3204 [failure addObject:name];
3206 pkgCache::PkgIterator target(start.TargetPkg());
3207 if (target->ProvidesList != 0)
3208 [failure addObject:@"?"];
3210 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3212 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3213 else if (!cache_[target].CandidateVerIter(cache_).end())
3214 [failure addObject:@"-"];
3215 else if (target->ProvidesList == 0)
3216 [failure addObject:@"!"];
3218 [failure addObject:@"%"];
3222 if (start.TargetVer() != 0)
3223 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3234 - (bool) popErrorWithTitle:(NSString *)title {
3236 std::string message;
3238 while (!_error->empty()) {
3240 bool warning(!_error->PopMessage(error));
3244 size_t size(error.size());
3245 if (size == 0 || error[size - 1] != '\n')
3247 error.resize(size - 1);
3249 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3251 if (!message.empty())
3256 if (fatal && !message.empty())
3257 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3262 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3263 return [self popErrorWithTitle:title] || !success;
3266 - (void) reloadData { _pooled
3267 @synchronized ([Database class]) {
3268 @synchronized (self) {
3272 [packages_ removeAllObjects];
3298 apr_pool_clear(pool_);
3299 NSRecycleZone(zone_);
3301 int chk(creat("/tmp/cydia.chk", 0644));
3305 NSString *title(UCLocalize("DATABASE"));
3308 if (!cache_.Open(progress_, true)) { pop:
3310 bool warning(!_error->PopMessage(error));
3311 lprintf("cache_.Open():[%s]\n", error.c_str());
3313 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3314 [delegate_ repairWithSelector:@selector(configure)];
3315 else if (error == "The package lists or status file could not be parsed or opened.")
3316 [delegate_ repairWithSelector:@selector(update)];
3317 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3318 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3319 // else if (error == "The list of sources could not be read.")
3321 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3330 unlink("/tmp/cydia.chk");
3332 now_ = [[NSDate date] retain];
3334 policy_ = new pkgDepCache::Policy();
3335 records_ = new pkgRecords(cache_);
3336 resolver_ = new pkgProblemResolver(cache_);
3337 fetcher_ = new pkgAcquire(&status_);
3340 list_ = new pkgSourceList();
3341 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3344 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3345 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3349 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3352 if (cache_->BrokenCount() != 0) {
3353 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3356 if (cache_->BrokenCount() != 0) {
3357 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3361 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3367 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3368 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3369 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3370 // XXX: this could be more intelligent
3371 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3372 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3374 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3381 /*std::vector<Package *> packages;
3382 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3383 [packages_ release];
3388 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3389 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3390 //packages.push_back(package);
3391 [packages_ addObject:package];
3395 /*if (packages.empty())
3396 packages_ = [[NSArray alloc] init];
3398 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3401 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3402 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3403 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3411 /*if (!packages.empty())
3412 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3413 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3415 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3417 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3419 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3425 - (void) configure {
3426 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3427 system([dpkg UTF8String]);
3431 // XXX: I don't remember this condition
3436 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3438 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3440 if ([self popErrorWithTitle:title])
3444 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3447 public pkgArchiveCleaner
3450 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3455 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3462 fetcher_->Shutdown();
3464 pkgRecords records(cache_);
3466 lock_ = new FileFd();
3467 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3469 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3471 if ([self popErrorWithTitle:title])
3475 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3478 manager_ = (_system->CreatePM(cache_));
3479 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3486 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3488 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3490 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3492 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3493 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3496 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3501 bool failed = false;
3502 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3503 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3505 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3508 std::string uri = (*item)->DescURI();
3509 std::string error = (*item)->ErrorText;
3511 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3514 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3515 withObject:[NSArray arrayWithObjects:
3516 [NSString stringWithUTF8String:error.c_str()],
3528 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3530 if (_error->PendingError()) {
3535 if (result == pkgPackageManager::Failed) {
3540 if (result != pkgPackageManager::Completed) {
3545 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3547 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3549 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3550 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3553 if (![before isEqualToArray:after])
3558 NSString *title(UCLocalize("UPGRADE"));
3559 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3565 [self updateWithStatus:status_];
3568 - (void) setVisible {
3569 for (Package *package in packages_)
3570 [package setVisible];
3573 - (void) updateWithStatus:(Status &)status {
3574 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3575 NSString *title(UCLocalize("REFRESHING_DATA"));
3578 if (!list.ReadMainList())
3579 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3582 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3583 if ([self popErrorWithTitle:title])
3586 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3587 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3588 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3590 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3594 - (void) setDelegate:(id)delegate {
3595 delegate_ = delegate;
3596 status_.setDelegate(delegate);
3597 progress_.setDelegate(delegate);
3600 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3601 SourceMap::const_iterator i(sources_.find(file->ID));
3602 return i == sources_.end() ? nil : i->second;
3608 /* Confirmation Controller {{{ */
3609 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3610 if (!iterator.end())
3611 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3612 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3614 pkgCache::PkgIterator package(dep.TargetPkg());
3617 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3625 /* Web Scripting {{{ */
3626 @interface CydiaObject : NSObject {
3631 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3634 @implementation CydiaObject
3637 [indirect_ release];
3641 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3642 if ((self = [super init]) != nil) {
3643 indirect_ = [indirect retain];
3647 - (void) setDelegate:(id)delegate {
3648 delegate_ = delegate;
3651 + (NSArray *) _attributeKeys {
3652 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3655 - (NSArray *) attributeKeys {
3656 return [[self class] _attributeKeys];
3659 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3660 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3663 - (NSString *) device {
3664 return [[UIDevice currentDevice] uniqueIdentifier];
3667 #if 0 // XXX: implement!
3668 - (NSString *) mac {
3669 if (![indirect_ promptForSensitive:@"Mac Address"])
3673 - (NSString *) serial {
3674 if (![indirect_ promptForSensitive:@"Serial #"])
3678 - (NSString *) firewire {
3679 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3683 - (NSString *) imei {
3684 if (![indirect_ promptForSensitive:@"IMEI"])
3689 + (NSString *) webScriptNameForSelector:(SEL)selector {
3690 if (selector == @selector(close))
3692 else if (selector == @selector(getInstalledPackages))
3693 return @"getInstalledPackages";
3694 else if (selector == @selector(getPackageById:))
3695 return @"getPackageById";
3696 else if (selector == @selector(installPackages:))
3697 return @"installPackages";
3698 else if (selector == @selector(setAutoPopup:))
3699 return @"setAutoPopup";
3700 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3701 return @"setButtonImage";
3702 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3703 return @"setButtonTitle";
3704 else if (selector == @selector(setFinishHook:))
3705 return @"setFinishHook";
3706 else if (selector == @selector(setPopupHook:))
3707 return @"setPopupHook";
3708 else if (selector == @selector(setSpecial:))
3709 return @"setSpecial";
3710 else if (selector == @selector(setToken:))
3712 else if (selector == @selector(setViewportWidth:))
3713 return @"setViewportWidth";
3714 else if (selector == @selector(supports:))
3716 else if (selector == @selector(stringWithFormat:arguments:))
3718 else if (selector == @selector(localizedStringForKey:value:table:))
3720 else if (selector == @selector(du:))
3722 else if (selector == @selector(statfs:))
3728 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3729 return [self webScriptNameForSelector:selector] == nil;
3732 - (BOOL) supports:(NSString *)feature {
3733 return [feature isEqualToString:@"window.open"];
3736 - (NSArray *) getInstalledPackages {
3737 NSArray *packages([[Database sharedInstance] packages]);
3738 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3739 for (Package *package in packages)
3740 if ([package installed] != nil)
3741 [installed addObject:package];
3745 - (Package *) getPackageById:(NSString *)id {
3746 Package *package([[Database sharedInstance] packageWithName:id]);
3751 - (NSArray *) statfs:(NSString *)path {
3754 if (path == nil || statfs([path UTF8String], &stat) == -1)
3757 return [NSArray arrayWithObjects:
3758 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3759 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3760 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3764 - (NSNumber *) du:(NSString *)path {
3765 NSNumber *value(nil);
3768 _assert(pipe(fds) != -1);
3770 pid_t pid(ExecFork());
3772 _assert(dup2(fds[1], 1) != -1);
3773 _assert(close(fds[0]) != -1);
3774 _assert(close(fds[1]) != -1);
3775 /* XXX: this should probably not use du */
3776 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3781 _assert(close(fds[1]) != -1);
3783 if (FILE *du = fdopen(fds[0], "r")) {
3785 while (fgets(line, sizeof(line), du) != NULL) {
3786 size_t length(strlen(line));
3787 while (length != 0 && line[length - 1] == '\n')
3788 line[--length] = '\0';
3789 if (char *tab = strchr(line, '\t')) {
3791 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3796 } else _assert(close(fds[0]));
3800 if (waitpid(pid, &status, 0) == -1)
3803 else _assert(false);
3812 - (void) installPackages:(NSArray *)packages {
3813 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3816 - (void) setAutoPopup:(BOOL)popup {
3817 [indirect_ setAutoPopup:popup];
3820 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3821 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3824 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3825 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3828 - (void) setSpecial:(id)function {
3829 [indirect_ setSpecial:function];
3832 - (void) setToken:(NSString *)token {
3835 Token_ = [token retain];
3837 [Metadata_ setObject:Token_ forKey:@"Token"];
3841 - (void) setFinishHook:(id)function {
3842 [indirect_ setFinishHook:function];
3845 - (void) setPopupHook:(id)function {
3846 [indirect_ setPopupHook:function];
3849 - (void) setViewportWidth:(float)width {
3850 [indirect_ setViewportWidth:width];
3853 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3854 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3855 unsigned count([arguments count]);
3857 for (unsigned i(0); i != count; ++i)
3858 values[i] = [arguments objectAtIndex:i];
3859 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3862 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3863 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3865 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3867 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3873 /* Cydia Browser Controller {{{ */
3874 @interface CYBrowserController : BrowserController {
3875 CydiaObject *cydia_;
3880 @implementation CYBrowserController
3887 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3890 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3891 [super webView:sender didClearWindowObject:window forFrame:frame];
3893 WebDataSource *source([frame dataSource]);
3894 NSURLResponse *response([source response]);
3895 NSURL *url([response URL]);
3896 NSString *scheme([url scheme]);
3898 NSHTTPURLResponse *http;
3899 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3900 http = (NSHTTPURLResponse *) response;
3904 NSDictionary *headers([http allHeaderFields]);
3905 NSString *host([url host]);
3906 [self setHeaders:headers forHost:host];
3909 [host isEqualToString:@"cydia.saurik.com"] ||
3910 [host hasSuffix:@".cydia.saurik.com"] ||
3911 [scheme isEqualToString:@"file"]
3913 [window setValue:cydia_ forKey:@"cydia"];
3916 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3917 if (System_ != NULL)
3918 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3919 if (Machine_ != NULL)
3920 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3922 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3924 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3927 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3928 NSMutableURLRequest *copy = [request mutableCopy];
3929 [self _setMoreHeaders:copy];
3933 - (void) setDelegate:(id)delegate {
3934 [super setDelegate:delegate];
3935 [cydia_ setDelegate:delegate];
3939 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3940 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3942 WebView *webview([document_ webView]);
3944 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3946 NSString *application = package == nil ? @"Cydia" : [NSString
3947 stringWithFormat:@"Cydia/%@",
3952 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3954 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3955 if (Product_ != nil)
3956 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3958 [webview setApplicationNameForUserAgent:application];
3965 /* Confirmation {{{ */
3966 @protocol ConfirmationControllerDelegate
3967 - (void) cancelAndClear:(bool)clear;
3968 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3972 @interface ConfirmationController : CYBrowserController {
3973 _transient Database *database_;
3974 UIAlertView *essential_;
3981 - (id) initWithDatabase:(Database *)database;
3985 @implementation ConfirmationController
3992 if (essential_ != nil)
3993 [essential_ release];
3997 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3998 NSString *context([alert context]);
4000 if ([context isEqualToString:@"remove"]) {
4001 if (button == [alert cancelButtonIndex]) {
4002 [self dismissModalViewControllerAnimated:YES];
4003 } else if (button == [alert firstOtherButtonIndex]) {
4006 [delegate_ confirmWithNavigationController:[self navigationController]];
4009 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4010 } else if ([context isEqualToString:@"unable"]) {
4011 [self dismissModalViewControllerAnimated:YES];
4012 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4014 [super alertView:alert clickedButtonAtIndex:button];
4018 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4019 [self dismissModalViewControllerAnimated:YES];
4020 [delegate_ cancelAndClear:NO];
4025 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4026 [super webView:sender didClearWindowObject:window forFrame:frame];
4027 [window setValue:changes_ forKey:@"changes"];
4028 [window setValue:issues_ forKey:@"issues"];
4029 [window setValue:sizes_ forKey:@"sizes"];
4030 [window setValue:self forKey:@"queue"];
4033 - (id) initWithDatabase:(Database *)database {
4034 if ((self = [super init]) != nil) {
4035 database_ = database;
4037 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4039 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4040 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4041 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4042 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4043 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4047 pkgDepCache::Policy *policy([database_ policy]);
4049 pkgCacheFile &cache([database_ cache]);
4050 NSArray *packages = [database_ packages];
4051 for (Package *package in packages) {
4052 pkgCache::PkgIterator iterator = [package iterator];
4053 pkgDepCache::StateCache &state(cache[iterator]);
4055 NSString *name([package name]);
4057 if (state.NewInstall())
4058 [installing addObject:name];
4059 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4060 [reinstalling addObject:name];
4061 else if (state.Upgrade())
4062 [upgrading addObject:name];
4063 else if (state.Downgrade())
4064 [downgrading addObject:name];
4065 else if (state.Delete()) {
4066 if ([package essential])
4068 [removing addObject:name];
4071 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4072 substrate_ |= DepSubstrate(iterator.CurrentVer());
4077 else if (Advanced_) {
4078 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4080 essential_ = [[UIAlertView alloc]
4081 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4082 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4084 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4085 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4088 [essential_ setContext:@"remove"];
4090 essential_ = [[UIAlertView alloc]
4091 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4092 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4094 cancelButtonTitle:UCLocalize("OKAY")
4095 otherButtonTitles:nil
4098 [essential_ setContext:@"unable"];
4101 changes_ = [[NSArray alloc] initWithObjects:
4109 issues_ = [database_ issues];
4111 issues_ = [issues_ retain];
4113 sizes_ = [[NSArray alloc] initWithObjects:
4114 SizeString([database_ fetcher].FetchNeeded()),
4115 SizeString([database_ fetcher].PartialPresent()),
4118 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4120 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
4121 initWithTitle:UCLocalize("CANCEL")
4122 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4123 style:UIBarButtonItemStylePlain
4125 action:@selector(cancelButtonClicked)
4127 [[self navigationItem] setLeftBarButtonItem:leftItem];
4132 - (void) applyRightButton {
4133 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
4134 initWithTitle:UCLocalize("CONFIRM")
4135 style:UIBarButtonItemStylePlain
4137 action:@selector(confirmButtonClicked)
4139 #if !AlwaysReload && !IgnoreInstall
4140 if (issues_ == nil && ![self isLoading]) [[self navigationItem] setRightBarButtonItem:rightItem];
4141 else [super applyRightButton];
4143 [[self navigationItem] setRightBarButtonItem:nil];
4145 [rightItem release];
4148 - (void) cancelButtonClicked {
4149 [self dismissModalViewControllerAnimated:YES];
4150 [delegate_ cancelAndClear:YES];
4154 - (void) confirmButtonClicked {
4158 if (essential_ != nil)
4163 [delegate_ confirmWithNavigationController:[self navigationController]];
4171 /* Progress Data {{{ */
4172 @interface ProgressData : NSObject {
4178 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4185 @implementation ProgressData
4187 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4188 if ((self = [super init]) != nil) {
4189 selector_ = selector;
4209 /* Progress Controller {{{ */
4210 @interface ProgressController : CYViewController <
4211 ConfigurationDelegate,
4214 _transient Database *database_;
4215 UIProgressBar *progress_;
4216 UITextView *output_;
4217 UITextLabel *status_;
4218 UIPushButton *close_;
4220 SHA1SumValue springlist_;
4221 SHA1SumValue notifyconf_;
4225 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4227 - (void) _retachThread;
4228 - (void) _detachNewThreadData:(ProgressData *)data;
4229 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4235 @protocol ProgressControllerDelegate
4236 - (void) progressControllerIsComplete:(ProgressController *)sender;
4239 @implementation ProgressController
4242 [database_ setDelegate:nil];
4243 [progress_ release];
4252 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4253 if ((self = [super init]) != nil) {
4254 database_ = database;
4255 [database_ setDelegate:self];
4256 delegate_ = delegate;
4258 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4260 progress_ = [[UIProgressBar alloc] init];
4261 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4262 [progress_ setStyle:0];
4264 status_ = [[UITextLabel alloc] init];
4265 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4266 [status_ setColor:[UIColor whiteColor]];
4267 [status_ setBackgroundColor:[UIColor clearColor]];
4268 [status_ setCentersHorizontally:YES];
4269 //[status_ setFont:font];
4271 output_ = [[UITextView alloc] init];
4273 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4274 //[output_ setTextFont:@"Courier New"];
4275 [output_ setFont:[[output_ font] fontWithSize:12]];
4276 [output_ setTextColor:[UIColor whiteColor]];
4277 [output_ setBackgroundColor:[UIColor clearColor]];
4278 [output_ setMarginTop:0];
4279 [output_ setAllowsRubberBanding:YES];
4280 [output_ setEditable:NO];
4281 [[self view] addSubview:output_];
4283 close_ = [[UIPushButton alloc] init];
4284 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4285 [close_ setAutosizesToFit:NO];
4286 [close_ setDrawsShadow:YES];
4287 [close_ setStretchBackground:YES];
4288 [close_ setEnabled:YES];
4289 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4290 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4291 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4292 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4296 - (void) positionViews {
4297 CGRect bounds = [[self view] bounds];
4298 CGSize prgsize = [UIProgressBar defaultSize];
4301 (bounds.size.width - prgsize.width) / 2,
4302 bounds.size.height - prgsize.height - 64
4305 float closewidth = bounds.size.width - 20;
4306 if (closewidth > 300) closewidth = 300;
4308 [progress_ setFrame:prgrect];
4309 [status_ setFrame:CGRectMake(
4311 bounds.size.height - prgsize.height - 94,
4312 bounds.size.width - 20,
4315 [output_ setFrame:CGRectMake(
4318 bounds.size.width - 20,
4319 bounds.size.height - 106
4321 [close_ setFrame:CGRectMake(
4322 (bounds.size.width - closewidth) / 2,
4323 bounds.size.height - prgsize.height - 94,
4329 - (void) viewWillAppear:(BOOL)animated {
4330 [super viewDidAppear:animated];
4331 [[self navigationItem] setHidesBackButton:YES];
4332 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4334 [self positionViews];
4337 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4338 [self positionViews];
4341 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4342 NSString *context([alert context]);
4344 if ([context isEqualToString:@"conffile"]) {
4345 FILE *input = [database_ input];
4346 if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
4347 else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
4352 - (void) closeButtonPushed {
4355 UpdateExternalStatus(0);
4359 [self dismissModalViewControllerAnimated:YES];
4363 [delegate_ terminateWithSuccess];
4364 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4365 [delegate_ suspendWithAnimation:YES];
4367 [delegate_ suspend];*/
4371 system("launchctl stop com.apple.SpringBoard");
4375 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4384 - (void) _retachThread {
4385 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4387 [[self view] addSubview:close_];
4388 [progress_ removeFromSuperview];
4389 [status_ removeFromSuperview];
4391 [database_ popErrorWithTitle:title_];
4392 [delegate_ progressControllerIsComplete:self];
4396 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4399 MMap mmap(file, MMap::ReadOnly);
4401 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4402 if (!(notifyconf_ == sha1.Result()))
4409 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4412 MMap mmap(file, MMap::ReadOnly);
4414 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4415 if (!(springlist_ == sha1.Result()))
4421 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4422 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4423 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4424 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4425 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4428 system("su -c /usr/bin/uicache mobile");
4430 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4432 [delegate_ setStatusBarShowsProgress:NO];
4435 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4436 [[data target] performSelector:[data selector] withObject:[data object]];
4439 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4442 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4443 UpdateExternalStatus(1);
4450 title_ = [title retain];
4452 [[self navigationItem] setTitle:title_];
4454 [status_ setText:nil];
4455 [output_ setText:@""];
4456 [progress_ setProgress:0];
4458 [close_ removeFromSuperview];
4459 [[self view] addSubview:progress_];
4460 [[self view] addSubview:status_];
4462 [delegate_ setStatusBarShowsProgress:YES];
4467 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4470 MMap mmap(file, MMap::ReadOnly);
4472 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4473 notifyconf_ = sha1.Result();
4479 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4482 MMap mmap(file, MMap::ReadOnly);
4484 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4485 springlist_ = sha1.Result();
4490 detachNewThreadSelector:@selector(_detachNewThreadData:)
4492 withObject:[[ProgressData alloc]
4493 initWithSelector:selector
4500 - (void) repairWithSelector:(SEL)selector {
4502 detachNewThreadSelector:selector
4505 title:UCLocalize("REPAIRING")
4509 - (void) setConfigurationData:(NSString *)data {
4511 performSelectorOnMainThread:@selector(_setConfigurationData:)
4517 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4518 CYActionSheet *sheet([[[CYActionSheet alloc]
4520 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4521 defaultButtonIndex:0
4524 [sheet setMessage:error];
4525 [sheet yieldToPopupAlertAnimated:YES];
4529 - (void) setProgressTitle:(NSString *)title {
4531 performSelectorOnMainThread:@selector(_setProgressTitle:)
4537 - (void) setProgressPercent:(float)percent {
4539 performSelectorOnMainThread:@selector(_setProgressPercent:)
4540 withObject:[NSNumber numberWithFloat:percent]
4545 - (void) startProgress {
4548 - (void) addProgressOutput:(NSString *)output {
4550 performSelectorOnMainThread:@selector(_addProgressOutput:)
4556 - (bool) isCancelling:(size_t)received {
4560 - (void) _setConfigurationData:(NSString *)data {
4561 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4563 if (!conffile_r(data)) {
4564 lprintf("E:invalid conffile\n");
4568 NSString *ofile = conffile_r[1];
4569 //NSString *nfile = conffile_r[2];
4571 UIAlertView *alert = [[[UIAlertView alloc]
4572 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4573 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4575 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4576 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4577 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4581 [alert setContext:@"conffile"];
4585 - (void) _setProgressTitle:(NSString *)title {
4586 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4587 for (size_t i(0), e([words count]); i != e; ++i) {
4588 NSString *word([words objectAtIndex:i]);
4589 if (Package *package = [database_ packageWithName:word])
4590 [words replaceObjectAtIndex:i withObject:[package name]];
4593 [status_ setText:[words componentsJoinedByString:@" "]];
4596 - (void) _setProgressPercent:(NSNumber *)percent {
4597 [progress_ setProgress:[percent floatValue]];
4600 - (void) _addProgressOutput:(NSString *)output {
4601 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4602 CGSize size = [output_ contentSize];
4603 CGRect rect = {{0, size.height}, {size.width, 0}};
4604 [output_ scrollRectToVisible:rect animated:YES];
4607 - (BOOL) isRunning {
4614 /* Cell Content View {{{ */
4615 @protocol ContentDelegate
4616 - (void) drawContentRect:(CGRect)rect;
4619 @interface ContentView : UIView {
4620 _transient id<ContentDelegate> delegate_;
4625 @implementation ContentView
4626 - (id) initWithFrame:(CGRect)frame {
4627 if ((self = [super initWithFrame:frame]) != nil) {
4628 /* Fix landscape stretching. */
4629 [self setNeedsDisplayOnBoundsChange:YES];
4633 - (void) setDelegate:(id<ContentDelegate>)delegate {
4634 delegate_ = delegate;
4637 - (void) drawRect:(CGRect)rect {
4638 [super drawRect:rect];
4639 [delegate_ drawContentRect:rect];
4643 /* Package Cell {{{ */
4644 @interface PackageCell : UITableViewCell <
4649 NSString *description_;
4655 ContentView *content_;
4661 - (PackageCell *) init;
4662 - (void) setPackage:(Package *)package;
4664 + (int) heightForPackage:(Package *)package;
4665 - (void) drawContentRect:(CGRect)rect;
4669 @implementation PackageCell
4671 - (void) clearPackage {
4682 if (description_ != nil) {
4683 [description_ release];
4687 if (source_ != nil) {
4692 if (badge_ != nil) {
4697 if (placard_ != nil) {
4707 [self clearPackage];
4714 return faded_ ? [self selectionPercent] : fade_;
4717 - (PackageCell *) init {
4718 CGRect frame(CGRectMake(0, 0, 320, 74));
4719 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4720 UIView *content([self contentView]);
4721 CGRect bounds([content bounds]);
4723 content_ = [[ContentView alloc] initWithFrame:bounds];
4724 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4725 [content addSubview:content_];
4727 [content_ setDelegate:self];
4728 [content_ setOpaque:YES];
4729 if ([self respondsToSelector:@selector(selectionPercent)])
4734 - (void) _setBackgroundColor {
4736 if (NSString *mode = [package_ mode]) {
4737 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4738 color = remove ? RemovingColor_ : InstallingColor_;
4740 color = [UIColor whiteColor];
4742 [content_ setBackgroundColor:color];
4743 [self setNeedsDisplay];
4746 - (void) setPackage:(Package *)package {
4747 [self clearPackage];
4750 Source *source = [package source];
4752 icon_ = [[package icon] retain];
4753 name_ = [[package name] retain];
4756 description_ = [package longDescription];
4757 if (description_ == nil)
4758 description_ = [package shortDescription];
4759 if (description_ != nil)
4760 description_ = [description_ retain];
4762 commercial_ = [package isCommercial];
4764 package_ = [package retain];
4766 NSString *label = nil;
4767 bool trusted = false;
4769 if (source != nil) {
4770 label = [source label];
4771 trusted = [source trusted];
4772 } else if ([[package id] isEqualToString:@"firmware"])
4773 label = UCLocalize("APPLE");
4775 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4777 NSString *from(label);
4779 NSString *section = [package simpleSection];
4780 if (section != nil && ![section isEqualToString:label]) {
4781 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4782 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4785 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4786 source_ = [from retain];
4788 if (NSString *purpose = [package primaryPurpose])
4789 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4790 badge_ = [badge_ retain];
4792 if ([package installed] != nil)
4793 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4794 placard_ = [placard_ retain];
4796 [self _setBackgroundColor];
4797 [content_ setNeedsDisplay];
4800 - (void) drawContentRect:(CGRect)rect {
4801 bool selected([self isSelected]);
4802 float width([self bounds].size.width);
4805 CGContextRef context(UIGraphicsGetCurrentContext());
4806 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4807 CGContextFillRect(context, rect);
4812 rect.size = [icon_ size];
4814 rect.size.width /= 2;
4815 rect.size.height /= 2;
4817 rect.origin.x = 25 - rect.size.width / 2;
4818 rect.origin.y = 25 - rect.size.height / 2;
4820 [icon_ drawInRect:rect];
4823 if (badge_ != nil) {
4824 CGSize size = [badge_ size];
4826 [badge_ drawAtPoint:CGPointMake(
4827 36 - size.width / 2,
4828 36 - size.height / 2
4836 UISetColor(commercial_ ? Purple_ : Black_);
4837 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4838 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4841 UISetColor(commercial_ ? Purplish_ : Gray_);
4842 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4844 if (placard_ != nil)
4845 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4848 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4849 //[self _setBackgroundColor];
4850 [super setSelected:selected animated:fade];
4851 [content_ setNeedsDisplay];
4854 + (int) heightForPackage:(Package *)package {
4860 /* Section Cell {{{ */
4861 @interface SectionCell : UITableViewCell <
4869 ContentView *content_;
4874 - (void) setSection:(Section *)section editing:(BOOL)editing;
4878 @implementation SectionCell
4880 - (void) clearSection {
4881 if (basic_ != nil) {
4886 if (section_ != nil) {
4896 if (count_ != nil) {
4903 [self clearSection];
4911 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4912 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4913 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4914 switch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4915 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4917 UIView *content([self contentView]);
4918 CGRect bounds([content bounds]);
4920 content_ = [[ContentView alloc] initWithFrame:bounds];
4921 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4922 [content addSubview:content_];
4923 [content_ setBackgroundColor:[UIColor whiteColor]];
4925 [content_ setDelegate:self];
4929 - (void) onSwitch:(id)sender {
4930 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4931 if (metadata == nil) {
4932 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4933 [Sections_ setObject:metadata forKey:basic_];
4937 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4940 - (void) setSection:(Section *)section editing:(BOOL)editing {
4941 if (editing != editing_) {
4943 [switch_ removeFromSuperview];
4945 [self addSubview:switch_];
4949 [self clearSection];
4951 if (section == nil) {
4952 name_ = [UCLocalize("ALL_PACKAGES") retain];
4955 basic_ = [section name];
4957 basic_ = [basic_ retain];
4959 section_ = [section localized];
4960 if (section_ != nil)
4961 section_ = [section_ retain];
4963 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4964 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4967 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4970 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4971 [content_ setNeedsDisplay];
4974 - (void) setFrame:(CGRect)frame {
4975 [super setFrame:frame];
4977 CGRect rect([switch_ frame]);
4978 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4981 - (void) drawContentRect:(CGRect)rect {
4982 BOOL selected = [self isSelected];
4984 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4992 float width(rect.size.width);
4996 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4998 CGSize size = [count_ sizeWithFont:Font14_];
5002 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5008 /* File Table {{{ */
5009 @interface FileTable : CYViewController <
5010 UITableViewDataSource,
5013 _transient Database *database_;
5016 NSMutableArray *files_;
5020 - (id) initWithDatabase:(Database *)database;
5021 - (void) setPackage:(Package *)package;
5025 @implementation FileTable
5028 if (package_ != nil)
5037 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5038 return files_ == nil ? 0 : [files_ count];
5041 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5045 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5046 static NSString *reuseIdentifier = @"Cell";
5048 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5050 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5051 [cell setFont:[UIFont systemFontOfSize:16]];
5053 [cell setText:[files_ objectAtIndex:indexPath.row]];
5054 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5059 - (id) initWithDatabase:(Database *)database {
5060 if ((self = [super init]) != nil) {
5061 database_ = database;
5063 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5065 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5067 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5068 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5069 [list_ setRowHeight:24.0f];
5070 [[self view] addSubview:list_];
5072 [list_ setDataSource:self];
5073 [list_ setDelegate:self];
5077 - (void) setPackage:(Package *)package {
5078 if (package_ != nil) {
5079 [package_ autorelease];
5088 [files_ removeAllObjects];
5090 if (package != nil) {
5091 package_ = [package retain];
5092 name_ = [[package id] retain];
5094 if (NSArray *files = [package files])
5095 [files_ addObjectsFromArray:files];
5097 if ([files_ count] != 0) {
5098 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5099 [files_ removeObjectAtIndex:0];
5100 [files_ sortUsingSelector:@selector(compareByPath:)];
5102 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5103 [stack addObject:@"/"];
5105 for (int i(0), e([files_ count]); i != e; ++i) {
5106 NSString *file = [files_ objectAtIndex:i];
5107 while (![file hasPrefix:[stack lastObject]])
5108 [stack removeLastObject];
5109 NSString *directory = [stack lastObject];
5110 [stack addObject:[file stringByAppendingString:@"/"]];
5111 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5112 ([stack count] - 2) * 3, "",
5113 [file substringFromIndex:[directory length]]
5122 - (void) reloadData {
5123 [self setPackage:[database_ packageWithName:name_]];
5128 /* Package Controller {{{ */
5129 @interface PackageController : CYBrowserController <
5130 UIActionSheetDelegate
5132 _transient Database *database_;
5136 NSMutableArray *buttons_;
5139 - (id) initWithDatabase:(Database *)database;
5140 - (void) setPackage:(Package *)package;
5144 @implementation PackageController
5147 if (package_ != nil)
5156 if ([self retainCount] == 1)
5157 [delegate_ setPackageController:self];
5161 /* XXX: this is not safe at all... localization of /fail/ */
5162 - (void) _clickButtonWithName:(NSString *)name {
5163 if ([name isEqualToString:UCLocalize("CLEAR")])
5164 [delegate_ clearPackage:package_];
5165 else if ([name isEqualToString:UCLocalize("INSTALL")])
5166 [delegate_ installPackage:package_];
5167 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5168 [delegate_ installPackage:package_];
5169 else if ([name isEqualToString:UCLocalize("REMOVE")])
5170 [delegate_ removePackage:package_];
5171 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5172 [delegate_ installPackage:package_];
5173 else _assert(false);
5176 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5177 NSString *context([sheet context]);
5179 if ([context isEqualToString:@"modify"]) {
5180 if (button != [sheet cancelButtonIndex]) {
5181 NSString *buttonName = [buttons_ objectAtIndex:button];
5182 [self _clickButtonWithName:buttonName];
5185 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5189 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
5190 return [super webView:sender didFinishLoadForFrame:frame];
5193 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5194 [super webView:sender didClearWindowObject:window forFrame:frame];
5195 [window setValue:package_ forKey:@"package"];
5198 - (bool) _allowJavaScriptPanel {
5203 - (void) _customButtonClicked {
5204 int count([buttons_ count]);
5209 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5211 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5212 [buttons addObjectsFromArray:buttons_];
5214 UIActionSheet *sheet = [[[UIActionSheet alloc]
5217 cancelButtonTitle:nil
5218 destructiveButtonTitle:nil
5219 otherButtonTitles:nil
5222 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5224 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5225 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5227 [sheet setContext:@"modify"];
5229 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5233 // We don't want to allow non-commercial packages to do custom things to the install button,
5234 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5235 - (void) customButtonClicked {
5237 [super customButtonClicked];
5239 [self _customButtonClicked];
5242 - (void) reloadButtonClicked {
5243 // Don't reload a package view by clicking the button.
5246 - (void) applyLoadingTitle {
5247 // Don't show "Loading" as the title. Ever.
5250 - (UIBarButtonItem *) rightButton {
5251 int count = [buttons_ count];
5252 return [[[UIBarButtonItem alloc]
5253 initWithTitle:count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0]
5254 style:UIBarButtonItemStylePlain
5256 action:@selector(customButtonClicked)
5261 - (id) initWithDatabase:(Database *)database {
5262 if ((self = [super init]) != nil) {
5263 database_ = database;
5264 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5265 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5269 - (void) setPackage:(Package *)package {
5270 if (package_ != nil) {
5271 [package_ autorelease];
5280 [buttons_ removeAllObjects];
5282 if (package != nil) {
5285 package_ = [package retain];
5286 name_ = [[package id] retain];
5287 commercial_ = [package isCommercial];
5289 if ([package_ mode] != nil)
5290 [buttons_ addObject:UCLocalize("CLEAR")];
5291 if ([package_ source] == nil);
5292 else if ([package_ upgradableAndEssential:NO])
5293 [buttons_ addObject:UCLocalize("UPGRADE")];
5294 else if ([package_ uninstalled])
5295 [buttons_ addObject:UCLocalize("INSTALL")];
5297 [buttons_ addObject:UCLocalize("REINSTALL")];
5298 if (![package_ uninstalled])
5299 [buttons_ addObject:UCLocalize("REMOVE")];
5301 if (special_ != NULL) {
5302 CGRect frame([document_ frame]);
5303 frame.size.height = 0;
5304 [document_ setFrame:frame];
5306 if ([scroller_ respondsToSelector:@selector(scrollPointVisibleAtTopLeft:)])
5307 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5309 [scroller_ scrollRectToVisible:CGRectZero animated:NO];
5312 [[[document_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5314 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5316 [self setFinishHook:nil];
5317 [self setPopupHook:nil];
5320 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5321 [super callFunction:special_];
5326 - (bool) isLoading {
5327 return commercial_ ? [super isLoading] : false;
5330 - (void) reloadData {
5331 [self setPackage:[database_ packageWithName:name_]];
5336 /* Package Table {{{ */
5337 @interface PackageTable : UIView <
5338 UITableViewDataSource,
5341 _transient Database *database_;
5342 NSMutableArray *packages_;
5343 NSMutableArray *sections_;
5345 NSMutableArray *index_;
5346 NSMutableDictionary *indices_;
5352 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5354 - (void) setDelegate:(id)delegate;
5356 - (void) reloadData;
5357 - (void) resetCursor;
5359 - (UITableView *) list;
5361 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5363 - (void) deselectWithAnimation:(BOOL)animated;
5367 @implementation PackageTable
5370 [packages_ release];
5371 [sections_ release];
5379 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5380 NSInteger count([sections_ count]);
5381 return count == 0 ? 1 : count;
5384 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5385 if ([sections_ count] == 0)
5387 return [[sections_ objectAtIndex:section] name];
5390 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5391 if ([sections_ count] == 0)
5393 return [[sections_ objectAtIndex:section] count];
5396 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5397 Section *section([sections_ objectAtIndex:[path section]]);
5398 NSInteger row([path row]);
5399 Package *package([packages_ objectAtIndex:([section row] + row)]);
5403 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5404 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5406 cell = [[[PackageCell alloc] init] autorelease];
5407 [cell setPackage:[self packageAtIndexPath:path]];
5411 - (void) deselectWithAnimation:(BOOL)animated {
5412 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5415 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5416 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5419 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5420 Package *package([self packageAtIndexPath:path]);
5421 package = [database_ packageWithName:[package id]];
5422 [target_ performSelector:action_ withObject:package];
5426 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5427 return [packages_ count] > 20 ? index_ : nil;
5430 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5434 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5435 if ((self = [super initWithFrame:frame]) != nil) {
5436 database_ = database;
5441 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5442 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5444 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5445 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5447 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5448 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5449 [list_ setRowHeight:73.0f];
5450 [self addSubview:list_];
5452 [list_ setDataSource:self];
5453 [list_ setDelegate:self];
5457 - (void) setDelegate:(id)delegate {
5458 delegate_ = delegate;
5461 - (bool) hasPackage:(Package *)package {
5465 - (void) reloadData {
5466 NSArray *packages = [database_ packages];
5468 [packages_ removeAllObjects];
5469 [sections_ removeAllObjects];
5471 _profile(PackageTable$reloadData$Filter)
5472 for (Package *package in packages)
5473 if ([self hasPackage:package])
5474 [packages_ addObject:package];
5477 [index_ removeAllObjects];
5478 [indices_ removeAllObjects];
5480 Section *section = nil;
5482 _profile(PackageTable$reloadData$Section)
5483 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5487 _profile(PackageTable$reloadData$Section$Package)
5488 package = [packages_ objectAtIndex:offset];
5489 index = [package index];
5492 if (section == nil || [section index] != index) {
5493 _profile(PackageTable$reloadData$Section$Allocate)
5494 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5497 [index_ addObject:[section name]];
5498 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5500 _profile(PackageTable$reloadData$Section$Add)
5501 [sections_ addObject:section];
5505 [section addToCount];
5509 _profile(PackageTable$reloadData$List)
5514 - (void) resetCursor {
5515 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5518 - (UITableView *) list {
5522 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5523 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5528 /* Filtered Package Table {{{ */
5529 @interface FilteredPackageTable : PackageTable {
5535 - (void) setObject:(id)object;
5536 - (void) setObject:(id)object forFilter:(SEL)filter;
5538 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5542 @implementation FilteredPackageTable
5550 - (void) setFilter:(SEL)filter {
5553 /* XXX: this is an unsafe optimization of doomy hell */
5554 Method method(class_getInstanceMethod([Package class], filter));
5555 _assert(method != NULL);
5556 imp_ = method_getImplementation(method);
5557 _assert(imp_ != NULL);
5560 - (void) setObject:(id)object {
5566 object_ = [object retain];
5569 - (void) setObject:(id)object forFilter:(SEL)filter {
5570 [self setFilter:filter];
5571 [self setObject:object];
5574 - (bool) hasPackage:(Package *)package {
5575 _profile(FilteredPackageTable$hasPackage)
5576 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5580 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5581 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5582 [self setFilter:filter];
5583 object_ = [object retain];
5591 /* Filtered Package Controller {{{ */
5592 @interface FilteredPackageController : CYViewController {
5593 _transient Database *database_;
5594 FilteredPackageTable *packages_;
5598 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5602 @implementation FilteredPackageController
5605 [packages_ release];
5611 - (void) viewDidAppear:(BOOL)animated {
5612 [super viewDidAppear:animated];
5613 [packages_ deselectWithAnimation:animated];
5616 - (void) didSelectPackage:(Package *)package {
5617 PackageController *view([delegate_ packageController]);
5618 [view setPackage:package];
5619 [view setDelegate:delegate_];
5620 [[self navigationController] pushViewController:view animated:YES];
5623 - (NSString *) title { return title_; }
5625 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5626 if ((self = [super init]) != nil) {
5627 database_ = database;
5628 title_ = [title copy];
5629 [[self navigationItem] setTitle:title_];
5631 packages_ = [[FilteredPackageTable alloc]
5632 initWithFrame:[[self view] bounds]
5635 action:@selector(didSelectPackage:)
5640 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5641 [[self view] addSubview:packages_];
5645 - (void) reloadData {
5646 [packages_ reloadData];
5649 - (void) setDelegate:(id)delegate {
5650 [super setDelegate:delegate];
5651 [packages_ setDelegate:delegate];
5658 /* Add Source Controller {{{ */
5659 @interface AddSourceController : CYViewController {
5660 _transient Database *database_;
5663 - (id) initWithDatabase:(Database *)database;
5667 @implementation AddSourceController
5669 - (id) initWithDatabase:(Database *)database {
5670 if ((self = [super init]) != nil) {
5671 database_ = database;
5677 /* Source Cell {{{ */
5678 @interface SourceCell : UITableViewCell <
5683 NSString *description_;
5685 ContentView *content_;
5688 - (void) setSource:(Source *)source;
5692 @implementation SourceCell
5694 - (void) clearSource {
5697 [description_ release];
5706 - (void) setSource:(Source *)source {
5710 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5712 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5713 icon_ = [icon_ retain];
5715 origin_ = [[source name] retain];
5716 label_ = [[source uri] retain];
5717 description_ = [[source description] retain];
5719 [content_ setNeedsDisplay];
5728 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5729 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5730 UIView *content([self contentView]);
5731 CGRect bounds([content bounds]);
5733 content_ = [[ContentView alloc] initWithFrame:bounds];
5734 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5735 [content_ setBackgroundColor:[UIColor whiteColor]];
5736 [content addSubview:content_];
5738 [content_ setDelegate:self];
5739 [content_ setOpaque:YES];
5743 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5744 [super setSelected:selected animated:animated];
5745 [content_ setNeedsDisplay];
5748 - (void) drawContentRect:(CGRect)rect {
5749 bool selected([self isSelected]);
5750 float width(rect.size.width);
5753 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5760 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5764 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5768 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5773 /* Source Table {{{ */
5774 @interface SourceTable : CYViewController <
5775 UITableViewDataSource,
5778 _transient Database *database_;
5780 NSMutableArray *sources_;
5784 UIProgressHUD *hud_;
5787 //NSURLConnection *installer_;
5788 NSURLConnection *trivial_;
5789 NSURLConnection *trivial_bz2_;
5790 NSURLConnection *trivial_gz_;
5791 //NSURLConnection *automatic_;
5796 - (id) initWithDatabase:(Database *)database;
5798 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5802 @implementation SourceTable
5804 - (void) _deallocConnection:(NSURLConnection *)connection {
5805 if (connection != nil) {
5806 [connection cancel];
5807 //[connection setDelegate:nil];
5808 [connection release];
5820 //[self _deallocConnection:installer_];
5821 [self _deallocConnection:trivial_];
5822 [self _deallocConnection:trivial_gz_];
5823 [self _deallocConnection:trivial_bz2_];
5824 //[self _deallocConnection:automatic_];
5831 - (void) viewDidAppear:(BOOL)animated {
5832 [super viewDidAppear:animated];
5833 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5836 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5837 return offset_ == 0 ? 1 : 2;
5840 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5841 switch (section + (offset_ == 0 ? 1 : 0)) {
5842 case 0: return UCLocalize("ENTERED_BY_USER");
5843 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5849 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5850 int count = [sources_ count];
5852 case 0: return (offset_ == 0 ? count : offset_);
5853 case 1: return count - offset_;
5859 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5861 switch (indexPath.section) {
5862 case 0: idx = indexPath.row; break;
5863 case 1: idx = indexPath.row + offset_; break;
5867 return [sources_ objectAtIndex:idx];
5870 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5871 Source *source = [self sourceAtIndexPath:indexPath];
5872 return [source description] == nil ? 56 : 73;
5875 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5876 static NSString *cellIdentifier = @"SourceCell";
5878 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5879 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5880 [cell setSource:[self sourceAtIndexPath:indexPath]];
5885 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5886 return UITableViewCellAccessoryDisclosureIndicator;
5889 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5890 Source *source = [self sourceAtIndexPath:indexPath];
5892 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5893 initWithDatabase:database_
5894 title:[source label]
5895 filter:@selector(isVisibleInSource:)
5899 [packages setDelegate:delegate_];
5901 [[self navigationController] pushViewController:packages animated:YES];
5904 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5905 Source *source = [self sourceAtIndexPath:indexPath];
5906 return [source record] != nil;
5909 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5910 Source *source = [self sourceAtIndexPath:indexPath];
5911 [Sources_ removeObjectForKey:[source key]];
5912 [delegate_ syncData];
5916 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5919 @"./", @"Distribution",
5920 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5922 [delegate_ syncData];
5925 - (NSString *) getWarning {
5926 NSString *href(href_);
5927 NSRange colon([href rangeOfString:@"://"]);
5928 if (colon.location != NSNotFound)
5929 href = [href substringFromIndex:(colon.location + 3)];
5930 href = [href stringByAddingPercentEscapes];
5931 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5932 href = [href stringByCachingURLWithCurrentCDN];
5934 NSURL *url([NSURL URLWithString:href]);
5936 NSStringEncoding encoding;
5937 NSError *error(nil);
5939 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5940 return [warning length] == 0 ? nil : warning;
5944 - (void) _endConnection:(NSURLConnection *)connection {
5945 NSURLConnection **field = NULL;
5946 if (connection == trivial_)
5948 else if (connection == trivial_bz2_)
5949 field = &trivial_bz2_;
5950 else if (connection == trivial_gz_)
5951 field = &trivial_gz_;
5952 _assert(field != NULL);
5953 [connection release];
5958 trivial_bz2_ == nil &&
5964 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5967 UIAlertView *alert = [[[UIAlertView alloc]
5968 initWithTitle:UCLocalize("SOURCE_WARNING")
5971 cancelButtonTitle:UCLocalize("CANCEL")
5972 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5975 [alert setContext:@"warning"];
5976 [alert setNumberOfRows:1];
5980 } else if (error_ != nil) {
5981 UIAlertView *alert = [[[UIAlertView alloc]
5982 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5983 message:[error_ localizedDescription]
5985 cancelButtonTitle:UCLocalize("OK")
5986 otherButtonTitles:nil
5989 [alert setContext:@"urlerror"];
5992 UIAlertView *alert = [[[UIAlertView alloc]
5993 initWithTitle:UCLocalize("NOT_REPOSITORY")
5994 message:UCLocalize("NOT_REPOSITORY_EX")
5996 cancelButtonTitle:UCLocalize("OK")
5997 otherButtonTitles:nil
6000 [alert setContext:@"trivial"];
6004 [delegate_ setStatusBarShowsProgress:NO];
6005 [delegate_ removeProgressHUD:hud_];
6015 if (error_ != nil) {
6022 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6023 switch ([response statusCode]) {
6029 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6030 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6032 error_ = [error retain];
6033 [self _endConnection:connection];
6036 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6037 [self _endConnection:connection];
6040 - (NSString *) title { return UCLocalize("SOURCES"); }
6042 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6043 NSMutableURLRequest *request = [NSMutableURLRequest
6044 requestWithURL:[NSURL URLWithString:href]
6045 cachePolicy:NSURLRequestUseProtocolCachePolicy
6046 timeoutInterval:120.0
6049 [request setHTTPMethod:method];
6051 if (Machine_ != NULL)
6052 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6053 if (UniqueID_ != nil)
6054 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6056 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6058 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6061 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6062 NSString *context([alert context]);
6064 if ([context isEqualToString:@"source"]) {
6067 NSString *href = [[alert textField] text];
6069 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6071 if (![href hasSuffix:@"/"])
6072 href_ = [href stringByAppendingString:@"/"];
6075 href_ = [href_ retain];
6077 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6078 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6079 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6080 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6084 hud_ = [[delegate_ addProgressHUD] retain];
6085 [hud_ setText:UCLocalize("VERIFYING_URL")];
6094 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6095 } else if ([context isEqualToString:@"trivial"])
6096 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6097 else if ([context isEqualToString:@"urlerror"])
6098 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6099 else if ([context isEqualToString:@"warning"]) {
6114 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6118 - (id) initWithDatabase:(Database *)database {
6119 if ((self = [super init]) != nil) {
6120 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6121 [self updateButtonsForEditingStatus:NO animated:NO];
6123 database_ = database;
6124 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6126 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6127 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6128 [[self view] addSubview:list_];
6130 [list_ setDataSource:self];
6131 [list_ setDelegate:self];
6137 - (void) reloadData {
6139 if (!list.ReadMainList())
6142 [sources_ removeAllObjects];
6143 [sources_ addObjectsFromArray:[database_ sources]];
6145 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6148 int count([sources_ count]);
6150 for (int i = 0; i != count; i++) {
6151 if ([[sources_ objectAtIndex:i] record] == nil) break;
6155 [list_ setEditing:NO];
6156 [self updateButtonsForEditingStatus:NO animated:NO];
6160 - (void) addButtonClicked {
6161 /*[book_ pushPage:[[[AddSourceController alloc]
6166 UIAlertView *alert = [[[UIAlertView alloc]
6167 initWithTitle:UCLocalize("ENTER_APT_URL")
6170 cancelButtonTitle:UCLocalize("CANCEL")
6171 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6174 [alert setContext:@"source"];
6175 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6177 [alert setNumberOfRows:1];
6178 [alert addTextFieldWithValue:@"http://" label:@""];
6180 UITextInputTraits *traits = [[alert textField] textInputTraits];
6181 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6182 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6183 [traits setKeyboardType:UIKeyboardTypeURL];
6184 // XXX: UIReturnKeyDone
6185 [traits setReturnKeyType:UIReturnKeyNext];
6190 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6191 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
6192 initWithTitle:UCLocalize("ADD")
6193 style:UIBarButtonItemStylePlain
6195 action:@selector(addButtonClicked)
6197 [[self navigationItem] setLeftBarButtonItem:editing ? leftItem : [[self navigationItem] backBarButtonItem] animated:animated];
6200 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6201 initWithTitle:editing ? UCLocalize("DONE") : UCLocalize("EDIT")
6202 style:editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6204 action:@selector(editButtonClicked)
6206 [[self navigationItem] setRightBarButtonItem:rightItem animated:animated];
6207 [rightItem release];
6209 if (IsWildcat_ && !editing) {
6210 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6211 initWithTitle:UCLocalize("SETTINGS")
6212 style:UIBarButtonItemStylePlain
6214 action:@selector(settingsButtonClicked)
6216 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6217 [settingsItem release];
6221 - (void) settingsButtonClicked {
6222 [delegate_ showSettings];
6225 - (void) editButtonClicked {
6226 [list_ setEditing:![list_ isEditing] animated:YES];
6228 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6234 /* Installed Controller {{{ */
6235 @interface InstalledController : FilteredPackageController {
6239 - (id) initWithDatabase:(Database *)database;
6241 - (void) updateRoleButton;
6242 - (void) queueStatusDidChange;
6246 @implementation InstalledController
6252 - (NSString *) title { return UCLocalize("INSTALLED"); }
6254 - (id) initWithDatabase:(Database *)database {
6255 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6256 [self updateRoleButton];
6257 [self queueStatusDidChange];
6262 - (void) queueButtonClicked {
6267 - (void) queueStatusDidChange {
6270 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6271 initWithTitle:UCLocalize("QUEUE")
6272 style:UIBarButtonItemStyleDone
6274 action:@selector(queueButtonClicked)
6276 if (Queuing_) [[self navigationItem] setLeftBarButtonItem:queueItem];
6277 else [[self navigationItem] setLeftBarButtonItem:nil];
6278 [queueItem release];
6283 - (void) reloadData {
6284 [packages_ reloadData];
6287 - (void) updateRoleButton {
6288 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6289 initWithTitle:expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")
6290 style:expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6292 action:@selector(roleButtonClicked)
6294 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) [[self navigationItem] setRightBarButtonItem:rightItem];
6295 [rightItem release];
6298 - (void) roleButtonClicked {
6299 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6300 [packages_ reloadData];
6303 [self updateRoleButton];
6306 - (void) setDelegate:(id)delegate {
6307 [super setDelegate:delegate];
6308 [packages_ setDelegate:delegate];
6314 /* Home Controller {{{ */
6315 @interface HomeController : CYBrowserController {
6320 @implementation HomeController
6322 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6323 [super _setMoreHeaders:request];
6325 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6326 if (UniqueID_ != nil)
6327 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6330 - (void) aboutButtonClicked {
6331 UIAlertView *alert = [[[UIAlertView alloc] init] autorelease];
6332 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6333 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6334 [alert setCancelButtonIndex:0];
6337 @"Copyright (C) 2008-2010\n"
6338 "Jay Freeman (saurik)\n"
6339 "saurik@saurik.com\n"
6340 "http://www.saurik.com/"
6346 - (void) viewWillAppear:(BOOL)animated {
6347 [super viewWillAppear:animated];
6348 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6351 - (void) viewWillDisappear:(BOOL)animated {
6352 [super viewWillDisappear:animated];
6353 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6357 if ((self = [super init]) != nil) {
6358 UIBarButtonItem *aboutItem = [[UIBarButtonItem alloc]
6359 initWithTitle:UCLocalize("ABOUT")
6360 style:UIBarButtonItemStylePlain
6362 action:@selector(aboutButtonClicked)
6364 [[self navigationItem] setLeftBarButtonItem:aboutItem];
6365 [aboutItem release];
6371 /* Manage Controller {{{ */
6372 @interface ManageController : CYBrowserController {
6375 - (void) queueStatusDidChange;
6378 @implementation ManageController
6381 if ((self = [super init]) != nil) {
6382 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6384 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6385 initWithTitle:UCLocalize("SETTINGS")
6386 style:UIBarButtonItemStylePlain
6388 action:@selector(settingsButtonClicked)
6390 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6391 [settingsItem release];
6393 [self queueStatusDidChange];
6397 - (void) settingsButtonClicked {
6398 [delegate_ showSettings];
6402 - (void) queueButtonClicked {
6406 - (void) applyLoadingTitle {
6407 // No "Loading" title.
6410 - (void) applyRightButton {
6415 - (void) queueStatusDidChange {
6417 if (!IsWildcat_ && Queuing_) {
6418 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6419 initWithTitle:UCLocalize("QUEUE")
6420 style:UIBarButtonItemStyleDone
6422 action:@selector(queueButtonClicked)
6424 [[self navigationItem] setRightBarButtonItem:queueItem];
6426 [queueItem release];
6428 [[self navigationItem] setRightBarButtonItem:nil];
6433 - (bool) isLoading {
6440 /* Refresh Bar {{{ */
6441 @interface RefreshBar : UINavigationBar {
6442 UIProgressIndicator *indicator_;
6443 UITextLabel *prompt_;
6444 UIProgressBar *progress_;
6445 UINavigationButton *cancel_;
6450 @implementation RefreshBar
6452 - (void) positionViews {
6453 CGRect frame = [cancel_ frame];
6454 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6455 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6456 [cancel_ setFrame:frame];
6458 CGSize prgsize = {75, 100};
6460 [self frame].size.width - prgsize.width - 10,
6461 ([self frame].size.height - prgsize.height) / 2
6463 [progress_ setFrame:prgrect];
6465 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6466 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6467 CGRect indrect = {{indoffset, indoffset}, indsize};
6468 [indicator_ setFrame:indrect];
6470 CGSize prmsize = {215, indsize.height + 4};
6472 indoffset * 2 + indsize.width,
6473 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6475 [prompt_ setFrame:prmrect];
6478 - (void)setFrame:(CGRect)frame {
6479 [super setFrame:frame];
6481 [self positionViews];
6484 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6485 if ((self = [super initWithFrame:frame])) {
6486 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6488 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6489 [self setBarStyle:UIBarStyleBlack];
6491 UIBarStyle barstyle([self _barStyle:NO]);
6492 bool ugly(barstyle == UIBarStyleDefault);
6494 UIProgressIndicatorStyle style = ugly ?
6495 UIProgressIndicatorStyleMediumBrown :
6496 UIProgressIndicatorStyleMediumWhite;
6498 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6499 [indicator_ setStyle:style];
6500 [indicator_ startAnimation];
6501 [self addSubview:indicator_];
6503 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6504 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6505 [prompt_ setBackgroundColor:[UIColor clearColor]];
6506 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6507 [self addSubview:prompt_];
6509 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6510 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6511 [progress_ setStyle:0];
6512 [self addSubview:progress_];
6514 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6515 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6516 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6517 [cancel_ setBarStyle:barstyle];
6519 [self positionViews];
6524 [cancel_ removeFromSuperview];
6528 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6529 [progress_ setProgress:0];
6530 [self addSubview:cancel_];
6534 [cancel_ removeFromSuperview];
6537 - (void) setPrompt:(NSString *)prompt {
6538 [prompt_ setText:prompt];
6541 - (void) setProgress:(float)progress {
6542 [progress_ setProgress:progress];
6548 @class CYNavigationController;
6550 /* Cydia Tab Bar Controller {{{ */
6551 @interface CYTabBarController : UITabBarController {
6552 Database *database_;
6557 @implementation CYTabBarController
6559 /* XXX: some logic should probably go here related to
6560 freeing the view controllers on tab change */
6562 - (void) reloadData {
6563 size_t count([[self viewControllers] count]);
6564 for (size_t i(0); i != count; ++i) {
6565 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6570 - (id) initWithDatabase:(Database *)database {
6571 if ((self = [super init]) != nil) {
6572 database_ = database;
6579 /* Cydia Navigation Controller {{{ */
6580 @interface CYNavigationController : UINavigationController {
6581 _transient Database *database_;
6582 id<UINavigationControllerDelegate> delegate_;
6585 - (id) initWithDatabase:(Database *)database;
6586 - (void) reloadData;
6591 @implementation CYNavigationController
6593 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6594 // Inherit autorotation settings for modal parents.
6595 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6596 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6598 return [super shouldAutorotateToInterfaceOrientation:orientation];
6606 - (void) reloadData {
6607 size_t count([[self viewControllers] count]);
6608 for (size_t i(0); i != count; ++i) {
6609 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6614 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6615 delegate_ = delegate;
6618 - (id) initWithDatabase:(Database *)database {
6619 if ((self = [super init]) != nil) {
6620 database_ = database;
6626 /* Cydia:// Protocol {{{ */
6627 @interface CydiaURLProtocol : NSURLProtocol {
6632 @implementation CydiaURLProtocol
6634 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6635 NSURL *url([request URL]);
6638 NSString *scheme([[url scheme] lowercaseString]);
6639 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6644 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6648 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6649 id<NSURLProtocolClient> client([self client]);
6651 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6653 NSData *data(UIImagePNGRepresentation(icon));
6655 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6656 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6657 [client URLProtocol:self didLoadData:data];
6658 [client URLProtocolDidFinishLoading:self];
6662 - (void) startLoading {
6663 id<NSURLProtocolClient> client([self client]);
6664 NSURLRequest *request([self request]);
6666 NSURL *url([request URL]);
6667 NSString *href([url absoluteString]);
6669 NSString *path([href substringFromIndex:8]);
6670 NSRange slash([path rangeOfString:@"/"]);
6673 if (slash.location == NSNotFound) {
6677 command = [path substringToIndex:slash.location];
6678 path = [path substringFromIndex:(slash.location + 1)];
6681 Database *database([Database sharedInstance]);
6683 if ([command isEqualToString:@"package-icon"]) {
6686 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6687 Package *package([database packageWithName:path]);
6690 UIImage *icon([package icon]);
6691 [self _returnPNGWithImage:icon forRequest:request];
6692 } else if ([command isEqualToString:@"source-icon"]) {
6695 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6696 NSString *source(Simplify(path));
6697 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6699 icon = [UIImage applicationImageNamed:@"unknown.png"];
6700 [self _returnPNGWithImage:icon forRequest:request];
6701 } else if ([command isEqualToString:@"uikit-image"]) {
6704 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6705 UIImage *icon(_UIImageWithName(path));
6706 [self _returnPNGWithImage:icon forRequest:request];
6707 } else if ([command isEqualToString:@"section-icon"]) {
6710 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6711 NSString *section(Simplify(path));
6712 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6714 icon = [UIImage applicationImageNamed:@"unknown.png"];
6715 [self _returnPNGWithImage:icon forRequest:request];
6717 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6721 - (void) stopLoading {
6727 /* Sections Controller {{{ */
6728 @interface SectionsController : CYViewController <
6729 UITableViewDataSource,
6732 _transient Database *database_;
6733 NSMutableArray *sections_;
6734 NSMutableArray *filtered_;
6740 - (id) initWithDatabase:(Database *)database;
6741 - (void) reloadData;
6744 - (void) editButtonClicked;
6748 @implementation SectionsController
6751 [list_ setDataSource:nil];
6752 [list_ setDelegate:nil];
6754 [sections_ release];
6755 [filtered_ release];
6757 [accessory_ release];
6761 - (void) viewDidAppear:(BOOL)animated {
6762 [super viewDidAppear:animated];
6763 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6766 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6767 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6771 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6772 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6775 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6779 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6780 static NSString *reuseIdentifier = @"SectionCell";
6782 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6783 if (cell == nil) cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6784 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6789 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6790 Section *section = [self sectionAtIndexPath:indexPath];
6791 NSString *name = [section name];
6794 if ([indexPath row] == 0) {
6797 title = UCLocalize("ALL_PACKAGES");
6800 name = [NSString stringWithString:name];
6801 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6804 title = UCLocalize("NO_SECTION");
6808 FilteredPackageController *table = [[[FilteredPackageController alloc]
6809 initWithDatabase:database_
6811 filter:@selector(isVisibleInSection:)
6815 [table setDelegate:delegate_];
6817 [[self navigationController] pushViewController:table animated:YES];
6820 - (NSString *) title { return UCLocalize("SECTIONS"); }
6822 - (id) initWithDatabase:(Database *)database {
6823 if ((self = [super init]) != nil) {
6824 database_ = database;
6826 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6828 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6829 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6831 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6832 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6833 [list_ setRowHeight:45.0f];
6834 [[self view] addSubview:list_];
6836 [list_ setDataSource:self];
6837 [list_ setDelegate:self];
6843 - (void) reloadData {
6844 NSArray *packages = [database_ packages];
6846 [sections_ removeAllObjects];
6847 [filtered_ removeAllObjects];
6850 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6851 SectionMap sections;
6852 sections.resize(64);
6854 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6858 for (Package *package in packages) {
6859 NSString *name([package section]);
6860 NSString *key(name == nil ? @"" : name);
6865 _profile(SectionsView$reloadData$Section)
6866 section = §ions[key];
6867 if (*section == nil) {
6868 _profile(SectionsView$reloadData$Section$Allocate)
6869 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6874 [*section addToCount];
6876 _profile(SectionsView$reloadData$Filter)
6877 if (![package valid] || ![package visible])
6881 [*section addToRow];
6885 _profile(SectionsView$reloadData$Section)
6886 section = [sections objectForKey:key];
6887 if (section == nil) {
6888 _profile(SectionsView$reloadData$Section$Allocate)
6889 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6890 [sections setObject:section forKey:key];
6895 [section addToCount];
6897 _profile(SectionsView$reloadData$Filter)
6898 if (![package valid] || ![package visible])
6908 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6909 [sections_ addObject:i->second];
6911 [sections_ addObjectsFromArray:[sections allValues]];
6914 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6916 for (Section *section in sections_) {
6917 size_t count([section row]);
6921 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6922 [section setCount:count];
6923 [filtered_ addObject:section];
6926 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6927 initWithTitle:[sections_ count] == 0 ? nil : UCLocalize("EDIT")
6928 style:UIBarButtonItemStylePlain
6930 action:@selector(editButtonClicked)
6932 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] != nil];
6933 [rightItem release];
6939 - (void) resetView {
6941 [self editButtonClicked];
6944 - (void) editButtonClicked {
6945 if ((editing_ = !editing_))
6948 [delegate_ updateData];
6950 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6951 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6952 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6955 - (UIView *) accessoryView {
6961 /* Changes Controller {{{ */
6962 @interface ChangesController : CYViewController <
6963 UITableViewDataSource,
6966 _transient Database *database_;
6967 NSMutableArray *packages_;
6968 NSMutableArray *sections_;
6971 BOOL hasSentFirstLoad_;
6974 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6975 - (void) reloadData;
6979 @implementation ChangesController
6982 [list_ setDelegate:nil];
6983 [list_ setDataSource:nil];
6985 [packages_ release];
6986 [sections_ release];
6991 - (void) viewDidAppear:(BOOL)animated {
6992 [super viewDidAppear:animated];
6993 if (!hasSentFirstLoad_) {
6994 hasSentFirstLoad_ = YES;
6995 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6997 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7001 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7002 NSInteger count([sections_ count]);
7003 return count == 0 ? 1 : count;
7006 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7007 if ([sections_ count] == 0)
7009 return [[sections_ objectAtIndex:section] name];
7012 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7013 if ([sections_ count] == 0)
7015 return [[sections_ objectAtIndex:section] count];
7018 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7019 Section *section([sections_ objectAtIndex:[path section]]);
7020 NSInteger row([path row]);
7021 return [packages_ objectAtIndex:([section row] + row)];
7024 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7025 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7027 cell = [[[PackageCell alloc] init] autorelease];
7028 [cell setPackage:[self packageAtIndexPath:path]];
7032 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7033 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7036 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7037 Package *package([self packageAtIndexPath:path]);
7038 PackageController *view([delegate_ packageController]);
7039 [view setDelegate:delegate_];
7040 [view setPackage:package];
7041 [[self navigationController] pushViewController:view animated:YES];
7045 - (void) refreshButtonClicked {
7046 [delegate_ beginUpdate];
7047 [[self navigationItem] setLeftBarButtonItem:nil];
7050 - (void) upgradeButtonClicked {
7051 [delegate_ distUpgrade];
7054 - (NSString *) title { return UCLocalize("CHANGES"); }
7056 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7057 if ((self = [super init]) != nil) {
7058 database_ = database;
7059 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7061 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
7062 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7064 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7065 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7066 [list_ setRowHeight:73.0f];
7067 [[self view] addSubview:list_];
7069 [list_ setDataSource:self];
7070 [list_ setDelegate:self];
7072 delegate_ = delegate;
7076 - (void) _reloadPackages:(NSArray *)packages {
7078 for (Package *package in packages)
7080 [package uninstalled] && [package valid] && [package visible] ||
7081 [package upgradableAndEssential:YES]
7083 [packages_ addObject:package];
7086 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7090 - (void) reloadData {
7091 NSArray *packages = [database_ packages];
7093 [packages_ removeAllObjects];
7094 [sections_ removeAllObjects];
7096 UIProgressHUD *hud([delegate_ addProgressHUD]);
7098 [hud setText:@"Loading Changes"];
7099 NSLog(@"HUD:%@::%@", delegate_, hud);
7100 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7101 [delegate_ removeProgressHUD:hud];
7103 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7104 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7105 Section *section = nil;
7109 bool unseens = false;
7111 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7113 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7114 Package *package = [packages_ objectAtIndex:offset];
7116 BOOL uae = [package upgradableAndEssential:YES];
7122 _profile(ChangesController$reloadData$Remember)
7123 seen = [package seen];
7126 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7131 name = UCLocalize("UNKNOWN");
7133 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7137 _profile(ChangesController$reloadData$Allocate)
7138 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7139 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7140 [sections_ addObject:section];
7144 [section addToCount];
7145 } else if ([package ignored])
7146 [ignored addToCount];
7149 [upgradable addToCount];
7154 CFRelease(formatter);
7157 Section *last = [sections_ lastObject];
7158 size_t count = [last count];
7159 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7160 [sections_ removeLastObject];
7163 if ([ignored count] != 0)
7164 [sections_ insertObject:ignored atIndex:0];
7166 [sections_ insertObject:upgradable atIndex:0];
7170 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7171 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7172 style:UIBarButtonItemStylePlain
7174 action:@selector(upgradeButtonClicked)
7176 if (upgrades_ > 0) [[self navigationItem] setRightBarButtonItem:rightItem];
7177 [rightItem release];
7179 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
7180 initWithTitle:UCLocalize("REFRESH")
7181 style:UIBarButtonItemStylePlain
7183 action:@selector(refreshButtonClicked)
7185 if (![delegate_ updating]) [[self navigationItem] setLeftBarButtonItem:leftItem];
7191 /* Search Controller {{{ */
7192 @interface SearchController : FilteredPackageController <
7195 UISearchBar *search_;
7198 - (id) initWithDatabase:(Database *)database;
7199 - (void) reloadData;
7203 @implementation SearchController
7210 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7211 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7212 [search_ resignFirstResponder];
7216 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7217 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7221 - (NSString *) title { return nil; }
7223 - (id) initWithDatabase:(Database *)database {
7224 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7227 - (void)viewDidAppear:(BOOL)animated {
7228 [super viewDidAppear:animated];
7230 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7231 [search_ layoutSubviews];
7232 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7233 UITextField *textField = [search_ searchField];
7234 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7235 [search_ setDelegate:self];
7236 [textField setEnablesReturnKeyAutomatically:NO];
7237 [[self navigationItem] setTitleView:textField];
7241 - (void) _reloadData {
7244 - (void) reloadData {
7245 _profile(SearchController$reloadData)
7246 [packages_ reloadData];
7249 [packages_ resetCursor];
7252 - (void) didSelectPackage:(Package *)package {
7253 [search_ resignFirstResponder];
7254 [super didSelectPackage:package];
7259 /* Settings Controller {{{ */
7260 @interface SettingsController : CYViewController <
7261 UITableViewDataSource,
7264 _transient Database *database_;
7267 UITableView *table_;
7268 id subscribedSwitch_;
7270 UITableViewCell *subscribedCell_;
7271 UITableViewCell *ignoredCell_;
7274 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7278 @implementation SettingsController
7282 if (package_ != nil)
7285 [subscribedSwitch_ release];
7286 [ignoredSwitch_ release];
7287 [subscribedCell_ release];
7288 [ignoredCell_ release];
7293 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7294 if (package_ == nil)
7300 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7301 if (package_ == nil)
7307 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7308 return UCLocalize("SHOW_ALL_CHANGES_EX");
7311 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7312 if (package_ == nil)
7315 NSMutableDictionary *metadata([package_ metadata]);
7318 if (NSNumber *number = [metadata objectForKey:key])
7319 before = [number boolValue];
7323 if (value != before) {
7324 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7326 [delegate_ updateData];
7330 - (void) onSubscribed:(id)control {
7331 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7334 - (void) onIgnored:(id)control {
7335 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
7338 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7339 if (package_ == nil)
7342 switch ([indexPath row]) {
7343 case 0: return subscribedCell_;
7344 case 1: return ignoredCell_;
7352 - (NSString *) title { return UCLocalize("SETTINGS"); }
7354 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7355 if ((self = [super init])) {
7356 database_ = database;
7357 name_ = [package retain];
7359 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7361 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7362 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7363 [table_ setAllowsSelection:NO];
7364 [[self view] addSubview:table_];
7366 subscribedSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7367 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7368 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7370 ignoredSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7371 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7372 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7374 subscribedCell_ = [[UITableViewCell alloc] init];
7375 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7376 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7378 ignoredCell_ = [[UITableViewCell alloc] init];
7379 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7380 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7382 [table_ setDataSource:self];
7383 [table_ setDelegate:self];
7388 - (void) reloadData {
7389 if (package_ != nil)
7390 [package_ autorelease];
7391 package_ = [database_ packageWithName:name_];
7392 if (package_ != nil) {
7394 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7395 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7398 [table_ reloadData];
7404 /* Signature Controller {{{ */
7405 @interface SignatureController : CYBrowserController {
7406 _transient Database *database_;
7410 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7414 @implementation SignatureController
7421 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7423 [super webView:sender didClearWindowObject:window forFrame:frame];
7426 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7427 if ((self = [super init]) != nil) {
7428 database_ = database;
7429 package_ = [package retain];
7434 - (void) reloadData {
7435 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7440 /* Role Controller {{{ */
7441 @interface RoleController : CYViewController <
7442 UITableViewDataSource,
7445 _transient Database *database_;
7447 UITableView *table_;
7448 UISegmentedControl *segment_;
7452 - (void) showDoneButton;
7453 - (void) resizeSegmentedControl;
7457 @implementation RoleController
7461 [container_ release];
7466 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7467 if ((self = [super init])) {
7468 database_ = database;
7469 roledelegate_ = delegate;
7471 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7473 NSArray *items = [NSArray arrayWithObjects:
7475 UCLocalize("HACKER"),
7476 UCLocalize("DEVELOPER"),
7478 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7479 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7480 [container_ addSubview:segment_];
7483 if ([Role_ isEqualToString:@"User"]) index = 0;
7484 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7485 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7487 [segment_ setSelectedSegmentIndex:index];
7488 [self showDoneButton];
7491 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7492 [self resizeSegmentedControl];
7494 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7495 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7496 [table_ setDelegate:self];
7497 [table_ setDataSource:self];
7498 [[self view] addSubview:table_];
7499 [table_ reloadData];
7503 - (void) resizeSegmentedControl {
7504 CGFloat width = [[self view] frame].size.width;
7505 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7508 - (void) viewWillAppear:(BOOL)animated {
7509 [super viewWillAppear:animated];
7511 [self resizeSegmentedControl];
7514 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7515 [self resizeSegmentedControl];
7518 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7519 [self resizeSegmentedControl];
7523 NSString *role(nil);
7525 switch ([segment_ selectedSegmentIndex]) {
7526 case 0: role = @"User"; break;
7527 case 1: role = @"Hacker"; break;
7528 case 2: role = @"Developer"; break;
7533 if (![role isEqualToString:Role_]) {
7534 bool rolling(Role_ == nil);
7537 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7541 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7546 [roledelegate_ loadData];
7548 [roledelegate_ updateData];
7552 - (void) segmentChanged:(UISegmentedControl *)control {
7553 [self showDoneButton];
7556 - (void) doneButtonClicked {
7558 [[self navigationController] dismissModalViewControllerAnimated:YES];
7561 - (void) showDoneButton {
7562 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7563 initWithTitle:UCLocalize("DONE")
7564 style:UIBarButtonItemStyleDone
7566 action:@selector(doneButtonClicked)
7568 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] == nil];
7569 [rightItem release];
7572 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7573 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7577 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7581 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7582 return nil; // This method is required by the protocol.
7585 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7587 return UCLocalize("ROLE_EX");
7589 return [NSString stringWithFormat:
7590 @"%@: %@\n%@: %@\n%@: %@",
7591 UCLocalize("USER"), UCLocalize("USER_EX"),
7592 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7593 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7598 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7599 if (section == 3) return 44.0f;
7603 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7604 if (section == 3) return container_;
7611 /* Cydia Container {{{ */
7612 @interface CYContainer : UIViewController <ProgressDelegate> {
7613 _transient Database *database_;
7614 RefreshBar *refreshbar_;
7619 UITabBarController *root_;
7622 - (void) setTabBarController:(UITabBarController *)controller;
7624 - (void) dropBar:(BOOL)animated;
7625 - (void) beginUpdate;
7626 - (void) raiseBar:(BOOL)animated;
7630 @implementation CYContainer
7632 // NOTE: UIWindow only sends the top controller these messages,
7633 // So we have to forward them on.
7635 - (void) viewDidAppear:(BOOL)animated {
7636 [super viewDidAppear:animated];
7637 [root_ viewDidAppear:animated];
7640 - (void) viewWillAppear:(BOOL)animated {
7641 [super viewWillAppear:animated];
7642 [root_ viewWillAppear:animated];
7645 - (void) viewDidDisappear:(BOOL)animated {
7646 [super viewDidDisappear:animated];
7647 [root_ viewDidDisappear:animated];
7650 - (void) viewWillDisappear:(BOOL)animated {
7651 [super viewWillDisappear:animated];
7652 [root_ viewWillDisappear:animated];
7655 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7659 - (void) setTabBarController:(UITabBarController *)controller {
7661 [[self view] addSubview:[root_ view]];
7664 - (void) setUpdate:(NSDate *)date {
7668 - (void) beginUpdate {
7670 [refreshbar_ start];
7675 detachNewThreadSelector:@selector(performUpdate)
7681 - (void) performUpdate { _pooled
7683 status.setDelegate(self);
7684 [database_ updateWithStatus:status];
7687 performSelectorOnMainThread:@selector(completeUpdate)
7693 - (void) completeUpdate {
7696 [self raiseBar:YES];
7698 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7701 - (void) cancelUpdate {
7702 [refreshbar_ cancel];
7703 [self completeUpdate];
7706 - (void) cancelPressed {
7707 [self cancelUpdate];
7714 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7715 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7718 - (void) startProgress {
7721 - (void) setProgressTitle:(NSString *)title {
7723 performSelectorOnMainThread:@selector(_setProgressTitle:)
7729 - (bool) isCancelling:(size_t)received {
7733 - (void) setProgressPercent:(float)percent {
7735 performSelectorOnMainThread:@selector(_setProgressPercent:)
7736 withObject:[NSNumber numberWithFloat:percent]
7741 - (void) addProgressOutput:(NSString *)output {
7743 performSelectorOnMainThread:@selector(_addProgressOutput:)
7749 - (void) _setProgressTitle:(NSString *)title {
7750 [refreshbar_ setPrompt:title];
7753 - (void) _setProgressPercent:(NSNumber *)percent {
7754 [refreshbar_ setProgress:[percent floatValue]];
7757 - (void) _addProgressOutput:(NSString *)output {
7760 - (void) setUpdateDelegate:(id)delegate {
7761 updatedelegate_ = delegate;
7764 - (void) dropBar:(BOOL)animated {
7765 if (dropped_) return;
7768 [[self view] addSubview:refreshbar_];
7770 if (animated) [UIView beginAnimations:nil context:NULL];
7771 CGRect barframe = [refreshbar_ frame];
7772 CGRect viewframe = [[root_ view] frame];
7773 viewframe.origin.y += barframe.size.height;
7774 viewframe.size.height -= barframe.size.height;
7775 [[root_ view] setFrame:viewframe];
7776 if (animated) [UIView commitAnimations];
7778 // Ensure bar has the proper width for our view, it might have changed
7779 barframe.size.width = viewframe.size.width;
7780 [refreshbar_ setFrame:barframe];
7782 // XXX: fix Apple's layout bug
7783 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7786 - (void) raiseBar:(BOOL)animated {
7787 if (!dropped_) return;
7790 [refreshbar_ removeFromSuperview];
7792 if (animated) [UIView beginAnimations:nil context:NULL];
7793 CGRect barframe = [refreshbar_ frame];
7794 CGRect viewframe = [[root_ view] frame];
7795 viewframe.origin.y -= barframe.size.height;
7796 viewframe.size.height += barframe.size.height;
7797 [[root_ view] setFrame:viewframe];
7798 if (animated) [UIView commitAnimations];
7800 // XXX: fix Apple's layout bug
7801 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7804 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7805 // XXX: fix Apple's layout bug
7806 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7809 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7815 // XXX: fix Apple's layout bug
7816 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7820 [refreshbar_ release];
7824 - (id) initWithDatabase:(Database *)database {
7825 if ((self = [super init]) != nil) {
7826 database_ = database;
7828 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7830 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7847 @interface Cydia : UIApplication <
7848 ConfirmationControllerDelegate,
7849 ProgressControllerDelegate,
7851 UINavigationControllerDelegate
7854 CYContainer *container_;
7858 NSMutableArray *essential_;
7859 NSMutableArray *broken_;
7861 Database *database_;
7865 UIKeyboard *keyboard_;
7866 UIProgressHUD *hud_;
7868 SectionsController *sections_;
7869 ChangesController *changes_;
7870 ManageController *manage_;
7871 SearchController *search_;
7872 SourceTable *sources_;
7873 InstalledController *installed_;
7876 #if RecyclePackageViews
7877 NSMutableArray *details_;
7883 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7884 - (void) setPage:(CYViewController *)page;
7889 static _finline void _setHomePage(Cydia *self) {
7890 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7893 @implementation Cydia
7895 - (void) beginUpdate {
7896 [container_ beginUpdate];
7900 return [container_ updating];
7903 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7908 if ([broken_ count] != 0) {
7909 int count = [broken_ count];
7911 UIAlertView *alert = [[[UIAlertView alloc]
7912 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7913 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7915 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7916 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
7919 [alert setContext:@"fixhalf"];
7921 } else if (!Ignored_ && [essential_ count] != 0) {
7922 int count = [essential_ count];
7924 UIAlertView *alert = [[[UIAlertView alloc]
7925 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7926 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
7928 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
7929 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
7932 [alert setContext:@"upgrade"];
7937 - (void) _saveConfig {
7940 NSString *error(nil);
7941 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7943 NSError *error(nil);
7944 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7945 NSLog(@"failure to save metadata data: %@", error);
7948 NSLog(@"failure to serialize metadata: %@", error);
7956 - (void) _updateData {
7959 /* XXX: this is just stupid */
7960 if (tag_ != 1 && sections_ != nil)
7961 [sections_ reloadData];
7962 if (tag_ != 2 && changes_ != nil)
7963 [changes_ reloadData];
7964 if (tag_ != 4 && search_ != nil)
7965 [search_ reloadData];
7967 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
7970 - (int)indexOfTabWithTag:(int)tag {
7972 for (UINavigationController *controller in [tabbar_ viewControllers]) {
7973 if ([[controller tabBarItem] tag] == tag) return i;
7980 - (void) _refreshIfPossible {
7981 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
7983 SCNetworkReachabilityFlags flags; {
7984 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
7985 SCNetworkReachabilityGetFlags(reachability, &flags);
7986 CFRelease(reachability);
7989 // XXX: this elaborate mess is what Apple is using to determine this? :(
7990 // XXX: do we care if the user has to intervene? maybe that's ok?
7992 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
7993 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
7994 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
7995 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
7996 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
7997 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8001 if (loaded_ || ManualRefresh || !reachable) loaded:
8002 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8006 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8008 if (update != nil) {
8009 NSTimeInterval interval([update timeIntervalSinceNow]);
8010 if (interval <= 0 && interval > -(15*60))
8014 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8020 - (void) refreshIfPossible {
8021 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8024 - (void) _reloadData {
8025 UIProgressHUD *hud([self addProgressHUD]);
8026 [hud setText:(loaded_ ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
8028 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8031 [self removeProgressHUD:hud];
8035 [essential_ removeAllObjects];
8036 [broken_ removeAllObjects];
8038 NSArray *packages([database_ packages]);
8039 for (Package *package in packages) {
8041 [broken_ addObject:package];
8042 if ([package upgradableAndEssential:NO]) {
8043 if ([package essential])
8044 [essential_ addObject:package];
8050 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8051 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:badge];
8052 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:YES];
8054 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8055 [self setApplicationBadge:badge];
8057 [self setApplicationBadgeString:badge];
8059 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:nil];
8060 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:NO];
8062 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8063 [self removeApplicationBadge];
8064 else // XXX: maybe use setApplicationBadgeString also?
8065 [self setApplicationIconBadgeNumber:0];
8070 [self refreshIfPossible];
8073 - (void) updateData {
8074 [database_ setVisible];
8083 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8084 _assert(file != NULL);
8086 for (NSString *key in [Sources_ allKeys]) {
8087 NSDictionary *source([Sources_ objectForKey:key]);
8089 fprintf(file, "%s %s %s\n",
8090 [[source objectForKey:@"Type"] UTF8String],
8091 [[source objectForKey:@"URI"] UTF8String],
8092 [[source objectForKey:@"Distribution"] UTF8String]
8100 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8101 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8102 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8103 [container_ presentModalViewController:navigation animated:YES];
8106 detachNewThreadSelector:@selector(update_)
8109 title:UCLocalize("UPDATING_SOURCES")
8113 - (void) reloadData {
8114 @synchronized (self) {
8120 pkgProblemResolver *resolver = [database_ resolver];
8122 resolver->InstallProtect();
8123 if (!resolver->Resolve(true))
8127 - (CGRect) popUpBounds {
8128 return [[tabbar_ view] bounds];
8132 if (![database_ prepare])
8135 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8136 [page setDelegate:self];
8137 CYNavigationController *confirm_ = [[CYNavigationController alloc] initWithRootViewController:page];
8138 [confirm_ setDelegate:self];
8140 if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8141 [container_ presentModalViewController:confirm_ animated:YES];
8147 @synchronized (self) {
8152 - (void) clearPackage:(Package *)package {
8153 @synchronized (self) {
8160 - (void) installPackages:(NSArray *)packages {
8161 @synchronized (self) {
8162 for (Package *package in packages)
8169 - (void) installPackage:(Package *)package {
8170 @synchronized (self) {
8177 - (void) removePackage:(Package *)package {
8178 @synchronized (self) {
8185 - (void) distUpgrade {
8186 @synchronized (self) {
8187 if (![database_ upgrade])
8194 @synchronized (self) {
8199 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8200 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8202 if (navigation != nil) {
8203 [navigation pushViewController:progress animated:YES];
8205 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8206 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8207 [container_ presentModalViewController:navigation animated:YES];
8211 detachNewThreadSelector:@selector(perform)
8214 title:UCLocalize("RUNNING")
8218 - (void) progressControllerIsComplete:(ProgressController *)progress {
8222 - (void) setPage:(CYViewController *)page {
8223 [page setDelegate:self];
8225 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8226 [navController setViewControllers:[NSArray arrayWithObject:page] animated:NO];
8227 for (CYNavigationController *page in [tabbar_ viewControllers]) {
8228 if (page != navController) [page setViewControllers:nil];
8232 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8233 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8234 [browser loadURL:url];
8238 - (SectionsController *) sectionsController {
8239 if (sections_ == nil)
8240 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8244 - (ChangesController *) changesController {
8245 if (changes_ == nil)
8246 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8250 - (ManageController *) manageController {
8251 if (manage_ == nil) {
8252 manage_ = (ManageController *) [[self
8253 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8254 withClass:[ManageController class]
8256 if (!IsWildcat_) queueDelegate_ = manage_;
8261 - (SearchController *) searchController {
8263 search_ = [[SearchController alloc] initWithDatabase:database_];
8267 - (SourceTable *) sourcesController {
8268 if (sources_ == nil)
8269 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8273 - (InstalledController *) installedController {
8274 if (installed_ == nil) {
8275 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8276 if (IsWildcat_) queueDelegate_ = installed_;
8281 - (void) tabBarController:(id)tabBarController didSelectViewController:(UIViewController *)viewController {
8282 int tag = [[viewController tabBarItem] tag];
8284 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8286 } else if (tag_ == 1) {
8287 [[self sectionsController] resetView];
8291 case kCydiaTag: _setHomePage(self); break;
8293 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8294 case kChangesTag: [self setPage:[self changesController]]; break;
8295 case kManageTag: [self setPage:[self manageController]]; break;
8296 case kInstalledTag: [self setPage:[self installedController]]; break;
8297 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8298 case kSearchTag: [self setPage:[self searchController]]; break;
8306 - (void) showSettings {
8307 RoleController *role = [[RoleController alloc] initWithDatabase:database_ delegate:self];
8308 CYNavigationController *nav = [[CYNavigationController alloc] initWithRootViewController:role];
8309 if (IsWildcat_) [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8310 [container_ presentModalViewController:nav animated:YES];
8313 - (void) setPackageController:(PackageController *)view {
8315 [view setPackage:nil];
8316 #if RecyclePackageViews
8317 if ([details_ count] < 3)
8318 [details_ addObject:view];
8323 - (PackageController *) _packageController {
8324 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8327 - (PackageController *) packageController {
8328 #if RecyclePackageViews
8329 PackageController *view;
8330 size_t count([details_ count]);
8333 view = [self _packageController];
8335 [details_ addObject:[self _packageController]];
8337 view = [[[details_ lastObject] retain] autorelease];
8338 [details_ removeLastObject];
8345 return [self _packageController];
8349 - (void) cancelAndClear:(bool)clear {
8350 @synchronized (self) {
8353 pkgCacheFile &cache([database_ cache]);
8354 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
8355 // Unmark method taken from Synaptic Package Manager.
8356 // Thanks for being sane, unlike Aptitude.
8357 if (!cache[iterator].Keep()) {
8358 cache->MarkKeep(iterator, false);
8359 cache->SetReInstall(iterator, false);
8363 // Stop queuing, and let the appropriate controller know it.
8365 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kManageTag] != -1 ? [self indexOfTabWithTag:kManageTag] : [self indexOfTabWithTag:kInstalledTag]] tabBarItem] setBadgeValue:nil];
8366 [queueDelegate_ queueStatusDidChange];
8368 // Start queuing, and let the controllers know.
8371 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kManageTag] != -1 ? [self indexOfTabWithTag:kManageTag] : [self indexOfTabWithTag:kInstalledTag]] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8372 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8374 [queueDelegate_ queueStatusDidChange];
8379 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8380 NSString *context([alert context]);
8382 if ([context isEqualToString:@"fixhalf"]) {
8383 if (button == [alert firstOtherButtonIndex]) {
8384 @synchronized (self) {
8385 for (Package *broken in broken_) {
8388 NSString *id = [broken id];
8389 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8390 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8391 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8392 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8398 } else if (button == [alert cancelButtonIndex]) {
8399 [broken_ removeAllObjects];
8403 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8404 } else if ([context isEqualToString:@"upgrade"]) {
8405 if (button == [alert firstOtherButtonIndex]) {
8406 @synchronized (self) {
8407 for (Package *essential in essential_)
8408 [essential install];
8413 } else if (button == [alert firstOtherButtonIndex] + 1) {
8415 } else if (button == [alert cancelButtonIndex]) {
8419 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8423 - (void) system:(NSString *)command { _pooled
8424 system([command UTF8String]);
8427 - (void) applicationWillSuspend {
8429 [super applicationWillSuspend];
8432 - (void) applicationSuspend:(__GSEvent *)event {
8433 // FIXME: This needs to be fixed, but we no longer have a progress_.
8434 // What's the best solution?
8435 if (hud_ == nil)// && ![progress_ isRunning])
8436 [super applicationSuspend:event];
8439 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8441 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8444 - (void) _setSuspended:(BOOL)value {
8446 [super _setSuspended:value];
8449 - (UIProgressHUD *) addProgressHUD {
8450 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8451 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8453 [window_ setUserInteractionEnabled:NO];
8455 [[container_ view] addSubview:hud];
8459 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8461 [hud removeFromSuperview];
8462 [window_ setUserInteractionEnabled:YES];
8465 - (CYViewController *) pageForPackage:(NSString *)name {
8466 if (Package *package = [database_ packageWithName:name]) {
8467 PackageController *view([self packageController]);
8468 [view setPackage:package];
8471 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8472 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8473 return [self _pageForURL:url withClass:[CYBrowserController class]];
8477 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8481 NSString *href([url absoluteString]);
8482 if ([href hasPrefix:@"apptapp://package/"])
8483 return [self pageForPackage:[href substringFromIndex:18]];
8485 NSString *scheme([[url scheme] lowercaseString]);
8486 if (![scheme isEqualToString:@"cydia"])
8488 NSString *path([url absoluteString]);
8489 if ([path length] < 8)
8491 path = [path substringFromIndex:8];
8492 if (![path hasPrefix:@"/"])
8493 path = [@"/" stringByAppendingString:path];
8495 if ([path isEqualToString:@"/add-source"])
8496 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8497 else if ([path isEqualToString:@"/storage"])
8498 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8499 else if ([path isEqualToString:@"/sources"])
8500 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8501 else if ([path isEqualToString:@"/packages"])
8502 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8503 else if ([path hasPrefix:@"/url/"])
8504 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8505 else if ([path hasPrefix:@"/launch/"])
8506 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8507 else if ([path hasPrefix:@"/package-settings/"])
8508 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8509 else if ([path hasPrefix:@"/package-signature/"])
8510 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8511 else if ([path hasPrefix:@"/package/"])
8512 return [self pageForPackage:[path substringFromIndex:9]];
8513 else if ([path hasPrefix:@"/files/"]) {
8514 NSString *name = [path substringFromIndex:7];
8516 if (Package *package = [database_ packageWithName:name]) {
8517 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8518 [files setPackage:package];
8526 - (void) applicationOpenURL:(NSURL *)url {
8527 [super applicationOpenURL:url];
8529 if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
8530 [self setPage:page];
8532 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8536 - (void) applicationWillResignActive:(UIApplication *)application {
8537 // Stop refreshing if you get a phone call or lock the device.
8538 if ([container_ updating]) [container_ cancelUpdate];
8540 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8541 [super applicationWillResignActive:application];
8544 - (void) applicationDidFinishLaunching:(id)unused {
8545 [CYBrowserController _initialize];
8547 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8549 Font12_ = [[UIFont systemFontOfSize:12] retain];
8550 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8551 Font14_ = [[UIFont systemFontOfSize:14] retain];
8552 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8553 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8557 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8558 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8560 UIScreen *screen([UIScreen mainScreen]);
8562 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8563 [window_ orderFront:self];
8564 [window_ makeKey:self];
8565 [window_ setHidden:NO];
8567 database_ = [Database sharedInstance];
8570 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8571 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8572 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8573 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8574 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8575 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8576 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8577 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8578 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8581 [self setIdleTimerDisabled:YES];
8583 hud_ = [self addProgressHUD];
8584 [hud_ setText:@"Reorganizing:\n\nWill Automatically\nClose When Done"];
8585 [self setStatusBarShowsProgress:YES];
8587 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8589 [self setStatusBarShowsProgress:NO];
8590 [self removeProgressHUD:hud_];
8593 if (ExecFork() == 0) {
8594 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8595 perror("launchctl stop");
8603 NSMutableArray *items([NSMutableArray arrayWithObjects:
8604 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8605 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8606 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8607 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8611 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8612 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8614 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8617 NSMutableArray *controllers([NSMutableArray array]);
8619 for (UITabBarItem *item in items) {
8620 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8621 [controller setTabBarItem:item];
8622 [controllers addObject:controller];
8625 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8626 [tabbar_ setViewControllers:controllers];
8627 [tabbar_ setDelegate:self];
8628 [tabbar_ setSelectedIndex:0];
8630 container_ = [[CYContainer alloc] initWithDatabase:database_];
8631 [container_ setUpdateDelegate:self];
8632 [container_ setTabBarController:tabbar_];
8633 [window_ addSubview:[container_ view]];
8635 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8640 [self showSettings];
8644 [UIKeyboard initImplementationNow];
8648 #if RecyclePackageViews
8649 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8650 [details_ addObject:[self _packageController]];
8651 [details_ addObject:[self _packageController]];
8659 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8660 if (item != nil && IsWildcat_) {
8661 [sheet showFromBarButtonItem:item animated:YES];
8663 [sheet showInView:window_];
8670 id Alloc_(id self, SEL selector) {
8671 id object = alloc_(self, selector);
8672 lprintf("[%s]A-%p\n", self->isa->name, object);
8677 id Dealloc_(id self, SEL selector) {
8678 id object = dealloc_(self, selector);
8679 lprintf("[%s]D-%p\n", self->isa->name, object);
8683 Class $WebDefaultUIKitDelegate;
8685 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8686 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8687 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8688 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8691 static NSNumber *shouldPlayKeyboardSounds;
8695 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8697 case 1104: // Keyboard Button Clicked
8698 case 1105: // Keyboard Delete Repeated
8699 if (shouldPlayKeyboardSounds == nil) {
8700 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8701 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8704 if (![shouldPlayKeyboardSounds boolValue])
8708 _UIHardware$_playSystemSound$(self, _cmd, sound);
8712 int main(int argc, char *argv[]) { _pooled
8715 if (Class $UIDevice = objc_getClass("UIDevice")) {
8716 UIDevice *device([$UIDevice currentDevice]);
8717 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8721 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8723 /* Library Hacks {{{ */
8724 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8726 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8727 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8728 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8729 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8730 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8733 $UIHardware = objc_getClass("UIHardware");
8734 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8735 if (UIHardware$_playSystemSound$ != NULL) {
8736 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8737 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8740 /* Set Locale {{{ */
8741 Locale_ = CFLocaleCopyCurrent();
8742 Languages_ = [NSLocale preferredLanguages];
8743 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8744 //NSLog(@"%@", [Languages_ description]);
8747 if (Languages_ == nil || [Languages_ count] == 0)
8748 // XXX: consider just setting to C and then falling through?
8751 lang = [[Languages_ objectAtIndex:0] UTF8String];
8752 setenv("LANG", lang, true);
8755 //std::setlocale(LC_ALL, lang);
8756 NSLog(@"Setting Language: %s", lang);
8759 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8761 /* Parse Arguments {{{ */
8762 bool substrate(false);
8768 for (int argi(1); argi != argc; ++argi)
8769 if (strcmp(argv[argi], "--") == 0) {
8771 argv[argi] = argv[0];
8777 for (int argi(1); argi != arge; ++argi)
8778 if (strcmp(args[argi], "--substrate") == 0)
8781 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8785 App_ = [[NSBundle mainBundle] bundlePath];
8786 Home_ = NSHomeDirectory();
8792 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8793 alloc_ = alloc->method_imp;
8794 alloc->method_imp = (IMP) &Alloc_;*/
8796 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8797 dealloc_ = dealloc->method_imp;
8798 dealloc->method_imp = (IMP) &Dealloc_;*/
8800 /* System Information {{{ */
8804 size = sizeof(maxproc);
8805 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8806 perror("sysctlbyname(\"kern.maxproc\", ?)");
8807 else if (maxproc < 64) {
8809 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8810 perror("sysctlbyname(\"kern.maxproc\", #)");
8813 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8814 char *osversion = new char[size];
8815 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8816 perror("sysctlbyname(\"kern.osversion\", ?)");
8818 System_ = [NSString stringWithUTF8String:osversion];
8820 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8821 char *machine = new char[size];
8822 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8823 perror("sysctlbyname(\"hw.machine\", ?)");
8827 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8828 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8829 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8830 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8834 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8835 NSData *data((NSData *) ecid);
8836 size_t length([data length]);
8837 uint8_t bytes[length];
8838 [data getBytes:bytes];
8839 char string[length * 2 + 1];
8840 for (size_t i(0); i != length; ++i)
8841 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8842 ChipID_ = [NSString stringWithUTF8String:string];
8846 IOObjectRelease(service);
8850 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8852 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8853 Build_ = [system objectForKey:@"ProductBuildVersion"];
8854 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8855 Product_ = [info objectForKey:@"SafariProductVersion"];
8856 Safari_ = [info objectForKey:@"CFBundleVersion"];
8859 /* Load Database {{{ */
8861 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8863 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8866 if (Metadata_ == NULL)
8867 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8869 Settings_ = [Metadata_ objectForKey:@"Settings"];
8871 Packages_ = [Metadata_ objectForKey:@"Packages"];
8872 Sections_ = [Metadata_ objectForKey:@"Sections"];
8873 Sources_ = [Metadata_ objectForKey:@"Sources"];
8875 Token_ = [Metadata_ objectForKey:@"Token"];
8878 if (Settings_ != nil)
8879 Role_ = [Settings_ objectForKey:@"Role"];
8881 if (Packages_ == nil) {
8882 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8883 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8886 if (Sections_ == nil) {
8887 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8888 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8891 if (Sources_ == nil) {
8892 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8893 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8898 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8901 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8903 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
8904 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
8905 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8906 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8907 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8908 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8910 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
8912 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8913 unlink("/tmp/.cydia.fw");
8915 } else if (access("/User", F_OK) != 0 || version < 2) {
8918 system("/usr/libexec/cydia/firmware.sh");
8922 _assert([[NSFileManager defaultManager]
8923 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8924 withIntermediateDirectories:YES
8929 if (access("/tmp/cydia.chk", F_OK) == 0) {
8930 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8931 _assert(errno == ENOENT);
8932 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8933 _assert(errno == ENOENT);
8936 /* APT Initialization {{{ */
8937 _assert(pkgInitConfig(*_config));
8938 _assert(pkgInitSystem(*_config, _system));
8941 _config->Set("APT::Acquire::Translation", lang);
8942 _config->Set("Acquire::http::Timeout", 15);
8943 _config->Set("Acquire::http::MaxParallel", 3);
8945 /* Color Choices {{{ */
8946 space_ = CGColorSpaceCreateDeviceRGB();
8948 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8949 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8950 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8951 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8952 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8953 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8954 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8955 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8956 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8958 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8959 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8961 /* UIKit Configuration {{{ */
8962 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8963 if ($GSFontSetUseLegacyFontMetrics != NULL)
8964 $GSFontSetUseLegacyFontMetrics(YES);
8966 // XXX: I have a feeling this was important
8967 //UIKeyboardDisableAutomaticAppearance();
8970 Colon_ = UCLocalize("COLON_DELIMITED");
8971 Error_ = UCLocalize("ERROR");
8972 Warning_ = UCLocalize("WARNING");
8975 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
8977 CGColorSpaceRelease(space_);