1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 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>
105 #include <sys/reboot.h>
112 #include <mach-o/nlist.h>
122 #include <Cytore.hpp>
124 #include "UICaboodle/BrowserView.h"
125 #include "SDURLCache/SDURLCache.h"
127 #include "substrate.h"
136 #define _timestamp ({ \
138 gettimeofday(&tv, NULL); \
139 tv.tv_sec * 1000000 + tv.tv_usec; \
142 typedef std::vector<class ProfileTime *> TimeList;
152 ProfileTime(const char *name) :
156 times_.push_back(this);
159 void AddTime(uint64_t time) {
166 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
178 ProfileTimer(ProfileTime &time) :
185 time_.AddTime(_timestamp - start_);
190 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
192 std::cerr << "========" << std::endl;
195 #define _profile(name) { \
196 static ProfileTime name(#name); \
197 ProfileTimer _ ## name(name);
202 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
204 #define CYPoolStart() \
205 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
207 #define CYPoolEnd() \
211 // Hash Functions/Structures {{{
212 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
220 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
222 static _finline NSString *CydiaURL(NSString *path) {
224 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
225 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
226 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
227 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
228 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
230 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
233 static _finline void UpdateExternalStatus(uint64_t newStatus) {
235 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
236 notify_set_state(notify_token, newStatus);
237 notify_cancel(notify_token);
239 notify_post("com.saurik.Cydia.status");
242 /* [NSObject yieldToSelector:(withObject:)] {{{*/
243 @interface NSObject (Cydia)
244 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
245 - (id) yieldToSelector:(SEL)selector;
248 @implementation NSObject (Cydia)
253 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
254 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
255 id object([[context objectAtIndex:1] nonretainedObjectValue]);
256 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
258 /* XXX: deal with exceptions */
259 id value([self performSelector:selector withObject:object]);
261 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
262 [context removeAllObjects];
263 if ([signature methodReturnLength] != 0 && value != nil)
264 [context addObject:value];
269 performSelectorOnMainThread:@selector(doNothing)
275 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
276 volatile bool stopped(false);
278 NSMutableArray *context([NSMutableArray arrayWithObjects:
279 [NSValue valueWithPointer:selector],
280 [NSValue valueWithNonretainedObject:object],
281 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
284 NSThread *thread([[[NSThread alloc]
286 selector:@selector(_yieldToContext:)
292 NSRunLoop *loop([NSRunLoop currentRunLoop]);
293 NSDate *future([NSDate distantFuture]);
294 NSString *mode([loop currentMode] ?: NSDefaultRunLoopMode);
296 while (!stopped && [loop runMode:mode beforeDate:future]);
298 return [context count] == 0 ? nil : [context objectAtIndex:0];
301 - (id) yieldToSelector:(SEL)selector {
302 return [self yieldToSelector:selector withObject:nil];
308 /* Cydia Alert View {{{ */
309 @interface CYAlertView : UIAlertView {
313 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
317 @implementation CYAlertView
319 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
320 if ((self = [super init]) != nil) {
321 [self setTitle:title];
322 [self setDelegate:self];
323 for (NSString *button in buttons) [self addButtonWithTitle:button];
324 [self setCancelButtonIndex:index];
328 - (void) _updateFrameForDisplay {
329 [super _updateFrameForDisplay];
330 if ([self cancelButtonIndex] == -1) {
331 NSArray *buttons = [self buttons];
332 if ([buttons count]) {
333 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
334 for (UIThreePartButton *button in buttons)
335 [button setBackground:background forState:0];
340 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
341 button_ = buttonIndex + 1;
345 [self dismissWithClickedButtonIndex:-1 animated:YES];
348 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
349 [self setRunsModal:YES];
358 /* NSForcedOrderingSearch doesn't work on the iPhone */
359 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
360 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
361 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
363 #define lprintf(args...) fprintf(stderr, args)
366 #define TraceLogging (1 && !ForRelease)
367 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
368 #define ProfileTimes (0 && !ForRelease)
369 #define ForSaurik (0 && !ForRelease)
370 #define LogBrowser (0 && !ForRelease)
371 #define TrackResize (0 && !ForRelease)
372 #define ManualRefresh (1 && !ForRelease)
373 #define ShowInternals (0 && !ForRelease)
374 #define AlwaysReload (0 && !ForRelease)
375 #define TryIndexedCollation (0 && !ForRelease)
379 #define _trace(args...)
384 #define _profile(name) {
387 #define PrintTimes() do {} while (false)
391 typedef uint32_t (*SKRadixFunction)(id, void *);
393 @interface NSMutableArray (Radix)
394 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
402 @implementation NSMutableArray (Radix)
404 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
405 size_t count([self count]);
406 struct RadixItem_ *swap(new RadixItem_[count * 2]);
408 for (size_t i(0); i != count; ++i) {
409 RadixItem_ &item(swap[i]);
412 id object([self objectAtIndex:i]);
413 item.key = function(object, argument);
416 struct RadixItem_ *lhs(swap), *rhs(swap + count);
418 static const size_t width = 32;
419 static const size_t bits = 11;
420 static const size_t slots = 1 << bits;
421 static const size_t passes = (width + (bits - 1)) / bits;
423 size_t *hist(new size_t[slots]);
425 for (size_t pass(0); pass != passes; ++pass) {
426 memset(hist, 0, sizeof(size_t) * slots);
428 for (size_t i(0); i != count; ++i) {
429 uint32_t key(lhs[i].key);
431 key &= _not(uint32_t) >> width - bits;
436 for (size_t i(0); i != slots; ++i) {
437 size_t local(offset);
442 for (size_t i(0); i != count; ++i) {
443 uint32_t key(lhs[i].key);
445 key &= _not(uint32_t) >> width - bits;
446 rhs[hist[key]++] = lhs[i];
449 RadixItem_ *tmp(lhs);
456 const void **values(new const void *[count]);
457 for (size_t i(0); i != count; ++i)
458 values[i] = [self objectAtIndex:lhs[i].index];
459 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
467 /* Insertion Sort {{{ */
469 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
470 const char *ptr = (const char *)list;
472 CFIndex half = count / 2;
473 const char *probe = ptr + elementSize * half;
474 CFComparisonResult cr = comparator(element, probe, context);
475 if (0 == cr) return (probe - (const char *)list) / elementSize;
476 ptr = (cr < 0) ? ptr : probe + elementSize;
477 count = (cr < 0) ? half : (half + (count & 1) - 1);
479 return (ptr - (const char *)list) / elementSize;
482 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
483 const char *ptr = (const char *)list;
485 CFIndex half = count / 2;
486 const char *probe = ptr + elementSize * half;
487 CFComparisonResult cr = comparator(element, probe, context);
488 if (0 == cr) return (probe - (const char *)list) / elementSize;
489 ptr = (cr < 0) ? ptr : probe + elementSize;
490 count = (cr < 0) ? half : (half + (count & 1) - 1);
492 return (ptr - (const char *)list) / elementSize;
495 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
496 if (range.length == 0)
498 const void **values(new const void *[range.length]);
499 CFArrayGetValues(array, range, values);
501 #if HistogramInsertionSort > 0
502 uint32_t total(0), *offsets(new uint32_t[range.length]);
505 for (CFIndex index(1); index != range.length; ++index) {
506 const void *value(values[index]);
507 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
508 CFIndex correct(index);
509 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
510 #if HistogramInsertionSort > 1
511 NSLog(@"%@ < %@", value, values[correct - 1]);
516 if (correct != index) {
517 size_t offset(index - correct);
518 #if HistogramInsertionSort
522 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
524 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
525 values[correct] = value;
529 CFArrayReplaceValues(array, range, values, range.length);
532 #if HistogramInsertionSort > 0
533 for (CFIndex index(0); index != range.length; ++index)
534 if (offsets[index] != 0)
535 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
536 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
543 /* Apple Bug Fixes {{{ */
544 @implementation UIWebDocumentView (Cydia)
546 - (void) _setScrollerOffset:(CGPoint)offset {
547 UIScroller *scroller([self _scroller]);
549 CGSize size([scroller contentSize]);
550 CGSize bounds([scroller bounds].size);
553 max.x = size.width - bounds.width;
554 max.y = size.height - bounds.height;
562 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
563 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
565 [scroller setOffset:offset];
571 @interface NSInvocation (Cydia)
572 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target;
575 @implementation NSInvocation (Cydia)
577 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target {
578 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[target methodSignatureForSelector:selector]]);
579 [invocation setTarget:target];
580 [invocation setSelector:selector];
586 @implementation WebScriptObject (NSFastEnumeration)
588 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
589 size_t length([self count] - state->state);
592 else if (length > count)
594 for (size_t i(0); i != length; ++i)
595 objects[i] = [self objectAtIndex:state->state++];
596 state->itemsPtr = objects;
597 state->mutationsPtr = (unsigned long *) self;
603 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
604 size_t length([self length] - state->state);
607 else if (length > count)
609 for (size_t i(0); i != length; ++i)
610 objects[i] = [self item:state->state++];
611 state->itemsPtr = objects;
612 state->mutationsPtr = (unsigned long *) self;
616 /* Cydia NSString Additions {{{ */
617 @interface NSString (Cydia)
618 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
619 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
620 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
621 - (NSComparisonResult) compareByPath:(NSString *)other;
622 - (NSString *) stringByCachingURLWithCurrentCDN;
623 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
626 @implementation NSString (Cydia)
628 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
629 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
632 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
633 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
634 memcpy(data, bytes, length);
635 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
638 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
639 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
642 - (NSComparisonResult) compareByPath:(NSString *)other {
643 NSString *prefix = [self commonPrefixWithString:other options:0];
644 size_t length = [prefix length];
646 NSRange lrange = NSMakeRange(length, [self length] - length);
647 NSRange rrange = NSMakeRange(length, [other length] - length);
649 lrange = [self rangeOfString:@"/" options:0 range:lrange];
650 rrange = [other rangeOfString:@"/" options:0 range:rrange];
652 NSComparisonResult value;
654 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
655 value = NSOrderedSame;
656 else if (lrange.location == NSNotFound)
657 value = NSOrderedAscending;
658 else if (rrange.location == NSNotFound)
659 value = NSOrderedDescending;
661 value = NSOrderedSame;
663 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
664 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
665 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
666 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
668 NSComparisonResult result = [lpath compare:rpath];
669 return result == NSOrderedSame ? value : result;
672 - (NSString *) stringByCachingURLWithCurrentCDN {
674 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
675 withString:@"://cache.cydia.saurik.com/"
679 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
680 return [(id)CFURLCreateStringByAddingPercentEscapes(
685 kCFStringEncodingUTF8
692 /* C++ NSString Wrapper Cache {{{ */
693 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
694 return size == 0 ? NULL :
695 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
696 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
699 static _finline CFStringRef CYStringCreate(const char *data) {
700 return CYStringCreate(data, strlen(data));
709 _finline void clear_() {
710 if (cache_ != NULL) {
717 _finline bool empty() const {
721 _finline size_t size() const {
725 _finline char *data() const {
729 _finline void clear() {
734 _finline CYString() :
741 _finline ~CYString() {
745 void operator =(const CYString &rhs) {
749 if (rhs.cache_ == nil)
752 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
755 void copy(apr_pool_t *pool) {
756 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
757 memcpy(temp, data_, size_);
762 void set(apr_pool_t *pool, const char *data, size_t size) {
768 data_ = const_cast<char *>(data);
776 _finline void set(apr_pool_t *pool, const char *data) {
777 set(pool, data, data == NULL ? 0 : strlen(data));
780 _finline void set(apr_pool_t *pool, const std::string &rhs) {
781 set(pool, rhs.data(), rhs.size());
784 bool operator ==(const CYString &rhs) const {
785 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
788 _finline operator CFStringRef() {
790 cache_ = CYStringCreate(data_, size_);
794 _finline operator id() {
795 return (NSString *) static_cast<CFStringRef>(*this);
798 _finline operator const char *() {
799 return reinterpret_cast<const char *>(data_);
803 /* C++ NSString Algorithm Adapters {{{ */
805 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
808 struct NSStringMapHash :
809 std::unary_function<NSString *, size_t>
811 _finline size_t operator ()(NSString *value) const {
812 return CFStringHashNSString((CFStringRef) value);
816 struct NSStringMapLess :
817 std::binary_function<NSString *, NSString *, bool>
819 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
820 return [lhs compare:rhs] == NSOrderedAscending;
824 struct NSStringMapEqual :
825 std::binary_function<NSString *, NSString *, bool>
827 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
828 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
829 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
830 //[lhs isEqualToString:rhs];
835 /* Perl-Compatible RegEx {{{ */
845 Pcre(const char *regex) :
850 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
853 lprintf("%d:%s\n", offset, error);
857 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
858 matches_ = new int[(capture_ + 1) * 3];
866 NSString *operator [](size_t match) {
867 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
870 bool operator ()(NSString *data) {
871 // XXX: length is for characters, not for bytes
872 return operator ()([data UTF8String], [data length]);
875 bool operator ()(const char *data, size_t size) {
877 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
881 /* Mime Addresses {{{ */
882 @interface Address : NSObject {
888 - (NSString *) address;
890 - (void) setAddress:(NSString *)address;
892 + (Address *) addressWithString:(NSString *)string;
893 - (Address *) initWithString:(NSString *)string;
897 @implementation Address
906 - (NSString *) name {
910 - (NSString *) address {
914 - (void) setAddress:(NSString *)address {
916 [address_ autorelease];
920 address_ = [address retain];
923 + (Address *) addressWithString:(NSString *)string {
924 return [[[Address alloc] initWithString:string] autorelease];
927 + (NSArray *) _attributeKeys {
928 return [NSArray arrayWithObjects:
934 - (NSArray *) attributeKeys {
935 return [[self class] _attributeKeys];
938 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
939 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
942 - (Address *) initWithString:(NSString *)string {
943 if ((self = [super init]) != nil) {
944 const char *data = [string UTF8String];
945 size_t size = [string length];
947 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
949 if (address_r(data, size)) {
950 name_ = [address_r[1] retain];
951 address_ = [address_r[2] retain];
953 name_ = [string retain];
961 /* CoreGraphics Primitives {{{ */
966 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
967 CGFloat color[] = {red, green, blue, alpha};
968 return CGColorCreate(space, color);
977 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
978 color_(Create_(space, red, green, blue, alpha))
980 Set(space, red, green, blue, alpha);
985 CGColorRelease(color_);
992 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
994 color_ = Create_(space, red, green, blue, alpha);
997 operator CGColorRef() {
1003 /* Random Global Variables {{{ */
1004 static const int PulseInterval_ = 50000;
1006 static const NSString *UI_;
1009 static bool RestartSubstrate_;
1010 static NSArray *Finishes_;
1012 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1013 #define NotifyConfig_ "/etc/notify.conf"
1015 static bool Queuing_;
1017 static CYColor Blue_;
1018 static CYColor Blueish_;
1019 static CYColor Black_;
1020 static CYColor Off_;
1021 static CYColor White_;
1022 static CYColor Gray_;
1023 static CYColor Green_;
1024 static CYColor Purple_;
1025 static CYColor Purplish_;
1027 static UIColor *InstallingColor_;
1028 static UIColor *RemovingColor_;
1030 static NSString *App_;
1032 static BOOL Advanced_;
1033 static BOOL Ignored_;
1035 static UIFont *Font12_;
1036 static UIFont *Font12Bold_;
1037 static UIFont *Font14_;
1038 static UIFont *Font18Bold_;
1039 static UIFont *Font22Bold_;
1041 static const char *Machine_ = NULL;
1042 static NSString *System_ = nil;
1043 static NSString *SerialNumber_ = nil;
1044 static NSString *ChipID_ = nil;
1045 static _H<NSString> Token_;
1046 static NSString *UniqueID_ = nil;
1047 static NSString *PLMN_ = nil;
1048 static NSString *Build_ = nil;
1049 static NSString *Product_ = nil;
1050 static NSString *Safari_ = nil;
1052 static CFLocaleRef Locale_;
1053 static NSArray *Languages_;
1054 static CGColorSpaceRef space_;
1056 static NSDictionary *SectionMap_;
1057 static NSMutableDictionary *Metadata_;
1058 static _transient NSMutableDictionary *Settings_;
1059 static _transient NSString *Role_;
1060 static _transient NSMutableDictionary *Packages_;
1061 static _transient NSMutableDictionary *Sections_;
1062 static _transient NSMutableDictionary *Sources_;
1063 static bool Changed_;
1067 static CGFloat ScreenScale_;
1068 static NSString *Idiom_;
1071 /* Display Helpers {{{ */
1072 inline float Interpolate(float begin, float end, float fraction) {
1073 return (end - begin) * fraction + begin;
1076 static _finline const char *StripVersion_(const char *version) {
1077 const char *colon(strchr(version, ':'));
1078 return colon == NULL ? version : colon + 1;
1081 NSString *LocalizeSection(NSString *section) {
1082 static Pcre title_r("^(.*?) \\((.*)\\)$");
1083 if (title_r(section)) {
1084 NSString *parent(title_r[1]);
1085 NSString *child(title_r[2]);
1087 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1088 LocalizeSection(parent),
1089 LocalizeSection(child)
1093 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1096 NSString *Simplify(NSString *title) {
1097 const char *data = [title UTF8String];
1098 size_t size = [title length];
1100 static Pcre square_r("^\\[(.*)\\]$");
1101 if (square_r(data, size))
1102 return Simplify(square_r[1]);
1104 static Pcre paren_r("^\\((.*)\\)$");
1105 if (paren_r(data, size))
1106 return Simplify(paren_r[1]);
1108 static Pcre title_r("^(.*?) \\((.*)\\)$");
1109 if (title_r(data, size))
1110 return Simplify(title_r[1]);
1116 NSString *GetLastUpdate() {
1117 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1120 return UCLocalize("NEVER_OR_UNKNOWN");
1122 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1123 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1125 CFRelease(formatter);
1127 return [(NSString *) formatted autorelease];
1130 bool isSectionVisible(NSString *section) {
1131 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1132 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1133 return hidden == nil || ![hidden boolValue];
1138 /* Delegate Prototypes {{{ */
1141 @class CydiaProgressEvent;
1143 @protocol DatabaseDelegate
1144 - (void) repairWithSelector:(SEL)selector;
1145 - (void) setConfigurationData:(NSString *)data;
1146 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
1149 @class CYPackageController;
1151 @protocol CydiaDelegate
1152 - (void) retainNetworkActivityIndicator;
1153 - (void) releaseNetworkActivityIndicator;
1154 - (void) clearPackage:(Package *)package;
1155 - (void) installPackage:(Package *)package;
1156 - (void) installPackages:(NSArray *)packages;
1157 - (void) removePackage:(Package *)package;
1158 - (void) beginUpdate;
1160 - (void) distUpgrade;
1162 - (void) updateData;
1164 - (void) addTrivialSource:(NSString *)href;
1165 - (void) showSettings;
1166 - (UIProgressHUD *) addProgressHUD;
1167 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1168 - (CYViewController *) pageForPackage:(NSString *)name;
1169 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1170 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1174 /* ProgressEvent Interface/Delegate {{{ */
1175 @interface CydiaProgressEvent : NSObject {
1176 _H<NSString> message_;
1180 _H<NSString> package_;
1182 _H<NSString> version_;
1185 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type;
1186 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package;
1187 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item;
1189 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type;
1191 - (NSString *) message;
1192 - (NSString *) type;
1195 - (NSString *) package;
1197 - (NSString *) version;
1199 - (void) setItem:(NSArray *)item;
1200 - (void) setPackage:(NSString *)package;
1201 - (void) setURL:(NSString *)url;
1202 - (void) setVersion:(NSString *)version;
1204 - (NSString *) compound:(NSString *)value;
1205 - (NSString *) compoundMessage;
1206 - (NSString *) compoundTitle;
1210 @protocol ProgressDelegate
1211 - (void) addProgressEvent:(CydiaProgressEvent *)event;
1212 - (void) setProgressPercent:(NSNumber *)percent;
1213 - (void) setProgressStatus:(NSDictionary *)status;
1214 - (void) setProgressCancellable:(NSNumber *)cancellable;
1215 - (bool) isProgressCancelled;
1216 - (void) setTitle:(NSString *)title;
1219 /* Status Delegation {{{ */
1221 public pkgAcquireStatus
1224 _transient NSObject<ProgressDelegate> *delegate_;
1234 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1235 delegate_ = delegate;
1238 NSObject<ProgressDelegate> *getDelegate() const {
1242 virtual bool MediaChange(std::string media, std::string drive) {
1246 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1249 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1250 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1251 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:@"STATUS" forItem:item]);
1252 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1255 virtual void Done(pkgAcquire::ItemDesc &item) {
1258 virtual void Fail(pkgAcquire::ItemDesc &item) {
1260 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1261 item.Owner->Status == pkgAcquire::Item::StatDone
1265 std::string &error(item.Owner->ErrorText);
1269 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:@"ERROR" forItem:item]);
1270 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1273 virtual bool Pulse(pkgAcquire *Owner) {
1274 bool value = pkgAcquireStatus::Pulse(Owner);
1277 double(CurrentBytes + CurrentItems) /
1278 double(TotalBytes + TotalItems)
1281 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1282 [NSNumber numberWithDouble:percent], @"Percent",
1284 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1285 [NSNumber numberWithDouble:TotalBytes], @"Total",
1286 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1287 nil] waitUntilDone:YES];
1289 if (value && ![delegate_ isProgressCancelled])
1297 _finline bool WasCancelled() const {
1301 virtual void Start() {
1302 pkgAcquireStatus::Start();
1303 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1306 virtual void Stop() {
1307 pkgAcquireStatus::Stop();
1308 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1309 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1313 /* Database Interface {{{ */
1314 typedef std::map< unsigned long, _H<Source> > SourceMap;
1316 @interface Database : NSObject {
1322 pkgCacheFile cache_;
1323 pkgDepCache::Policy *policy_;
1324 pkgRecords *records_;
1325 pkgProblemResolver *resolver_;
1326 pkgAcquire *fetcher_;
1328 SPtr<pkgPackageManager> manager_;
1329 pkgSourceList *list_;
1331 SourceMap sourceMap_;
1332 NSMutableArray *sourceList_;
1334 CFMutableArrayRef packages_;
1336 _transient NSObject<DatabaseDelegate> *delegate_;
1337 _transient NSObject<ProgressDelegate> *progress_;
1345 std::map<const char *, _H<NSString> > sections_;
1348 + (Database *) sharedInstance;
1351 - (void) _readCydia:(NSNumber *)fd;
1352 - (void) _readStatus:(NSNumber *)fd;
1353 - (void) _readOutput:(NSNumber *)fd;
1357 - (Package *) packageWithName:(NSString *)name;
1359 - (pkgCacheFile &) cache;
1360 - (pkgDepCache::Policy *) policy;
1361 - (pkgRecords *) records;
1362 - (pkgProblemResolver *) resolver;
1363 - (pkgAcquire &) fetcher;
1364 - (pkgSourceList &) list;
1365 - (NSArray *) packages;
1366 - (NSArray *) sources;
1367 - (Source *) sourceWithKey:(NSString *)key;
1368 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1376 - (void) updateWithStatus:(Status &)status;
1378 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1380 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1381 - (NSObject<ProgressDelegate> *) progressDelegate;
1383 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1385 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1389 /* ProgressEvent Implementation {{{ */
1390 @implementation CydiaProgressEvent
1392 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1393 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1396 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1397 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1398 [event setPackage:package];
1402 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1403 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1405 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1406 NSArray *fields([description componentsSeparatedByString:@" "]);
1407 [event setItem:fields];
1409 if ([fields count] > 3) {
1410 [event setPackage:[fields objectAtIndex:2]];
1411 [event setVersion:[fields objectAtIndex:3]];
1414 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1419 + (NSArray *) _attributeKeys {
1420 return [NSArray arrayWithObjects:
1430 - (NSArray *) attributeKeys {
1431 return [[self class] _attributeKeys];
1434 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1435 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1438 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1439 if ((self = [super init]) != nil) {
1445 - (NSString *) message {
1449 - (NSString *) type {
1453 - (NSArray *) item {
1454 return (id) item_ ?: [NSNull null];
1457 - (void) setItem:(NSArray *)item {
1461 - (NSString *) package {
1462 return (id) package_ ?: [NSNull null];
1465 - (void) setPackage:(NSString *)package {
1469 - (NSString *) url {
1470 return (id) url_ ?: [NSNull null];
1473 - (void) setURL:(NSString *)url {
1477 - (void) setVersion:(NSString *)version {
1481 - (NSString *) version {
1482 return (id) version_ ?: [NSNull null];
1485 - (NSString *) compound:(NSString *)value {
1487 NSString *mode(nil); {
1488 NSString *type([self type]);
1489 if ([type isEqualToString:@"ERROR"])
1490 mode = UCLocalize("ERROR");
1491 else if ([type isEqualToString:@"WARNING"])
1492 mode = UCLocalize("WARNING");
1496 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1502 - (NSString *) compoundMessage {
1503 return [self compound:[self message]];
1506 - (NSString *) compoundTitle {
1509 if (package_ == nil)
1511 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1512 title = [package name];
1516 return [self compound:title];
1522 // Cytore Definitions {{{
1523 struct PackageValue :
1526 Cytore::Offset<PackageValue> next_;
1528 uint32_t index_ : 23;
1529 uint32_t subscribed_ : 1;
1546 Cytore::Offset<PackageValue> packages_[1 << 16];
1549 static Cytore::File<MetaValue> MetaFile_;
1551 // Cytore Helper Functions {{{
1552 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1553 SplitHash nhash = { hashlittle(name, length) };
1555 PackageValue *metadata;
1557 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1558 offset: if (offset->IsNull()) {
1559 *offset = MetaFile_.New<PackageValue>(length + 1);
1560 metadata = &MetaFile_.Get(*offset);
1562 if (metadata == NULL) {
1566 metadata = new PackageValue();
1567 memset(metadata, 0, sizeof(*metadata));
1570 memcpy(metadata->name_, name, length + 1);
1571 metadata->nhash_ = nhash.u16[1];
1573 metadata = &MetaFile_.Get(*offset);
1575 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1576 offset = &metadata->next_;
1584 static void PackageImport(const void *key, const void *value, void *context) {
1585 bool &fail(*reinterpret_cast<bool *>(context));
1588 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1589 NSLog(@"failed to import package %@", key);
1593 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1594 NSDictionary *package((NSDictionary *) value);
1596 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1597 if ([subscribed boolValue] && !metadata->subscribed_)
1598 metadata->subscribed_ = true;
1600 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1601 time_t time([date timeIntervalSince1970]);
1602 if (metadata->first_ > time || metadata->first_ == 0)
1603 metadata->first_ = time;
1606 NSDate *date([package objectForKey:@"LastSeen"]);
1607 NSString *version([package objectForKey:@"LastVersion"]);
1609 if (date != nil && version != nil) {
1610 time_t time([date timeIntervalSince1970]);
1611 if (metadata->last_ < time || metadata->last_ == 0)
1612 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1613 size_t length(strlen(buffer));
1614 uint16_t vhash(hashlittle(buffer, length));
1616 size_t capped(std::min<size_t>(8, length));
1617 char *latest(buffer + length - capped);
1619 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1620 metadata->vhash_ = vhash;
1622 metadata->last_ = time;
1628 /* Source Class {{{ */
1629 @interface Source : NSObject {
1630 CYString depiction_;
1631 CYString description_;
1637 CYString distribution_;
1642 _H<NSString> authority_;
1644 CYString defaultIcon_;
1646 _H<NSDictionary> record_;
1650 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1652 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1654 - (NSString *) depictionForPackage:(NSString *)package;
1655 - (NSString *) supportForPackage:(NSString *)package;
1657 - (NSDictionary *) record;
1661 - (NSString *) distribution;
1662 - (NSString *) type;
1664 - (NSString *) host;
1666 - (NSString *) name;
1667 - (NSString *) description;
1668 - (NSString *) label;
1669 - (NSString *) origin;
1670 - (NSString *) version;
1672 - (NSString *) defaultIcon;
1676 @implementation Source
1680 distribution_.clear();
1683 description_.clear();
1689 defaultIcon_.clear();
1697 // XXX: this is a very inefficient way to call these deconstructors
1702 + (NSArray *) _attributeKeys {
1703 return [NSArray arrayWithObjects:
1718 - (NSArray *) attributeKeys {
1719 return [[self class] _attributeKeys];
1722 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1723 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1726 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1729 trusted_ = index->IsTrusted();
1731 uri_.set(pool, index->GetURI());
1732 distribution_.set(pool, index->GetDist());
1733 type_.set(pool, index->GetType());
1735 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1736 if (dindex != NULL) {
1738 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1741 pkgTagFile tags(&fd);
1743 pkgTagSection section;
1750 {"default-icon", &defaultIcon_},
1751 {"depiction", &depiction_},
1752 {"description", &description_},
1754 {"origin", &origin_},
1755 {"support", &support_},
1756 {"version", &version_},
1759 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1760 const char *start, *end;
1762 if (section.Find(names[i].name_, start, end)) {
1763 CYString &value(*names[i].value_);
1764 value.set(pool, start, end - start);
1770 record_ = [Sources_ objectForKey:[self key]];
1772 NSURL *url([NSURL URLWithString:uri_]);
1776 host_ = [host_ lowercaseString];
1779 // XXX: this is due to a bug in _H<>
1780 authority_ = (id) host_;
1782 authority_ = [url path];
1785 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1786 if ((self = [super init]) != nil) {
1787 [self setMetaIndex:index inPool:pool];
1791 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1792 NSDictionary *lhr = [self record];
1793 NSDictionary *rhr = [source record];
1796 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1798 NSString *lhs = [self name];
1799 NSString *rhs = [source name];
1801 if ([lhs length] != 0 && [rhs length] != 0) {
1802 unichar lhc = [lhs characterAtIndex:0];
1803 unichar rhc = [rhs characterAtIndex:0];
1805 if (isalpha(lhc) && !isalpha(rhc))
1806 return NSOrderedAscending;
1807 else if (!isalpha(lhc) && isalpha(rhc))
1808 return NSOrderedDescending;
1811 return [lhs compare:rhs options:LaxCompareOptions_];
1814 - (NSString *) depictionForPackage:(NSString *)package {
1815 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1818 - (NSString *) supportForPackage:(NSString *)package {
1819 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1822 - (NSDictionary *) record {
1830 - (NSString *) uri {
1834 - (NSString *) distribution {
1835 return distribution_;
1838 - (NSString *) type {
1842 - (NSString *) key {
1843 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1846 - (NSString *) host {
1850 - (NSString *) name {
1851 return origin_.empty() ? (id) authority_ : origin_;
1854 - (NSString *) description {
1855 return description_;
1858 - (NSString *) label {
1859 return label_.empty() ? (id) authority_ : label_;
1862 - (NSString *) origin {
1866 - (NSString *) version {
1870 - (NSString *) defaultIcon {
1871 return defaultIcon_;
1876 /* CydiaOperation Class {{{ */
1877 @interface CydiaOperation : NSObject {
1878 NSString *operator_;
1882 - (NSString *) operator;
1883 - (NSString *) value;
1887 @implementation CydiaOperation
1890 [operator_ release];
1895 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1896 if ((self = [super init]) != nil) {
1897 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1898 value_ = [[NSString alloc] initWithUTF8String:value];
1902 + (NSArray *) _attributeKeys {
1903 return [NSArray arrayWithObjects:
1909 - (NSArray *) attributeKeys {
1910 return [[self class] _attributeKeys];
1913 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1914 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1917 - (NSString *) operator {
1921 - (NSString *) value {
1927 /* CydiaClause Class {{{ */
1928 @interface CydiaClause : NSObject {
1930 CydiaOperation *version_;
1933 - (NSString *) package;
1934 - (CydiaOperation *) version;
1938 @implementation CydiaClause
1946 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1947 if ((self = [super init]) != nil) {
1948 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1950 if (const char *version = dep.TargetVer())
1951 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1953 version_ = [[NSNull null] retain];
1957 + (NSArray *) _attributeKeys {
1958 return [NSArray arrayWithObjects:
1964 - (NSArray *) attributeKeys {
1965 return [[self class] _attributeKeys];
1968 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1969 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1972 - (NSString *) package {
1976 - (CydiaOperation *) version {
1982 /* CydiaRelation Class {{{ */
1983 @interface CydiaRelation : NSObject {
1984 NSString *relationship_;
1985 NSMutableArray *clauses_;
1988 - (NSString *) relationship;
1989 - (NSArray *) clauses;
1993 @implementation CydiaRelation
1996 [relationship_ release];
2001 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2002 if ((self = [super init]) != nil) {
2003 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
2004 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
2006 pkgCache::DepIterator start;
2007 pkgCache::DepIterator end;
2008 dep.GlobOr(start, end); // ++dep
2011 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2013 // yes, seriously. (wtf?)
2021 + (NSArray *) _attributeKeys {
2022 return [NSArray arrayWithObjects:
2028 - (NSArray *) attributeKeys {
2029 return [[self class] _attributeKeys];
2032 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2033 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2036 - (NSString *) relationship {
2037 return relationship_;
2040 - (NSArray *) clauses {
2044 - (void) addClause:(CydiaClause *)clause {
2045 [clauses_ addObject:clause];
2050 /* Package Class {{{ */
2051 struct ParsedPackage {
2056 CYString depiction_;
2066 @interface Package : NSObject {
2069 uint32_t essential_ : 1;
2070 uint32_t obsolete_ : 1;
2071 uint32_t ignored_ : 1;
2075 _transient Database *database_;
2077 pkgCache::VerIterator version_;
2078 pkgCache::PkgIterator iterator_;
2079 pkgCache::VerFileIterator file_;
2085 CYString installed_;
2087 const char *section_;
2088 _transient NSString *section$_;
2092 PackageValue *metadata_;
2093 ParsedPackage *parsed_;
2095 NSMutableArray *tags_;
2098 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2099 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2101 - (pkgCache::PkgIterator) iterator;
2104 - (NSString *) section;
2105 - (NSString *) simpleSection;
2107 - (NSString *) longSection;
2108 - (NSString *) shortSection;
2112 - (Address *) maintainer;
2114 - (NSString *) longDescription;
2115 - (NSString *) shortDescription;
2118 - (PackageValue *) metadata;
2121 - (bool) subscribed;
2122 - (bool) setSubscribed:(bool)subscribed;
2126 - (NSString *) latest;
2127 - (NSString *) installed;
2128 - (BOOL) uninstalled;
2131 - (BOOL) upgradableAndEssential:(BOOL)essential;
2134 - (BOOL) unfiltered;
2138 - (BOOL) halfConfigured;
2139 - (BOOL) halfInstalled;
2141 - (NSString *) mode;
2144 - (NSString *) name;
2146 - (NSString *) homepage;
2147 - (NSString *) depiction;
2148 - (Address *) author;
2150 - (NSString *) support;
2152 - (NSArray *) files;
2153 - (NSArray *) warnings;
2154 - (NSArray *) applications;
2156 - (Source *) source;
2158 - (BOOL) matches:(NSString *)text;
2160 - (bool) hasSupportingRole;
2161 - (BOOL) hasTag:(NSString *)tag;
2162 - (NSString *) primaryPurpose;
2163 - (NSArray *) purposes;
2164 - (bool) isCommercial;
2166 - (void) setIndex:(size_t)index;
2168 - (CYString &) cyname;
2170 - (uint32_t) compareBySection:(NSArray *)sections;
2175 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2176 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2177 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2178 - (bool) isVisibleInSection:(NSString *)section;
2179 - (bool) isVisibleInSource:(Source *)source;
2183 uint32_t PackageChangesRadix(Package *self, void *) {
2188 uint32_t timestamp : 30;
2189 uint32_t ignored : 1;
2190 uint32_t upgradable : 1;
2194 bool upgradable([self upgradableAndEssential:YES]);
2195 value.bits.upgradable = upgradable ? 1 : 0;
2198 value.bits.timestamp = 0;
2199 value.bits.ignored = [self ignored] ? 0 : 1;
2200 value.bits.upgradable = 1;
2202 value.bits.timestamp = [self seen] >> 2;
2203 value.bits.ignored = 0;
2204 value.bits.upgradable = 0;
2207 return _not(uint32_t) - value.key;
2210 uint32_t PackagePrefixRadix(Package *self, void *context) {
2211 size_t offset(reinterpret_cast<size_t>(context));
2212 CYString &name([self cyname]);
2214 size_t size(name.size());
2217 char *text(name.data());
2220 if (!isdigit(text[0]))
2224 while (size != digits && isdigit(text[digits]))
2232 if (offset == 0 && zeros != 0) {
2233 memset(data, '0', zeros);
2234 memcpy(data + zeros, text, 4 - zeros);
2236 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2237 if (size <= offset - zeros)
2240 text += offset - zeros;
2241 size -= offset - zeros;
2244 memcpy(data, text, 4);
2246 memcpy(data, text, size);
2247 memset(data + size, 0, 4 - size);
2250 for (size_t i(0); i != 4; ++i)
2251 if (isalpha(data[i]))
2259 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2261 /* XXX: ntohl may be more honest */
2262 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2265 CYString &(*PackageName)(Package *self, SEL sel);
2267 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2268 _profile(PackageNameCompare)
2269 CYString &lhi(PackageName(lhs, @selector(cyname)));
2270 CYString &rhi(PackageName(rhs, @selector(cyname)));
2271 CFStringRef lhn(lhi), rhn(rhi);
2274 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2275 else if (rhn == NULL)
2276 return NSOrderedDescending;
2278 _profile(PackageNameCompare$NumbersLast)
2279 if (!lhi.empty() && !rhi.empty()) {
2280 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2281 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2282 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2283 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2284 return lha ? NSOrderedAscending : NSOrderedDescending;
2288 CFIndex length = CFStringGetLength(lhn);
2290 _profile(PackageNameCompare$Compare)
2291 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2296 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2297 return PackageNameCompare(*lhs, *rhs, context);
2300 struct PackageNameOrdering :
2301 std::binary_function<Package *, Package *, bool>
2303 _finline bool operator ()(Package *lhs, Package *rhs) const {
2304 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2308 @implementation Package
2310 - (NSString *) description {
2311 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2315 if (parsed_ != NULL)
2324 + (NSString *) webScriptNameForSelector:(SEL)selector {
2326 else if (selector == @selector(clear))
2328 else if (selector == @selector(getField:))
2330 else if (selector == @selector(hasTag:))
2332 else if (selector == @selector(install))
2334 else if (selector == @selector(remove))
2340 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2341 return [self webScriptNameForSelector:selector] == nil;
2344 + (NSArray *) _attributeKeys {
2345 return [NSArray arrayWithObjects:
2364 @"shortDescription",
2377 - (NSArray *) attributeKeys {
2378 return [[self class] _attributeKeys];
2381 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2382 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2385 - (NSArray *) relations {
2386 @synchronized (database_) {
2387 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2388 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2389 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2393 - (NSString *) getField:(NSString *)name {
2394 @synchronized (database_) {
2395 if ([database_ era] != era_ || file_.end())
2398 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2400 const char *start, *end;
2401 if (!parser.Find([name UTF8String], start, end))
2402 return (NSString *) [NSNull null];
2404 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2408 if (parsed_ != NULL)
2410 @synchronized (database_) {
2411 if ([database_ era] != era_ || file_.end())
2414 ParsedPackage *parsed(new ParsedPackage);
2417 _profile(Package$parse)
2418 pkgRecords::Parser *parser;
2420 _profile(Package$parse$Lookup)
2421 parser = &[database_ records]->Lookup(file_);
2426 _profile(Package$parse$Find)
2431 {"icon", &parsed->icon_},
2432 {"depiction", &parsed->depiction_},
2433 {"homepage", &parsed->homepage_},
2434 {"website", &website},
2435 {"bugs", &parsed->bugs_},
2436 {"support", &parsed->support_},
2437 {"sponsor", &parsed->sponsor_},
2438 {"author", &parsed->author_},
2441 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2442 const char *start, *end;
2444 if (parser->Find(names[i].name_, start, end)) {
2445 CYString &value(*names[i].value_);
2446 _profile(Package$parse$Value)
2447 value.set(pool_, start, end - start);
2453 _profile(Package$parse$Tagline)
2454 const char *start, *end;
2455 if (parser->ShortDesc(start, end)) {
2456 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2459 while (stop != start && stop[-1] == '\r')
2461 parsed->tagline_.set(pool_, start, stop - start);
2465 _profile(Package$parse$Retain)
2466 if (parsed->homepage_.empty())
2467 parsed->homepage_ = website;
2468 if (parsed->homepage_ == parsed->depiction_)
2469 parsed->homepage_.clear();
2474 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2475 if ((self = [super init]) != nil) {
2476 _profile(Package$initWithVersion)
2479 database_ = database;
2480 era_ = [database era];
2484 pkgCache::PkgIterator iterator(version.ParentPkg());
2485 iterator_ = iterator;
2487 _profile(Package$initWithVersion$Version)
2488 if (!version_.end())
2489 file_ = version_.FileList();
2491 pkgCache &cache([database_ cache]);
2492 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2496 _profile(Package$initWithVersion$Cache)
2497 name_.set(NULL, iterator.Display());
2499 latest_.set(NULL, StripVersion_(version_.VerStr()));
2501 pkgCache::VerIterator current(iterator.CurrentVer());
2503 installed_.set(NULL, StripVersion_(current.VerStr()));
2506 _profile(Package$initWithVersion$Tags)
2507 pkgCache::TagIterator tag(iterator.TagList());
2509 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2511 const char *name(tag.Name());
2512 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2514 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2515 if (strcmp(name + 6, "enduser") == 0)
2517 else if (strcmp(name + 6, "hacker") == 0)
2519 else if (strcmp(name + 6, "developer") == 0)
2521 else if (strcmp(name + 6, "cydia") == 0)
2527 if (strncmp(name, "cydia::", 7) == 0) {
2528 if (strcmp(name + 7, "essential") == 0)
2530 else if (strcmp(name + 7, "obsolete") == 0)
2535 } while (!tag.end());
2539 _profile(Package$initWithVersion$Metadata)
2540 const char *mixed(iterator.Name());
2541 size_t size(strlen(mixed));
2542 char lower[size + 1];
2544 for (size_t i(0); i != size; ++i)
2545 lower[i] = mixed[i] | 0x20;
2548 PackageValue *metadata(PackageFind(lower, size));
2549 metadata_ = metadata;
2551 id_.set(NULL, metadata->name_, size);
2553 const char *latest(version_.VerStr());
2554 size_t length(strlen(latest));
2556 uint16_t vhash(hashlittle(latest, length));
2558 size_t capped(std::min<size_t>(8, length));
2559 latest = latest + length - capped;
2561 if (metadata->first_ == 0)
2562 metadata->first_ = now_;
2564 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2565 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2566 metadata->vhash_ = vhash;
2567 metadata->last_ = now_;
2568 } else if (metadata->last_ == 0)
2569 metadata->last_ = metadata->first_;
2572 _profile(Package$initWithVersion$Section)
2573 section_ = iterator.Section();
2576 _profile(Package$initWithVersion$Flags)
2577 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2578 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2583 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2584 pkgCache::VerIterator version;
2586 _profile(Package$packageWithIterator$GetCandidateVer)
2587 version = [database policy]->GetCandidateVer(iterator);
2595 _profile(Package$packageWithIterator$Allocate)
2596 package = [Package allocWithZone:zone];
2599 _profile(Package$packageWithIterator$Initialize)
2601 initWithVersion:version
2608 _profile(Package$packageWithIterator$Autorelease)
2609 package = [package autorelease];
2615 - (pkgCache::PkgIterator) iterator {
2619 - (NSString *) section {
2620 if (section$_ == nil) {
2621 if (section_ == NULL)
2624 _profile(Package$section$mappedSectionForPointer)
2625 section$_ = [database_ mappedSectionForPointer:section_];
2630 - (NSString *) simpleSection {
2631 if (NSString *section = [self section])
2632 return Simplify(section);
2637 - (NSString *) longSection {
2638 return LocalizeSection([self section]);
2641 - (NSString *) shortSection {
2642 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2645 - (NSString *) uri {
2648 pkgIndexFile *index;
2649 pkgCache::PkgFileIterator file(file_.File());
2650 if (![database_ list].FindIndex(file, index))
2652 return [NSString stringWithUTF8String:iterator_->Path];
2653 //return [NSString stringWithUTF8String:file.Site()];
2654 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2658 - (Address *) maintainer {
2659 @synchronized (database_) {
2660 if ([database_ era] != era_ || file_.end())
2663 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2664 const std::string &maintainer(parser->Maintainer());
2665 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2669 @synchronized (database_) {
2670 if ([database_ era] != era_ || version_.end())
2673 return version_->InstalledSize;
2676 - (NSString *) longDescription {
2677 @synchronized (database_) {
2678 if ([database_ era] != era_ || file_.end())
2681 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2682 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2684 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2685 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2686 if ([lines count] < 2)
2689 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2690 for (size_t i(1), e([lines count]); i != e; ++i) {
2691 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2692 [trimmed addObject:trim];
2695 return [trimmed componentsJoinedByString:@"\n"];
2698 - (NSString *) shortDescription {
2699 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2703 _profile(Package$index)
2704 CFStringRef name((CFStringRef) [self name]);
2705 if (CFStringGetLength(name) == 0)
2707 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2708 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2710 return toupper(character);
2714 - (PackageValue *) metadata {
2719 PackageValue *metadata([self metadata]);
2720 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2723 - (bool) subscribed {
2724 return [self metadata]->subscribed_;
2727 - (bool) setSubscribed:(bool)subscribed {
2728 PackageValue *metadata([self metadata]);
2729 if (metadata->subscribed_ == subscribed)
2731 metadata->subscribed_ = subscribed;
2739 - (NSString *) latest {
2743 - (NSString *) installed {
2747 - (BOOL) uninstalled {
2748 return installed_.empty();
2752 return !version_.end();
2755 - (BOOL) upgradableAndEssential:(BOOL)essential {
2756 _profile(Package$upgradableAndEssential)
2757 pkgCache::VerIterator current(iterator_.CurrentVer());
2759 return essential && essential_;
2761 return !version_.end() && version_ != current;
2765 - (BOOL) essential {
2770 return [database_ cache][iterator_].InstBroken();
2773 - (BOOL) unfiltered {
2774 _profile(Package$unfiltered$obsolete)
2775 if (_unlikely(obsolete_))
2779 _profile(Package$unfiltered$hasSupportingRole)
2780 if (_unlikely(![self hasSupportingRole]))
2788 if (![self unfiltered])
2793 _profile(Package$visible$section)
2794 section = [self section];
2797 _profile(Package$visible$isSectionVisible)
2798 if (!isSectionVisible(section))
2806 unsigned char current(iterator_->CurrentState);
2807 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2810 - (BOOL) halfConfigured {
2811 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2814 - (BOOL) halfInstalled {
2815 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2819 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2820 return state.Mode != pkgDepCache::ModeKeep;
2823 - (NSString *) mode {
2824 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2826 switch (state.Mode) {
2827 case pkgDepCache::ModeDelete:
2828 if ((state.iFlags & pkgDepCache::Purge) != 0)
2832 case pkgDepCache::ModeKeep:
2833 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2834 return @"REINSTALL";
2835 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2839 case pkgDepCache::ModeInstall:
2840 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2841 return @"REINSTALL";
2842 else*/ switch (state.Status) {
2844 return @"DOWNGRADE";
2850 return @"NEW_INSTALL";
2861 - (NSString *) name {
2862 return name_.empty() ? id_ : name_;
2865 - (UIImage *) icon {
2866 NSString *section = [self simpleSection];
2869 if (parsed_ != NULL)
2870 if (NSString *href = parsed_->icon_)
2871 if ([href hasPrefix:@"file:///"])
2872 // XXX: correct escaping
2873 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2874 if (icon == nil) if (section != nil)
2875 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2876 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2877 if ([dicon hasPrefix:@"file:///"])
2878 // XXX: correct escaping
2879 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2881 icon = [UIImage applicationImageNamed:@"unknown.png"];
2885 - (NSString *) homepage {
2886 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2889 - (NSString *) depiction {
2890 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2893 - (Address *) sponsor {
2894 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2897 - (Address *) author {
2898 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2901 - (NSString *) support {
2902 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2905 - (NSArray *) files {
2906 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2907 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2910 fin.open([path UTF8String]);
2915 while (std::getline(fin, line))
2916 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2921 - (NSString *) state {
2922 @synchronized (database_) {
2923 if ([database_ era] != era_ || file_.end())
2926 switch (iterator_->CurrentState) {
2927 case pkgCache::State::NotInstalled:
2928 return @"NotInstalled";
2929 case pkgCache::State::UnPacked:
2931 case pkgCache::State::HalfConfigured:
2932 return @"HalfConfigured";
2933 case pkgCache::State::HalfInstalled:
2934 return @"HalfInstalled";
2935 case pkgCache::State::ConfigFiles:
2936 return @"ConfigFiles";
2937 case pkgCache::State::Installed:
2938 return @"Installed";
2939 case pkgCache::State::TriggersAwaited:
2940 return @"TriggersAwaited";
2941 case pkgCache::State::TriggersPending:
2942 return @"TriggersPending";
2945 return (NSString *) [NSNull null];
2948 - (NSString *) selection {
2949 @synchronized (database_) {
2950 if ([database_ era] != era_ || file_.end())
2953 switch (iterator_->SelectedState) {
2954 case pkgCache::State::Unknown:
2956 case pkgCache::State::Install:
2958 case pkgCache::State::Hold:
2960 case pkgCache::State::DeInstall:
2961 return @"DeInstall";
2962 case pkgCache::State::Purge:
2966 return (NSString *) [NSNull null];
2969 - (NSArray *) warnings {
2970 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2971 const char *name(iterator_.Name());
2973 size_t length(strlen(name));
2974 if (length < 2) invalid:
2975 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2976 else for (size_t i(0); i != length; ++i)
2978 /* XXX: technically this is not allowed */
2979 (name[i] < 'A' || name[i] > 'Z') &&
2980 (name[i] < 'a' || name[i] > 'z') &&
2981 (name[i] < '0' || name[i] > '9') &&
2982 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2985 if (strcmp(name, "cydia") != 0) {
2988 bool _private = false;
2991 bool repository = [[self section] isEqualToString:@"Repositories"];
2993 if (NSArray *files = [self files])
2994 for (NSString *file in files)
2995 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2997 else if (!user && [file isEqualToString:@"/User"])
2999 else if (!_private && [file isEqualToString:@"/private"])
3001 else if (!stash && [file isEqualToString:@"/var/stash"])
3004 /* XXX: this is not sensitive enough. only some folders are valid. */
3005 if (cydia && !repository)
3006 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3008 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3010 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3012 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3015 return [warnings count] == 0 ? nil : warnings;
3018 - (NSArray *) applications {
3019 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3021 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3023 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
3024 if (NSArray *files = [self files])
3025 for (NSString *file in files)
3026 if (application_r(file)) {
3027 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3028 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3029 if ([id isEqualToString:me])
3032 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3034 display = application_r[1];
3036 NSString *bundle([file stringByDeletingLastPathComponent]);
3037 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3038 if (icon == nil || [icon length] == 0)
3040 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3042 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3043 [applications addObject:application];
3045 [application addObject:id];
3046 [application addObject:display];
3047 [application addObject:url];
3050 return [applications count] == 0 ? nil : applications;
3053 - (Source *) source {
3054 if (source_ == nil) {
3055 @synchronized (database_) {
3056 if ([database_ era] != era_ || file_.end())
3057 source_ = (Source *) [NSNull null];
3059 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
3063 return source_ == (Source *) [NSNull null] ? nil : source_;
3066 - (BOOL) matches:(NSString *)text {
3072 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
3073 if (range.location != NSNotFound)
3076 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
3077 if (range.location != NSNotFound)
3082 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
3083 if (range.location != NSNotFound)
3089 - (bool) hasSupportingRole {
3094 if ([Role_ isEqualToString:@"User"])
3098 if ([Role_ isEqualToString:@"Hacker"])
3102 if ([Role_ isEqualToString:@"Developer"])
3107 - (NSArray *) tags {
3111 - (BOOL) hasTag:(NSString *)tag {
3112 return tags_ == nil ? NO : [tags_ containsObject:tag];
3115 - (NSString *) primaryPurpose {
3116 for (NSString *tag in tags_)
3117 if ([tag hasPrefix:@"purpose::"])
3118 return [tag substringFromIndex:9];
3122 - (NSArray *) purposes {
3123 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3124 for (NSString *tag in tags_)
3125 if ([tag hasPrefix:@"purpose::"])
3126 [purposes addObject:[tag substringFromIndex:9]];
3127 return [purposes count] == 0 ? nil : purposes;
3130 - (bool) isCommercial {
3131 return [self hasTag:@"cydia::commercial"];
3134 - (void) setIndex:(size_t)index {
3135 if (metadata_->index_ != index)
3136 metadata_->index_ = index;
3139 - (CYString &) cyname {
3140 return name_.empty() ? id_ : name_;
3143 - (uint32_t) compareBySection:(NSArray *)sections {
3144 NSString *section([self section]);
3145 for (size_t i(0), e([sections count]); i != e; ++i) {
3146 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3150 return _not(uint32_t);
3154 @synchronized (database_) {
3155 pkgProblemResolver *resolver = [database_ resolver];
3156 resolver->Clear(iterator_);
3158 pkgCacheFile &cache([database_ cache]);
3159 cache->SetReInstall(iterator_, false);
3160 cache->MarkKeep(iterator_, false);
3164 @synchronized (database_) {
3165 pkgProblemResolver *resolver = [database_ resolver];
3166 resolver->Clear(iterator_);
3167 resolver->Protect(iterator_);
3169 pkgCacheFile &cache([database_ cache]);
3170 cache->SetReInstall(iterator_, false);
3171 cache->MarkInstall(iterator_, false);
3173 pkgDepCache::StateCache &state((*cache)[iterator_]);
3174 if (!state.Install())
3175 cache->SetReInstall(iterator_, true);
3179 @synchronized (database_) {
3180 pkgProblemResolver *resolver = [database_ resolver];
3181 resolver->Clear(iterator_);
3182 resolver->Remove(iterator_);
3183 resolver->Protect(iterator_);
3185 pkgCacheFile &cache([database_ cache]);
3186 cache->SetReInstall(iterator_, false);
3187 cache->MarkDelete(iterator_, true);
3190 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3191 _profile(Package$isUnfilteredAndSearchedForBy)
3194 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3195 value &= [self unfiltered];
3198 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3199 value &= [self matches:search];
3206 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3207 if ([search length] == 0)
3210 _profile(Package$isUnfilteredAndSelectedForBy)
3213 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3214 value &= [self unfiltered];
3217 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3218 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3225 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3226 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3229 - (bool) isVisibleInSection:(NSString *)name {
3230 NSString *section([self section]);
3234 section == nil && [name length] == 0 ||
3235 [name isEqualToString:section]
3236 ) && [self visible];
3239 - (bool) isVisibleInSource:(Source *)source {
3240 return [self source] == source && [self visible];
3245 /* Section Class {{{ */
3246 @interface Section : NSObject {
3251 NSString *localized_;
3254 - (NSComparisonResult) compareByLocalized:(Section *)section;
3255 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3256 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3257 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3258 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3259 - (NSString *) name;
3266 - (void) addToCount;
3268 - (void) setCount:(size_t)count;
3269 - (NSString *) localized;
3273 @implementation Section
3277 if (localized_ != nil)
3278 [localized_ release];
3282 - (NSComparisonResult) compareByLocalized:(Section *)section {
3283 NSString *lhs(localized_);
3284 NSString *rhs([section localized]);
3286 /*if ([lhs length] != 0 && [rhs length] != 0) {
3287 unichar lhc = [lhs characterAtIndex:0];
3288 unichar rhc = [rhs characterAtIndex:0];
3290 if (isalpha(lhc) && !isalpha(rhc))
3291 return NSOrderedAscending;
3292 else if (!isalpha(lhc) && isalpha(rhc))
3293 return NSOrderedDescending;
3296 return [lhs compare:rhs options:LaxCompareOptions_];
3299 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3300 if ((self = [self initWithName:name localize:NO]) != nil) {
3301 if (localized != nil)
3302 localized_ = [localized retain];
3306 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3307 return [self initWithName:name row:0 localize:localize];
3310 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3311 if ((self = [super init]) != nil) {
3312 name_ = [name retain];
3316 localized_ = [LocalizeSection(name_) retain];
3320 /* XXX: localize the index thingees */
3321 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3322 if ((self = [super init]) != nil) {
3323 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3329 - (NSString *) name {
3349 - (void) addToCount {
3353 - (void) setCount:(size_t)count {
3357 - (NSString *) localized {
3364 static NSString *Colon_;
3365 static NSString *Elision_;
3366 static NSString *Error_;
3367 static NSString *Warning_;
3369 /* Database Implementation {{{ */
3370 @implementation Database
3372 + (Database *) sharedInstance {
3373 static Database *instance;
3374 if (instance == nil)
3375 instance = [[Database alloc] init];
3383 - (void) releasePackages {
3384 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3385 CFArrayRemoveAllValues(packages_);
3389 // XXX: actually implement this thing
3391 [sourceList_ release];
3392 [self releasePackages];
3393 apr_pool_destroy(pool_);
3394 NSRecycleZone(zone_);
3398 - (void) _readCydia:(NSNumber *)fd { _pooled
3399 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3400 std::istream is(&ib);
3403 static Pcre finish_r("^finish:([^:]*)$");
3405 while (std::getline(is, line)) {
3406 const char *data(line.c_str());
3407 size_t size = line.size();
3408 lprintf("C:%s\n", data);
3410 if (finish_r(data, size)) {
3411 NSString *finish = finish_r[1];
3412 int index = [Finishes_ indexOfObject:finish];
3413 if (index != INT_MAX && index > Finish_)
3421 - (void) _readStatus:(NSNumber *)fd { _pooled
3422 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3423 std::istream is(&ib);
3426 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3427 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3429 while (std::getline(is, line)) {
3430 const char *data(line.c_str());
3431 size_t size(line.size());
3432 lprintf("S:%s\n", data);
3434 if (conffile_r(data, size)) {
3435 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3436 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3437 } else if (strncmp(data, "status: ", 8) == 0) {
3438 // status: <package>: {unpacked,half-configured,installed}
3439 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:@"STATUS"]);
3440 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3441 } else if (strncmp(data, "processing: ", 12) == 0) {
3442 // processing: configure: config-test
3443 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:@"STATUS"]);
3444 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3445 } else if (pmstatus_r(data, size)) {
3446 std::string type([pmstatus_r[1] UTF8String]);
3448 NSString *package = pmstatus_r[2];
3449 if ([package isEqualToString:@"dpkg-exec"])
3452 float percent([pmstatus_r[3] floatValue]);
3453 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3455 NSString *string = pmstatus_r[4];
3457 if (type == "pmerror") {
3458 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:@"ERROR" forPackage:package]);
3459 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3460 } else if (type == "pmstatus") {
3461 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:@"STATUS" forPackage:package]);
3462 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3463 } else if (type == "pmconffile")
3464 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3466 lprintf("E:unknown pmstatus\n");
3468 lprintf("E:unknown status\n");
3474 - (void) _readOutput:(NSNumber *)fd { _pooled
3475 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3476 std::istream is(&ib);
3479 while (std::getline(is, line)) {
3480 lprintf("O:%s\n", line.c_str());
3482 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:@"INFORMATION"]);
3483 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3493 - (Package *) packageWithName:(NSString *)name {
3494 @synchronized (self) {
3495 if (static_cast<pkgDepCache *>(cache_) == NULL)
3497 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3498 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3502 if ((self = [super init]) != nil) {
3509 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3510 apr_pool_create(&pool_, NULL);
3512 size_t capacity(MetaFile_->active_);
3518 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3519 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3523 _assert(pipe(fds) != -1);
3526 _config->Set("APT::Keep-Fds::", cydiafd_);
3527 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3530 detachNewThreadSelector:@selector(_readCydia:)
3532 withObject:[NSNumber numberWithInt:fds[0]]
3535 _assert(pipe(fds) != -1);
3539 detachNewThreadSelector:@selector(_readStatus:)
3541 withObject:[NSNumber numberWithInt:fds[0]]
3544 _assert(pipe(fds) != -1);
3545 _assert(dup2(fds[0], 0) != -1);
3546 _assert(close(fds[0]) != -1);
3548 input_ = fdopen(fds[1], "a");
3550 _assert(pipe(fds) != -1);
3551 _assert(dup2(fds[1], 1) != -1);
3552 _assert(close(fds[1]) != -1);
3555 detachNewThreadSelector:@selector(_readOutput:)
3557 withObject:[NSNumber numberWithInt:fds[0]]
3562 - (pkgCacheFile &) cache {
3566 - (pkgDepCache::Policy *) policy {
3570 - (pkgRecords *) records {
3574 - (pkgProblemResolver *) resolver {
3578 - (pkgAcquire &) fetcher {
3582 - (pkgSourceList &) list {
3586 - (NSArray *) packages {
3587 return (NSArray *) packages_;
3590 - (NSArray *) sources {
3594 - (Source *) sourceWithKey:(NSString *)key {
3595 for (Source *source in [self sources]) {
3596 if ([[source key] isEqualToString:key])
3601 - (bool) popErrorWithTitle:(NSString *)title {
3604 while (!_error->empty()) {
3606 bool warning(!_error->PopMessage(error));
3611 size_t size(error.size());
3612 if (size == 0 || error[size - 1] != '\n')
3614 error.resize(size - 1);
3617 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3619 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? @"WARNING" : @"ERROR")] forTask:title];
3625 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3626 return [self popErrorWithTitle:title] || !success;
3629 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3630 @synchronized (self) {
3633 [self releasePackages];
3636 [sourceList_ removeAllObjects];
3656 apr_pool_clear(pool_);
3658 NSRecycleZone(zone_);
3659 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3661 int chk(creat("/tmp/cydia.chk", 0644));
3665 if (invocation != nil)
3666 [invocation invoke];
3668 NSString *title(UCLocalize("DATABASE"));
3671 OpProgress progress;
3672 while (!cache_.Open(progress, true)) { pop:
3674 bool warning(!_error->PopMessage(error));
3675 lprintf("cache_.Open():[%s]\n", error.c_str());
3677 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3678 [delegate_ repairWithSelector:@selector(configure)];
3679 else if (error == "The package lists or status file could not be parsed or opened.")
3680 [delegate_ repairWithSelector:@selector(update)];
3681 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3682 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3683 // else if (error == "Malformed Status line")
3684 // else if (error == "The list of sources could not be read.")
3686 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? @"WARNING" : @"ERROR")] forTask:title];
3696 unlink("/tmp/cydia.chk");
3698 now_ = [[NSDate date] timeIntervalSince1970];
3700 policy_ = new pkgDepCache::Policy();
3701 records_ = new pkgRecords(cache_);
3702 resolver_ = new pkgProblemResolver(cache_);
3703 fetcher_ = new pkgAcquire(&status_);
3706 list_ = new pkgSourceList();
3707 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3710 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3711 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:@"ERROR"] forTask:title];
3715 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3718 if (cache_->BrokenCount() != 0) {
3719 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3722 if (cache_->BrokenCount() != 0) {
3723 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:@"ERROR"] forTask:title];
3727 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3731 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3732 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3733 [sourceList_ addObject:object];
3735 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3736 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3737 // XXX: this could be more intelligent
3738 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3739 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3741 sourceMap_[cached->ID] = object;
3746 /*std::vector<Package *> packages;
3747 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3748 [packages_ release];
3753 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3754 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3755 //packages.push_back(package);
3756 CFArrayAppendValue(packages_, [package retain]);
3760 /*if (packages.empty())
3761 packages_ = [[NSArray alloc] init];
3763 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3766 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3767 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3768 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3776 /*if (!packages.empty())
3777 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3778 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3780 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3782 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3784 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3788 size_t count(CFArrayGetCount(packages_));
3789 MetaFile_->active_ = count;
3791 for (size_t index(0); index != count; ++index)
3792 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3796 } } CYPoolEnd() _trace(); }
3799 @synchronized (self) {
3801 resolver_ = new pkgProblemResolver(cache_);
3803 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3804 if (!cache_[iterator].Keep())
3805 cache_->MarkKeep(iterator, false);
3806 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3807 cache_->SetReInstall(iterator, false);
3810 - (void) configure {
3811 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3813 system([dpkg UTF8String]);
3818 // XXX: I don't remember this condition
3823 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3825 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3827 if ([self popErrorWithTitle:title])
3831 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3834 public pkgArchiveCleaner
3837 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3842 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3849 fetcher_->Shutdown();
3851 pkgRecords records(cache_);
3853 lock_ = new FileFd();
3854 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3856 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3858 if ([self popErrorWithTitle:title])
3862 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3865 manager_ = (_system->CreatePM(cache_));
3866 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3873 bool substrate(RestartSubstrate_);
3874 RestartSubstrate_ = false;
3876 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3878 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3880 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3882 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3883 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3886 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3888 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3890 [self popErrorWithTitle:title];
3894 bool failed = false;
3895 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3896 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3898 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3904 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3912 RestartSubstrate_ = true;
3915 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3917 if (_error->PendingError()) {
3922 if (result == pkgPackageManager::Failed) {
3927 if (result != pkgPackageManager::Completed) {
3932 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3934 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3936 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3937 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3940 if (![before isEqualToArray:after])
3945 NSString *title(UCLocalize("UPGRADE"));
3946 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3952 [self updateWithStatus:status_];
3955 - (void) updateWithStatus:(Status &)status {
3956 NSString *title(UCLocalize("REFRESHING_DATA"));
3959 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3963 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3964 if ([self popErrorWithTitle:title])
3967 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3969 bool success(ListUpdate(status, list, PulseInterval_));
3970 if (status.WasCancelled())
3973 [self popErrorWithTitle:title forOperation:success];
3975 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3977 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3981 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3982 delegate_ = delegate;
3985 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3986 progress_ = delegate;
3987 status_.setDelegate(delegate);
3990 - (NSObject<ProgressDelegate> *) progressDelegate {
3994 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3995 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3996 return i == sourceMap_.end() ? nil : i->second;
3999 - (NSString *) mappedSectionForPointer:(const char *)section {
4000 _H<NSString> *mapped;
4002 _profile(Database$mappedSectionForPointer$Cache)
4003 mapped = §ions_[section];
4006 if (*mapped == NULL) {
4007 size_t length(strlen(section));
4008 char spaced[length + 1];
4010 _profile(Database$mappedSectionForPointer$Replace)
4011 for (size_t index(0); index != length; ++index)
4012 spaced[index] = section[index] == '_' ? ' ' : section[index];
4013 spaced[length] = '\0';
4018 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4019 string = [NSString stringWithUTF8String:spaced];
4022 _profile(Database$mappedSectionForPointer$Map)
4023 string = [SectionMap_ objectForKey:string] ?: string;
4033 /* Web Scripting {{{ */
4034 @interface CydiaObject : NSObject {
4036 _transient id delegate_;
4039 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4043 @implementation CydiaObject
4046 [indirect_ release];
4050 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4051 if ((self = [super init]) != nil) {
4052 indirect_ = [indirect retain];
4056 - (void) setDelegate:(id)delegate {
4057 delegate_ = delegate;
4060 + (NSArray *) _attributeKeys {
4061 return [NSArray arrayWithObjects:
4076 - (NSArray *) attributeKeys {
4077 return [[self class] _attributeKeys];
4080 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4081 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4084 - (NSString *) version {
4088 - (NSString *) device {
4089 return [[UIDevice currentDevice] uniqueIdentifier];
4092 - (NSString *) firmware {
4093 return [[UIDevice currentDevice] systemVersion];
4096 - (NSString *) hostname {
4097 return [[UIDevice currentDevice] name];
4100 - (NSString *) idiom {
4101 return (id) Idiom_ ?: [NSNull null];
4104 - (NSString *) plmn {
4105 return (id) PLMN_ ?: [NSNull null];
4108 - (NSString *) ecid {
4109 return (id) ChipID_ ?: [NSNull null];
4112 - (NSString *) serial {
4113 return SerialNumber_;
4116 - (NSString *) role {
4117 return (id) Role_ ?: [NSNull null];
4120 - (NSString *) model {
4121 return [NSString stringWithUTF8String:Machine_];
4124 - (NSString *) token {
4125 return (id) Token_ ?: [NSNull null];
4128 + (NSString *) webScriptNameForSelector:(SEL)selector {
4130 else if (selector == @selector(addTrivialSource:))
4131 return @"addTrivialSource";
4132 else if (selector == @selector(close))
4134 else if (selector == @selector(du:))
4136 else if (selector == @selector(stringWithFormat:arguments:))
4138 else if (selector == @selector(getAllSources))
4139 return @"getAllSourcs";
4140 else if (selector == @selector(getKernelNumber:))
4141 return @"getKernelNumber";
4142 else if (selector == @selector(getKernelString:))
4143 return @"getKernelString";
4144 else if (selector == @selector(getInstalledPackages))
4145 return @"getInstalledPackages";
4146 else if (selector == @selector(getPackageById:))
4147 return @"getPackageById";
4148 else if (selector == @selector(installPackages:))
4149 return @"installPackages";
4150 else if (selector == @selector(localizedStringForKey:value:table:))
4152 else if (selector == @selector(refreshSources))
4153 return @"refreshSources";
4154 else if (selector == @selector(removeButton))
4155 return @"removeButton";
4156 else if (selector == @selector(substitutePackageNames:))
4157 return @"substitutePackageNames";
4158 else if (selector == @selector(scrollToBottom:))
4159 return @"scrollToBottom";
4160 else if (selector == @selector(setAllowsNavigationAction:))
4161 return @"setAllowsNavigationAction";
4162 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4163 return @"setButtonImage";
4164 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4165 return @"setButtonTitle";
4166 else if (selector == @selector(setHidesBackButton:))
4167 return @"setHidesBackButton";
4168 else if (selector == @selector(setHidesNavigationBar:))
4169 return @"setHidesNavigationBar";
4170 else if (selector == @selector(setNavigationBarStyle:))
4171 return @"setNavigationBarStyle";
4172 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4173 return @"setNavigationBarTintColor";
4174 else if (selector == @selector(setPopupHook:))
4175 return @"setPopupHook";
4176 else if (selector == @selector(setToken:))
4178 else if (selector == @selector(setViewportWidth:))
4179 return @"setViewportWidth";
4180 else if (selector == @selector(statfs:))
4182 else if (selector == @selector(supports:))
4188 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4189 return [self webScriptNameForSelector:selector] == nil;
4192 - (BOOL) supports:(NSString *)feature {
4193 return [feature isEqualToString:@"window.open"];
4196 - (NSNumber *) getKernelNumber:(NSString *)name {
4197 const char *string([name UTF8String]);
4200 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4201 return (id) [NSNull null];
4203 if (size != sizeof(int))
4204 return (id) [NSNull null];
4207 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4208 return (id) [NSNull null];
4210 return [NSNumber numberWithInt:value];
4213 - (NSString *) getKernelString:(NSString *)name {
4214 const char *string([name UTF8String]);
4217 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4218 return (id) [NSNull null];
4220 char value[size + 1];
4221 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4222 return (id) [NSNull null];
4224 // XXX: just in case you request something ludicrous
4227 return [NSString stringWithCString:value];
4230 - (void) addTrivialSource:(NSString *)href {
4231 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4234 - (void) refreshSources {
4235 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4238 - (NSArray *) getAllSources {
4239 return [[Database sharedInstance] sources];
4242 - (NSArray *) getInstalledPackages {
4243 Database *database([Database sharedInstance]);
4244 @synchronized (database) {
4245 NSArray *packages([database packages]);
4246 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4247 for (Package *package in packages)
4248 if (![package uninstalled])
4249 [installed addObject:package];
4253 - (Package *) getPackageById:(NSString *)id {
4254 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4258 return (Package *) [NSNull null];
4261 - (NSArray *) statfs:(NSString *)path {
4264 if (path == nil || statfs([path UTF8String], &stat) == -1)
4267 return [NSArray arrayWithObjects:
4268 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4269 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4270 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4274 - (NSNumber *) du:(NSString *)path {
4275 NSNumber *value(nil);
4278 _assert(pipe(fds) != -1);
4280 pid_t pid(ExecFork());
4282 _assert(dup2(fds[1], 1) != -1);
4283 _assert(close(fds[0]) != -1);
4284 _assert(close(fds[1]) != -1);
4285 /* XXX: this should probably not use du */
4286 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4291 _assert(close(fds[1]) != -1);
4293 if (FILE *du = fdopen(fds[0], "r")) {
4295 while (fgets(line, sizeof(line), du) != NULL) {
4296 size_t length(strlen(line));
4297 while (length != 0 && line[length - 1] == '\n')
4298 line[--length] = '\0';
4299 if (char *tab = strchr(line, '\t')) {
4301 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4306 } else _assert(close(fds[0]));
4310 if (waitpid(pid, &status, 0) == -1)
4313 else _assert(false);
4319 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4322 - (void) installPackages:(NSArray *)packages {
4323 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4326 - (NSString *) substitutePackageNames:(NSString *)message {
4327 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4328 for (size_t i(0), e([words count]); i != e; ++i) {
4329 NSString *word([words objectAtIndex:i]);
4330 if (Package *package = [[Database sharedInstance] packageWithName:word])
4331 [words replaceObjectAtIndex:i withObject:[package name]];
4334 return [words componentsJoinedByString:@" "];
4337 - (void) removeButton {
4338 [indirect_ removeButton];
4341 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4342 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4345 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4346 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4349 - (void) setAllowsNavigationAction:(NSString *)value {
4350 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4353 - (void) setHidesBackButton:(NSString *)value {
4354 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4357 - (void) setHidesNavigationBar:(NSString *)value {
4358 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4361 - (void) setNavigationBarStyle:(NSString *)value {
4362 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4365 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4366 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4367 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4368 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4371 - (void) _setToken:(NSString *)token {
4375 [Metadata_ removeObjectForKey:@"Token"];
4377 [Metadata_ setObject:Token_ forKey:@"Token"];
4382 - (void) setToken:(NSString *)token {
4383 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4386 - (void) setPopupHook:(id)function {
4387 [indirect_ setPopupHook:function];
4390 - (void) scrollToBottom:(NSNumber *)animated {
4391 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4394 - (void) setViewportWidth:(float)width {
4395 [indirect_ setViewportWidthOnMainThread:width];
4398 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4399 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4400 unsigned count([arguments count]);
4402 for (unsigned i(0); i != count; ++i)
4403 values[i] = [arguments objectAtIndex:i];
4404 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4407 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4408 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4410 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4412 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4418 /* @ Loading... Indicator {{{ */
4419 @interface CYLoadingIndicator : UIView {
4420 _H<UIActivityIndicatorView> spinner_;
4422 _H<UIView> container_;
4425 @property (readonly, nonatomic) UILabel *label;
4426 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4430 @implementation CYLoadingIndicator
4432 - (id) initWithFrame:(CGRect)frame {
4433 if ((self = [super initWithFrame:frame]) != nil) {
4434 container_ = [[[UIView alloc] init] autorelease];
4435 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4437 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4438 [spinner_ startAnimating];
4439 [container_ addSubview:spinner_];
4441 label_ = [[[UILabel alloc] init] autorelease];
4442 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4443 [label_ setBackgroundColor:[UIColor clearColor]];
4444 [label_ setTextColor:[UIColor blackColor]];
4445 [label_ setShadowColor:[UIColor whiteColor]];
4446 [label_ setShadowOffset:CGSizeMake(0, 1)];
4447 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4448 [container_ addSubview:label_];
4450 CGSize viewsize = frame.size;
4451 CGSize spinnersize = [spinner_ bounds].size;
4452 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4453 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4455 CGRect containrect = {
4456 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4457 CGSizeMake(bothwidth, spinnersize.height)
4460 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4468 [container_ setFrame:containrect];
4469 [spinner_ setFrame:spinrect];
4470 [label_ setFrame:textrect];
4471 [self addSubview:container_];
4475 - (UILabel *) label {
4479 - (UIActivityIndicatorView *) activityIndicatorView {
4485 /* Emulated Loading Controller {{{ */
4486 @interface CYEmulatedLoadingController : CYViewController {
4487 _transient Database *database_;
4488 _H<CYLoadingIndicator> indicator_;
4489 _H<UITabBar> tabbar_;
4490 _H<UINavigationBar> navbar_;
4495 @implementation CYEmulatedLoadingController
4497 - (id) initWithDatabase:(Database *)database {
4498 if ((self = [super init]) != nil) {
4499 database_ = database;
4503 // XXX: factor this out somewhere
4504 - (UIColor *) groupTableViewBackgroundColor {
4505 UIDevice *device([UIDevice currentDevice]);
4506 bool iPad([device respondsToSelector:@selector(userInterfaceIdiom)] && [device userInterfaceIdiom] == UIUserInterfaceIdiomPad);
4507 return iPad ? [UIColor colorWithRed:0.821 green:0.834 blue:0.860 alpha:1] : [UIColor groupTableViewBackgroundColor];
4511 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4512 [[self view] setBackgroundColor:[self groupTableViewBackgroundColor]];
4514 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4515 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4516 [[self view] addSubview:indicator_];
4518 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4519 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4520 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4521 [[self view] addSubview:tabbar_];
4523 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4524 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4525 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4526 [[self view] addSubview:navbar_];
4529 - (void) releaseSubviews {
4538 /* Cydia Browser Controller {{{ */
4539 @interface CYBrowserController : BrowserController {
4540 CydiaObject *cydia_;
4545 @implementation CYBrowserController
4552 - (NSURL *) navigationURL {
4553 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4556 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4559 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4560 [super webView:view didClearWindowObject:window forFrame:frame];
4562 WebDataSource *source([frame dataSource]);
4563 NSURLResponse *response([source response]);
4565 NSURL *url([response URL]);
4566 NSString *scheme([url scheme]);
4567 NSString *host([url host]);
4569 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4570 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4571 NSDictionary *headers([http allHeaderFields]);
4572 [self setHeaders:headers forHost:host];
4576 [host isEqualToString:@"cydia.saurik.com"] ||
4577 [host hasSuffix:@".cydia.saurik.com"] ||
4578 [scheme isEqualToString:@"file"]
4580 [window setValue:cydia_ forKey:@"cydia"];
4583 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4584 if (System_ != NULL)
4585 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4586 if (Machine_ != NULL)
4587 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4589 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4591 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4594 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4595 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4596 [self _setMoreHeaders:copy];
4600 - (void) setDelegate:(id)delegate {
4601 [super setDelegate:delegate];
4602 [cydia_ setDelegate:delegate];
4606 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4607 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4609 WebView *webview([[webview_ _documentView] webView]);
4611 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4614 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4616 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4617 if (Product_ != nil)
4618 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4620 [webview setApplicationNameForUserAgent:application];
4628 @interface NSObject (CydiaScript)
4629 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4632 @implementation NSObject (CydiaScript)
4634 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4640 @implementation NSArray (CydiaScript)
4642 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4643 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4644 for (size_t i(0), e([self count]); i != e; ++i)
4645 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4651 @implementation NSDictionary (CydiaScript)
4653 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4654 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4656 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4663 /* Confirmation Controller {{{ */
4664 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4665 if (!iterator.end())
4666 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4667 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4669 pkgCache::PkgIterator package(dep.TargetPkg());
4672 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4679 @protocol ConfirmationControllerDelegate
4680 - (void) cancelAndClear:(bool)clear;
4681 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4685 @interface ConfirmationController : CYBrowserController {
4686 _transient Database *database_;
4688 UIAlertView *essential_;
4690 NSDictionary *changes_;
4691 NSMutableArray *issues_;
4692 NSDictionary *sizes_;
4697 - (id) initWithDatabase:(Database *)database;
4701 @implementation ConfirmationController
4708 if (essential_ != nil)
4709 [essential_ release];
4716 RestartSubstrate_ = true;
4717 [delegate_ confirmWithNavigationController:[self navigationController]];
4720 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4721 NSString *context([alert context]);
4723 if ([context isEqualToString:@"remove"]) {
4724 if (button == [alert cancelButtonIndex])
4725 [self dismissModalViewControllerAnimated:YES];
4726 else if (button == [alert firstOtherButtonIndex]) {
4730 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4731 } else if ([context isEqualToString:@"unable"]) {
4732 [self dismissModalViewControllerAnimated:YES];
4733 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4735 [super alertView:alert clickedButtonAtIndex:button];
4739 - (void) _doContinue {
4740 [self dismissModalViewControllerAnimated:YES];
4741 [delegate_ cancelAndClear:NO];
4744 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4745 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4749 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4750 [super webView:view didClearWindowObject:window forFrame:frame];
4752 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4753 changes_, @"changes",
4757 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4760 - (id) initWithDatabase:(Database *)database {
4761 if ((self = [super init]) != nil) {
4762 database_ = database;
4764 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4765 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4766 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4767 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4768 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4772 pkgCacheFile &cache([database_ cache]);
4773 NSArray *packages([database_ packages]);
4774 pkgDepCache::Policy *policy([database_ policy]);
4776 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4778 for (Package *package in packages) {
4779 pkgCache::PkgIterator iterator([package iterator]);
4780 NSString *name([package id]);
4782 if ([package broken]) {
4783 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4785 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4787 reasons, @"reasons",
4790 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4794 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4795 pkgCache::DepIterator start;
4796 pkgCache::DepIterator end;
4797 dep.GlobOr(start, end); // ++dep
4799 if (!cache->IsImportantDep(end))
4801 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4804 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4806 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4807 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4808 clauses, @"clauses",
4812 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4814 pkgCache::PkgIterator target(start.TargetPkg());
4815 if (target->ProvidesList != 0)
4816 reason = @"missing";
4818 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4820 reason = @"installed";
4821 installed = [NSString stringWithUTF8String:ver.VerStr()];
4822 } else if (!cache[target].CandidateVerIter(cache).end())
4823 reason = @"uninstalled";
4824 else if (target->ProvidesList == 0)
4825 reason = @"uninstallable";
4827 reason = @"virtual";
4830 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4831 [NSString stringWithUTF8String:start.CompType()], @"operator",
4832 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4835 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4836 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4837 version, @"version",
4839 installed, @"installed",
4842 // yes, seriously. (wtf?)
4850 pkgDepCache::StateCache &state(cache[iterator]);
4852 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4854 if (state.NewInstall())
4855 [installs addObject:name];
4856 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4857 [reinstalls addObject:name];
4858 else if (state.Upgrade())
4859 [upgrades addObject:name];
4860 else if (state.Downgrade())
4861 [downgrades addObject:name];
4862 else if (!state.Delete())
4864 else if (special_r(name))
4865 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4866 [NSNull null], @"package",
4867 [NSArray arrayWithObjects:
4868 [NSDictionary dictionaryWithObjectsAndKeys:
4869 @"Conflicts", @"relationship",
4870 [NSArray arrayWithObjects:
4871 [NSDictionary dictionaryWithObjectsAndKeys:
4873 [NSNull null], @"version",
4874 @"installed", @"reason",
4881 if ([package essential])
4883 [removes addObject:name];
4886 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4887 substrate_ |= DepSubstrate(iterator.CurrentVer());
4892 else if (Advanced_) {
4893 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4895 essential_ = [[UIAlertView alloc]
4896 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4897 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4899 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4901 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4905 [essential_ setContext:@"remove"];
4907 essential_ = [[UIAlertView alloc]
4908 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4909 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4911 cancelButtonTitle:UCLocalize("OKAY")
4912 otherButtonTitles:nil
4915 [essential_ setContext:@"unable"];
4918 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4919 installs, @"installs",
4920 reinstalls, @"reinstalls",
4921 upgrades, @"upgrades",
4922 downgrades, @"downgrades",
4923 removes, @"removes",
4926 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4927 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4928 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4931 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4933 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4934 initWithTitle:UCLocalize("CANCEL")
4935 style:UIBarButtonItemStylePlain
4937 action:@selector(cancelButtonClicked)
4943 - (void) applyRightButton {
4944 if ([issues_ count] == 0 && ![self isLoading])
4945 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4946 initWithTitle:UCLocalize("CONFIRM")
4947 style:UIBarButtonItemStyleDone
4949 action:@selector(confirmButtonClicked)
4952 [[self navigationItem] setRightBarButtonItem:nil];
4956 - (void) cancelButtonClicked {
4957 [self dismissModalViewControllerAnimated:YES];
4958 [delegate_ cancelAndClear:YES];
4962 - (void) confirmButtonClicked {
4963 if (essential_ != nil)
4973 /* Progress Data {{{ */
4974 @interface CydiaProgressData : NSObject {
4975 _transient id delegate_;
4984 _H<NSMutableArray> events_;
4985 _H<NSString> title_;
4987 _H<NSString> status_;
4988 _H<NSString> finish_;
4993 @implementation CydiaProgressData
4995 + (NSArray *) _attributeKeys {
4996 return [NSArray arrayWithObjects:
5008 - (NSArray *) attributeKeys {
5009 return [[self class] _attributeKeys];
5012 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5013 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5017 if ((self = [super init]) != nil) {
5018 events_ = [NSMutableArray arrayWithCapacity:32];
5022 - (void) setDelegate:(id)delegate {
5023 delegate_ = delegate;
5026 - (void) setPercent:(float)value {
5030 - (NSNumber *) percent {
5031 return [NSNumber numberWithFloat:percent_];
5034 - (void) setCurrent:(float)value {
5038 - (NSNumber *) current {
5039 return [NSNumber numberWithFloat:current_];
5042 - (void) setTotal:(float)value {
5046 - (NSNumber *) total {
5047 return [NSNumber numberWithFloat:total_];
5050 - (void) setSpeed:(float)value {
5054 - (NSNumber *) speed {
5055 return [NSNumber numberWithFloat:speed_];
5058 - (NSArray *) events {
5062 - (void) removeAllEvents {
5063 [events_ removeAllObjects];
5066 - (void) addEvent:(CydiaProgressEvent *)event {
5067 [events_ addObject:event];
5070 - (void) setTitle:(NSString *)text {
5074 - (NSString *) title {
5078 - (void) setFinish:(NSString *)text {
5082 - (NSString *) finish {
5083 return (id) finish_ ?: [NSNull null];
5086 - (void) setRunning:(bool)running {
5090 - (NSNumber *) running {
5091 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5096 /* Progress Controller {{{ */
5097 @interface ProgressController : CYBrowserController <
5100 _transient Database *database_;
5101 _H<CydiaProgressData> progress_;
5105 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5107 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5109 - (void) setTitle:(NSString *)title;
5110 - (void) setCancellable:(bool)cancellable;
5114 @implementation ProgressController
5117 [database_ setProgressDelegate:nil];
5118 [progress_ setDelegate:nil];
5122 - (void) updateCancel {
5123 [[self navigationItem] setLeftBarButtonItem:(cancel_ == 1 ? [[[UIBarButtonItem alloc]
5124 initWithTitle:UCLocalize("CANCEL")
5125 style:UIBarButtonItemStylePlain
5127 action:@selector(cancel)
5128 ] autorelease] : nil)];
5131 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5132 if ((self = [super init]) != nil) {
5133 database_ = database;
5134 delegate_ = delegate;
5136 [database_ setProgressDelegate:self];
5138 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5139 [progress_ setDelegate:self];
5141 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5143 [scroller_ setBackgroundColor:[UIColor blackColor]];
5145 [[self navigationItem] setHidesBackButton:YES];
5147 [self updateCancel];
5151 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5152 [super webView:view didClearWindowObject:window forFrame:frame];
5153 [window setValue:progress_ forKey:@"cydiaProgress"];
5156 - (void) updateProgress {
5157 [self dispatchEvent:@"CydiaProgressUpdate"];
5160 - (void) viewWillAppear:(BOOL)animated {
5161 if (![self hasLoaded])
5162 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5164 [super viewWillAppear:animated];
5168 UpdateExternalStatus(0);
5175 [delegate_ terminateWithSuccess];
5176 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5177 [delegate_ suspendWithAnimation:YES];
5179 [delegate_ suspend];*/
5191 system("/usr/bin/sbreload");
5197 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5198 SBReboot(SBSSpringBoardServerPort());
5200 reboot2(RB_AUTOBOOT);
5207 - (void) setTitle:(NSString *)title {
5208 [progress_ setTitle:title];
5209 [self updateProgress];
5212 - (UIBarButtonItem *) rightButton {
5213 return [[progress_ running] boolValue] ? nil : [[[UIBarButtonItem alloc]
5214 initWithTitle:UCLocalize("CLOSE")
5215 style:UIBarButtonItemStylePlain
5217 action:@selector(close)
5221 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5222 UpdateExternalStatus(1);
5224 [progress_ setRunning:true];
5225 [self setTitle:title];
5226 // implicit updateProgress
5228 SHA1SumValue notifyconf; {
5230 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5233 MMap mmap(file, MMap::ReadOnly);
5235 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5236 notifyconf = sha1.Result();
5240 SHA1SumValue springlist; {
5242 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5245 MMap mmap(file, MMap::ReadOnly);
5247 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5248 springlist = sha1.Result();
5252 if (invocation != nil) {
5253 [invocation yieldToSelector:@selector(invoke)];
5254 [self setTitle:@"COMPLETE"];
5259 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5262 MMap mmap(file, MMap::ReadOnly);
5264 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5265 if (!(notifyconf == sha1.Result()))
5272 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5275 MMap mmap(file, MMap::ReadOnly);
5277 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5278 if (!(springlist == sha1.Result()))
5284 if (RestartSubstrate_)
5288 RestartSubstrate_ = false;
5291 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5292 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5293 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5294 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5295 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5299 system("su -c /usr/bin/uicache mobile");
5302 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5304 [progress_ setRunning:false];
5305 [self updateProgress];
5307 [self applyRightButton];
5310 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5311 [progress_ addEvent:event];
5312 [self updateProgress];
5315 - (bool) isProgressCancelled {
5316 return cancel_ == 2;
5321 [self updateCancel];
5324 - (void) setCancellable:(bool)cancellable {
5325 unsigned cancel(cancel_);
5329 else if (cancel_ == 0)
5332 if (cancel != cancel_)
5333 [self updateCancel];
5336 - (void) setProgressCancellable:(NSNumber *)cancellable {
5337 [self setCancellable:[cancellable boolValue]];
5340 - (void) setProgressPercent:(NSNumber *)percent {
5341 [progress_ setPercent:[percent floatValue]];
5342 [self updateProgress];
5345 - (void) setProgressStatus:(NSDictionary *)status {
5346 if (status == nil) {
5347 [progress_ setCurrent:0];
5348 [progress_ setTotal:0];
5349 [progress_ setSpeed:0];
5351 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5353 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5354 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5355 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5358 [self updateProgress];
5364 /* Cell Content View {{{ */
5365 @protocol ContentDelegate
5366 - (void) drawContentRect:(CGRect)rect;
5369 @interface ContentView : UIView {
5370 _transient id<ContentDelegate> delegate_;
5375 @implementation ContentView
5377 - (id) initWithFrame:(CGRect)frame {
5378 if ((self = [super initWithFrame:frame]) != nil) {
5379 [self setNeedsDisplayOnBoundsChange:YES];
5383 - (void) setDelegate:(id<ContentDelegate>)delegate {
5384 delegate_ = delegate;
5387 - (void) drawRect:(CGRect)rect {
5388 [super drawRect:rect];
5389 [delegate_ drawContentRect:rect];
5394 /* Cydia TableView Cell {{{ */
5395 @interface CYTableViewCell : UITableViewCell {
5396 ContentView *content_;
5402 @implementation CYTableViewCell
5409 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5410 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5412 if (view == content_) {
5413 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5414 highlighted_ = highlighted;
5417 [super _updateHighlightColorsForView:view highlighted:highlighted];
5420 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5421 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5422 highlighted_ = selected;
5424 [super setSelected:selected animated:animated];
5425 [content_ setNeedsDisplay];
5431 /* Package Cell {{{ */
5432 @interface PackageCell : CYTableViewCell <
5437 NSString *description_;
5445 - (PackageCell *) init;
5446 - (void) setPackage:(Package *)package;
5448 - (void) drawContentRect:(CGRect)rect;
5452 @implementation PackageCell
5454 - (void) clearPackage {
5465 if (description_ != nil) {
5466 [description_ release];
5470 if (source_ != nil) {
5475 if (badge_ != nil) {
5480 if (placard_ != nil) {
5490 [self clearPackage];
5494 - (PackageCell *) init {
5495 CGRect frame(CGRectMake(0, 0, 320, 74));
5496 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5497 UIView *content([self contentView]);
5498 CGRect bounds([content bounds]);
5500 content_ = [[ContentView alloc] initWithFrame:bounds];
5501 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5502 [content addSubview:content_];
5504 [content_ setDelegate:self];
5505 [content_ setOpaque:YES];
5509 - (NSString *) accessibilityLabel {
5510 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5513 - (void) setPackage:(Package *)package {
5514 [self clearPackage];
5517 Source *source = [package source];
5519 icon_ = [[package icon] retain];
5520 name_ = [[package name] retain];
5523 description_ = [package longDescription];
5524 if (description_ == nil)
5525 description_ = [package shortDescription];
5526 if (description_ != nil)
5527 description_ = [description_ retain];
5529 commercial_ = [package isCommercial];
5531 package_ = [package retain];
5533 NSString *label = nil;
5534 bool trusted = false;
5536 if (source != nil) {
5537 label = [source label];
5538 trusted = [source trusted];
5539 } else if ([[package id] isEqualToString:@"firmware"])
5540 label = UCLocalize("APPLE");
5542 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5544 NSString *from(label);
5546 NSString *section = [package simpleSection];
5547 if (section != nil && ![section isEqualToString:label]) {
5548 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5549 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5552 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5553 source_ = [from retain];
5555 if (NSString *purpose = [package primaryPurpose])
5556 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5557 badge_ = [badge_ retain];
5562 if (NSString *mode = [package_ mode]) {
5563 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5564 color = RemovingColor_;
5565 //placard = @"removing";
5567 color = InstallingColor_;
5568 //placard = @"installing";
5571 // XXX: the removing/installing placards are not @2x
5574 color = [UIColor whiteColor];
5576 if ([package installed] != nil)
5577 placard = @"installed";
5582 [content_ setBackgroundColor:color];
5585 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5586 placard_ = [placard_ retain];
5588 [self setNeedsDisplay];
5589 [content_ setNeedsDisplay];
5592 - (void) drawContentRect:(CGRect)rect {
5593 bool highlighted(highlighted_);
5594 float width([self bounds].size.width);
5597 CGContextRef context(UIGraphicsGetCurrentContext());
5598 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5599 CGContextFillRect(context, rect);
5604 rect.size = [icon_ size];
5606 rect.size.width /= 2;
5607 rect.size.height /= 2;
5609 rect.origin.x = 25 - rect.size.width / 2;
5610 rect.origin.y = 25 - rect.size.height / 2;
5612 [icon_ drawInRect:rect];
5615 if (badge_ != nil) {
5617 rect.size = [badge_ size];
5619 rect.size.width /= 2;
5620 rect.size.height /= 2;
5622 rect.origin.x = 36 - rect.size.width / 2;
5623 rect.origin.y = 36 - rect.size.height / 2;
5625 [badge_ drawInRect:rect];
5632 UISetColor(commercial_ ? Purple_ : Black_);
5633 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5634 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5637 UISetColor(commercial_ ? Purplish_ : Gray_);
5638 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5640 if (placard_ != nil)
5641 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5646 /* Section Cell {{{ */
5647 @interface SectionCell : CYTableViewCell <
5659 - (void) setSection:(Section *)section editing:(BOOL)editing;
5663 @implementation SectionCell
5665 - (void) clearSection {
5666 if (basic_ != nil) {
5671 if (section_ != nil) {
5681 if (count_ != nil) {
5688 [self clearSection];
5694 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5695 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5696 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5697 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5698 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5700 UIView *content([self contentView]);
5701 CGRect bounds([content bounds]);
5703 content_ = [[ContentView alloc] initWithFrame:bounds];
5704 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5705 [content addSubview:content_];
5706 [content_ setBackgroundColor:[UIColor whiteColor]];
5708 [content_ setDelegate:self];
5712 - (void) onSwitch:(id)sender {
5713 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5714 if (metadata == nil) {
5715 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5716 [Sections_ setObject:metadata forKey:basic_];
5719 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5723 - (void) setSection:(Section *)section editing:(BOOL)editing {
5724 if (editing != editing_) {
5726 [switch_ removeFromSuperview];
5728 [self addSubview:switch_];
5732 [self clearSection];
5734 if (section == nil) {
5735 name_ = [UCLocalize("ALL_PACKAGES") retain];
5738 basic_ = [section name];
5740 basic_ = [basic_ retain];
5742 section_ = [section localized];
5743 if (section_ != nil)
5744 section_ = [section_ retain];
5746 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5747 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5750 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5753 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5754 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5756 [content_ setNeedsDisplay];
5759 - (void) setFrame:(CGRect)frame {
5760 [super setFrame:frame];
5762 CGRect rect([switch_ frame]);
5763 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5766 - (NSString *) accessibilityLabel {
5770 - (void) drawContentRect:(CGRect)rect {
5771 bool highlighted(highlighted_ && !editing_);
5773 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5778 float width(rect.size.width);
5784 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5786 CGSize size = [count_ sizeWithFont:Font14_];
5790 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5796 /* File Table {{{ */
5797 @interface FileTable : CYViewController <
5798 UITableViewDataSource,
5801 _transient Database *database_;
5804 NSMutableArray *files_;
5808 - (id) initWithDatabase:(Database *)database;
5809 - (void) setPackage:(Package *)package;
5813 @implementation FileTable
5816 [self releaseSubviews];
5825 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5826 return files_ == nil ? 0 : [files_ count];
5829 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5833 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5834 static NSString *reuseIdentifier = @"Cell";
5836 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5838 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5839 [cell setFont:[UIFont systemFontOfSize:16]];
5841 [cell setText:[files_ objectAtIndex:indexPath.row]];
5842 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5847 - (NSURL *) navigationURL {
5848 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5852 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5854 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5855 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5856 [list_ setRowHeight:24.0f];
5857 [list_ setDataSource:self];
5858 [list_ setDelegate:self];
5859 [[self view] addSubview:list_];
5862 - (void) viewDidLoad {
5863 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5866 - (void) releaseSubviews {
5871 - (id) initWithDatabase:(Database *)database {
5872 if ((self = [super init]) != nil) {
5873 database_ = database;
5875 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5879 - (void) setPackage:(Package *)package {
5880 if (package_ != nil) {
5881 [package_ autorelease];
5890 [files_ removeAllObjects];
5892 if (package != nil) {
5893 package_ = [package retain];
5894 name_ = [[package id] retain];
5896 if (NSArray *files = [package files])
5897 [files_ addObjectsFromArray:files];
5899 if ([files_ count] != 0) {
5900 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5901 [files_ removeObjectAtIndex:0];
5902 [files_ sortUsingSelector:@selector(compareByPath:)];
5904 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5905 [stack addObject:@"/"];
5907 for (int i(0), e([files_ count]); i != e; ++i) {
5908 NSString *file = [files_ objectAtIndex:i];
5909 while (![file hasPrefix:[stack lastObject]])
5910 [stack removeLastObject];
5911 NSString *directory = [stack lastObject];
5912 [stack addObject:[file stringByAppendingString:@"/"]];
5913 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5914 ([stack count] - 2) * 3, "",
5915 [file substringFromIndex:[directory length]]
5924 - (void) reloadData {
5927 [self setPackage:[database_ packageWithName:name_]];
5932 /* Package Controller {{{ */
5933 @interface CYPackageController : CYBrowserController <
5934 UIActionSheetDelegate
5936 _transient Database *database_;
5937 _H<Package> package_;
5940 _H<NSMutableArray> buttons_;
5941 _H<UIBarButtonItem> button_;
5944 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5948 @implementation CYPackageController
5950 - (NSURL *) navigationURL {
5951 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5954 /* XXX: this is not safe at all... localization of /fail/ */
5955 - (void) _clickButtonWithName:(NSString *)name {
5956 if ([name isEqualToString:UCLocalize("CLEAR")])
5957 [delegate_ clearPackage:package_];
5958 else if ([name isEqualToString:UCLocalize("INSTALL")])
5959 [delegate_ installPackage:package_];
5960 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5961 [delegate_ installPackage:package_];
5962 else if ([name isEqualToString:UCLocalize("REMOVE")])
5963 [delegate_ removePackage:package_];
5964 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5965 [delegate_ installPackage:package_];
5966 else _assert(false);
5969 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5970 NSString *context([sheet context]);
5972 if ([context isEqualToString:@"modify"]) {
5973 if (button != [sheet cancelButtonIndex]) {
5974 NSString *buttonName = [buttons_ objectAtIndex:button];
5975 [self _clickButtonWithName:buttonName];
5978 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5982 - (bool) _allowJavaScriptPanel {
5987 - (void) _customButtonClicked {
5988 int count([buttons_ count]);
5993 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5995 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5996 [buttons addObjectsFromArray:buttons_];
5998 UIActionSheet *sheet = [[[UIActionSheet alloc]
6001 cancelButtonTitle:nil
6002 destructiveButtonTitle:nil
6003 otherButtonTitles:nil
6006 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6008 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6009 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6011 [sheet setContext:@"modify"];
6013 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6017 // We don't want to allow non-commercial packages to do custom things to the install button,
6018 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6019 - (void) customButtonClicked {
6021 [super customButtonClicked];
6023 [self _customButtonClicked];
6026 - (void) reloadButtonClicked {
6027 // Don't reload a commerical package by tapping the loading button,
6028 // but if it's not an Install button, we should forward it on.
6029 if (![package_ uninstalled])
6030 [self _customButtonClicked];
6033 - (void) applyLoadingTitle {
6034 // Don't show "Loading" as the title. Ever.
6037 - (UIBarButtonItem *) rightButton {
6042 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
6043 if ((self = [super init]) != nil) {
6044 database_ = database;
6045 buttons_ = [NSMutableArray arrayWithCapacity:4];
6046 name_ = [NSString stringWithString:name];
6047 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
6051 - (void) reloadData {
6052 package_ = [database_ packageWithName:name_];
6054 [buttons_ removeAllObjects];
6056 if (package_ != nil) {
6057 [(Package *) package_ parse];
6059 commercial_ = [package_ isCommercial];
6061 if ([package_ mode] != nil)
6062 [buttons_ addObject:UCLocalize("CLEAR")];
6063 if ([package_ source] == nil);
6064 else if ([package_ upgradableAndEssential:NO])
6065 [buttons_ addObject:UCLocalize("UPGRADE")];
6066 else if ([package_ uninstalled])
6067 [buttons_ addObject:UCLocalize("INSTALL")];
6069 [buttons_ addObject:UCLocalize("REINSTALL")];
6070 if (![package_ uninstalled])
6071 [buttons_ addObject:UCLocalize("REMOVE")];
6075 switch ([buttons_ count]) {
6076 case 0: title = nil; break;
6077 case 1: title = [buttons_ objectAtIndex:0]; break;
6078 default: title = UCLocalize("MODIFY"); break;
6081 button_ = [[[UIBarButtonItem alloc]
6083 style:UIBarButtonItemStylePlain
6085 action:@selector(customButtonClicked)
6091 - (bool) isLoading {
6092 return commercial_ ? [super isLoading] : false;
6098 /* Package List Controller {{{ */
6099 @interface PackageListController : CYViewController <
6100 UITableViewDataSource,
6103 _transient Database *database_;
6105 NSMutableArray *packages_;
6106 NSMutableArray *sections_;
6108 NSMutableArray *index_;
6109 NSMutableDictionary *indices_;
6113 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6114 - (void) setDelegate:(id)delegate;
6115 - (void) resetCursor;
6119 @implementation PackageListController
6122 [packages_ release];
6123 [sections_ release];
6132 - (void) deselectWithAnimation:(BOOL)animated {
6133 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6136 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6137 CGRect base = [[self view] bounds];
6138 base.size.height -= bounds.size.height;
6139 base.origin = [list_ frame].origin;
6141 [UIView beginAnimations:nil context:NULL];
6142 [UIView setAnimationBeginsFromCurrentState:YES];
6143 [UIView setAnimationCurve:curve];
6144 [UIView setAnimationDuration:duration];
6145 [list_ setFrame:base];
6146 [UIView commitAnimations];
6149 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6150 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6153 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6154 [self resizeForKeyboardBounds:bounds duration:0];
6157 - (void) keyboardWillShow:(NSNotification *)notification {
6160 NSTimeInterval duration;
6161 UIViewAnimationCurve curve;
6162 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6163 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6164 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6165 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6167 CGRect kbframe = CGRectMake(round(center.x - bounds.size.width / 2.0), round(center.y - bounds.size.height / 2.0), bounds.size.width, bounds.size.height);
6168 UIViewController *base = self;
6169 while ([base parentViewController] != nil)
6170 base = [base parentViewController];
6171 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6172 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6174 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6177 - (void) keyboardWillHide:(NSNotification *)notification {
6178 NSTimeInterval duration;
6179 UIViewAnimationCurve curve;
6180 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6181 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6183 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6186 - (void) viewWillAppear:(BOOL)animated {
6187 [super viewWillAppear:animated];
6189 [self resizeForKeyboardBounds:CGRectZero];
6190 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6191 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6194 - (void) viewWillDisappear:(BOOL)animated {
6195 [super viewWillDisappear:animated];
6197 [self resizeForKeyboardBounds:CGRectZero];
6198 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6199 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6202 - (void) viewDidAppear:(BOOL)animated {
6203 [super viewDidAppear:animated];
6204 [self deselectWithAnimation:animated];
6207 - (void) didSelectPackage:(Package *)package {
6208 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6209 [view setDelegate:delegate_];
6210 [[self navigationController] pushViewController:view animated:YES];
6213 #if TryIndexedCollation
6214 + (BOOL) hasIndexedCollation {
6215 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6219 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6220 NSInteger count([sections_ count]);
6221 return count == 0 ? 1 : count;
6224 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6225 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6227 return [[sections_ objectAtIndex:section] name];
6230 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6231 if ([sections_ count] == 0)
6233 return [[sections_ objectAtIndex:section] count];
6236 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6237 @synchronized (database_) {
6238 if ([database_ era] != era_)
6241 Section *section([sections_ objectAtIndex:[path section]]);
6242 NSInteger row([path row]);
6243 Package *package([packages_ objectAtIndex:([section row] + row)]);
6244 return [[package retain] autorelease];
6247 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6248 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6250 cell = [[[PackageCell alloc] init] autorelease];
6251 [cell setPackage:[self packageAtIndexPath:path]];
6255 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6256 Package *package([self packageAtIndexPath:path]);
6257 package = [database_ packageWithName:[package id]];
6258 [self didSelectPackage:package];
6261 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6262 // XXX: is 20 the most optimal number here?
6263 return [packages_ count] > 20 ? index_ : nil;
6266 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6267 #if TryIndexedCollation
6268 if ([[self class] hasIndexedCollation]) {
6269 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6276 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6277 if ((self = [super init]) != nil) {
6278 database_ = database;
6279 title_ = [title copy];
6280 [[self navigationItem] setTitle:title_];
6282 #if TryIndexedCollation
6283 if ([[self class] hasIndexedCollation])
6284 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6287 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6289 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6291 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6292 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6294 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6295 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6296 [list_ setRowHeight:73];
6297 [[self view] addSubview:list_];
6299 [list_ setDataSource:self];
6300 [list_ setDelegate:self];
6304 - (void) setDelegate:(id)delegate {
6305 delegate_ = delegate;
6308 - (bool) hasPackage:(Package *)package {
6312 - (void) reloadData {
6315 era_ = [database_ era];
6316 NSArray *packages = [database_ packages];
6318 [packages_ removeAllObjects];
6319 [sections_ removeAllObjects];
6321 _profile(PackageTable$reloadData$Filter)
6322 for (Package *package in packages)
6323 if ([self hasPackage:package])
6324 [packages_ addObject:package];
6327 [indices_ removeAllObjects];
6329 Section *section = nil;
6331 #if TryIndexedCollation
6332 if ([[self class] hasIndexedCollation]) {
6333 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6334 NSArray *titles = [collation sectionIndexTitles];
6337 _profile(PackageTable$reloadData$Section)
6338 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6342 _profile(PackageTable$reloadData$Section$Package)
6343 package = [packages_ objectAtIndex:offset];
6344 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6347 while (secidx < index) {
6350 _profile(PackageTable$reloadData$Section$Allocate)
6351 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6354 _profile(PackageTable$reloadData$Section$Add)
6355 [sections_ addObject:section];
6359 [section addToCount];
6365 [index_ removeAllObjects];
6367 _profile(PackageTable$reloadData$Section)
6368 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6372 _profile(PackageTable$reloadData$Section$Package)
6373 package = [packages_ objectAtIndex:offset];
6374 index = [package index];
6377 if (section == nil || [section index] != index) {
6378 _profile(PackageTable$reloadData$Section$Allocate)
6379 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6382 [index_ addObject:[section name]];
6383 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6385 _profile(PackageTable$reloadData$Section$Add)
6386 [sections_ addObject:section];
6390 [section addToCount];
6395 _profile(PackageTable$reloadData$List)
6400 - (void) resetCursor {
6401 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6406 /* Filtered Package List Controller {{{ */
6407 @interface FilteredPackageListController : PackageListController {
6413 - (void) setObject:(id)object;
6414 - (void) setObject:(id)object forFilter:(SEL)filter;
6416 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6420 @implementation FilteredPackageListController
6428 - (void) setFilter:(SEL)filter {
6431 /* XXX: this is an unsafe optimization of doomy hell */
6432 Method method(class_getInstanceMethod([Package class], filter));
6433 _assert(method != NULL);
6434 imp_ = method_getImplementation(method);
6435 _assert(imp_ != NULL);
6438 - (void) setObject:(id)object {
6444 object_ = [object retain];
6447 - (void) setObject:(id)object forFilter:(SEL)filter {
6448 [self setFilter:filter];
6449 [self setObject:object];
6452 - (bool) hasPackage:(Package *)package {
6453 _profile(FilteredPackageTable$hasPackage)
6454 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6458 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6459 if ((self = [super initWithDatabase:database title:title]) != nil) {
6460 [self setFilter:filter];
6461 [self setObject:object];
6468 /* Home Controller {{{ */
6469 @interface HomeController : CYBrowserController {
6474 @implementation HomeController
6477 if ((self = [super init]) != nil) {
6478 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6482 - (NSURL *) navigationURL {
6483 return [NSURL URLWithString:@"cydia://home"];
6486 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6487 [super _setMoreHeaders:request];
6490 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6491 if (UniqueID_ != nil)
6492 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6494 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6497 - (void) aboutButtonClicked {
6498 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6500 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6501 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6502 [alert setCancelButtonIndex:0];
6505 @"Copyright (C) 2008-2011\n"
6506 "Jay Freeman (saurik)\n"
6507 "saurik@saurik.com\n"
6508 "http://www.saurik.com/"
6514 - (void) viewDidLoad {
6515 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6516 initWithTitle:UCLocalize("ABOUT")
6517 style:UIBarButtonItemStylePlain
6519 action:@selector(aboutButtonClicked)
6525 /* Manage Controller {{{ */
6526 @interface ManageController : CYBrowserController {
6529 - (void) queueStatusDidChange;
6533 @implementation ManageController
6536 if ((self = [super init]) != nil) {
6537 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6541 - (NSURL *) navigationURL {
6542 return [NSURL URLWithString:@"cydia://manage"];
6545 - (void) viewDidLoad {
6546 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6547 initWithTitle:UCLocalize("SETTINGS")
6548 style:UIBarButtonItemStylePlain
6550 action:@selector(settingsButtonClicked)
6553 [self queueStatusDidChange];
6556 - (void) settingsButtonClicked {
6557 [delegate_ showSettings];
6561 - (void) queueButtonClicked {
6565 - (void) applyLoadingTitle {
6566 // Disable "Loading" title.
6569 - (void) applyRightButton {
6570 // Disable right button.
6574 - (void) queueStatusDidChange {
6576 if (!IsWildcat_ && Queuing_) {
6577 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6578 initWithTitle:UCLocalize("QUEUE")
6579 style:UIBarButtonItemStyleDone
6581 action:@selector(queueButtonClicked)
6584 [[self navigationItem] setRightBarButtonItem:nil];
6589 - (bool) isLoading {
6590 // Never show as loading.
6597 /* Refresh Bar {{{ */
6598 @interface RefreshBar : UINavigationBar {
6599 UIProgressIndicator *indicator_;
6600 UITextLabel *prompt_;
6601 UIProgressBar *progress_;
6602 UINavigationButton *cancel_;
6607 @implementation RefreshBar
6610 [indicator_ release];
6612 [progress_ release];
6617 - (void) positionViews {
6618 CGRect frame = [cancel_ frame];
6619 frame.size = [cancel_ sizeThatFits:frame.size];
6620 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6621 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6622 [cancel_ setFrame:frame];
6624 CGSize prgsize = {75, 100};
6626 [self frame].size.width - prgsize.width - 10,
6627 ([self frame].size.height - prgsize.height) / 2
6629 [progress_ setFrame:prgrect];
6631 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6632 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6633 CGRect indrect = {{indoffset, indoffset}, indsize};
6634 [indicator_ setFrame:indrect];
6636 CGSize prmsize = {215, indsize.height + 4};
6638 indoffset * 2 + indsize.width,
6639 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6641 [prompt_ setFrame:prmrect];
6644 - (void) setFrame:(CGRect)frame {
6645 [super setFrame:frame];
6646 [self positionViews];
6649 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6650 if ((self = [super initWithFrame:frame]) != nil) {
6651 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6653 [self setBarStyle:UIBarStyleBlack];
6655 UIBarStyle barstyle([self _barStyle:NO]);
6656 bool ugly(barstyle == UIBarStyleDefault);
6658 UIProgressIndicatorStyle style = ugly ?
6659 UIProgressIndicatorStyleMediumBrown :
6660 UIProgressIndicatorStyleMediumWhite;
6662 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6663 [indicator_ setStyle:style];
6664 [indicator_ startAnimation];
6665 [self addSubview:indicator_];
6667 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6668 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6669 [prompt_ setBackgroundColor:[UIColor clearColor]];
6670 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6671 [self addSubview:prompt_];
6673 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6674 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6675 [progress_ setStyle:0];
6676 [self addSubview:progress_];
6678 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6679 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6680 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6681 [cancel_ setBarStyle:barstyle];
6683 [self positionViews];
6687 - (void) setCancellable:(bool)cancellable {
6689 [self addSubview:cancel_];
6691 [cancel_ removeFromSuperview];
6695 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6696 [progress_ setProgress:0];
6700 [self setCancellable:NO];
6703 - (void) setPrompt:(NSString *)prompt {
6704 [prompt_ setText:prompt];
6707 - (void) setProgress:(float)progress {
6708 [progress_ setProgress:progress];
6714 @class CYNavigationController;
6716 /* Cydia Tab Bar Controller {{{ */
6717 @interface CYTabBarController : UITabBarController <
6718 UITabBarControllerDelegate,
6721 _transient Database *database_;
6722 RefreshBar *refreshbar_;
6726 // XXX: ok, "updatedelegate_"?...
6727 _transient NSObject<CydiaDelegate> *updatedelegate_;
6730 UIViewController *remembered_;
6731 _transient UIViewController *transient_;
6734 - (NSArray *) navigationURLCollection;
6735 - (void) dropBar:(BOOL)animated;
6736 - (void) beginUpdate;
6737 - (void) raiseBar:(BOOL)animated;
6742 @implementation CYTabBarController
6744 - (void) setUnselectedViewController:(UIViewController *)transient {
6745 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6746 if (transient != nil) {
6747 if (transient_ == nil)
6748 remembered_ = [[controllers objectAtIndex:0] retain];
6749 transient_ = transient;
6750 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6751 [controllers replaceObjectAtIndex:0 withObject:transient_];
6752 [self setSelectedIndex:0];
6753 [self setViewControllers:controllers];
6754 [self concealTabBarSelection];
6755 } else if (remembered_ != nil) {
6756 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6757 transient_ = transient;
6758 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6759 [remembered_ release];
6761 [self setViewControllers:controllers];
6762 [self revealTabBarSelection];
6766 - (UIViewController *) unselectedViewController {
6770 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6771 if ([self unselectedViewController])
6772 [self setUnselectedViewController:nil];
6775 - (NSArray *) navigationURLCollection {
6776 NSMutableArray *items([NSMutableArray array]);
6778 // XXX: Should this deal with transient view controllers?
6779 for (id navigation in [self viewControllers]) {
6780 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6782 [items addObject:stack];
6788 - (void) reloadData {
6789 for (CYViewController *controller in [self viewControllers])
6790 [controller reloadData];
6792 [(CYNavigationController *)[self unselectedViewController] reloadData];
6796 [refreshbar_ release];
6797 [[NSNotificationCenter defaultCenter] removeObserver:self];
6802 - (id) initWithDatabase:(Database *)database {
6803 if ((self = [super init]) != nil) {
6804 database_ = database;
6805 [self setDelegate:self];
6807 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6808 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6810 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6814 - (void) setUpdate:(NSDate *)date {
6818 - (void) beginUpdate {
6819 [refreshbar_ start];
6822 [updatedelegate_ retainNetworkActivityIndicator];
6826 detachNewThreadSelector:@selector(performUpdate)
6832 - (void) performUpdate { _pooled
6834 status.setDelegate(self);
6835 [database_ updateWithStatus:status];
6838 performSelectorOnMainThread:@selector(completeUpdate)
6844 - (void) stopUpdateWithSelector:(SEL)selector {
6846 [updatedelegate_ releaseNetworkActivityIndicator];
6848 [self raiseBar:YES];
6851 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6854 - (void) completeUpdate {
6857 [self stopUpdateWithSelector:@selector(reloadData)];
6860 - (void) cancelUpdate {
6861 [self stopUpdateWithSelector:@selector(updateData)];
6864 - (void) cancelPressed {
6865 [self cancelUpdate];
6872 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6873 [refreshbar_ setPrompt:[event compoundMessage]];
6876 - (bool) isProgressCancelled {
6880 - (void) setProgressCancellable:(NSNumber *)cancellable {
6881 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6884 - (void) setProgressPercent:(NSNumber *)percent {
6885 [refreshbar_ setProgress:[percent floatValue]];
6888 - (void) setProgressStatus:(NSDictionary *)status {
6890 [self setProgressPercent:[status objectForKey:@"Percent"]];
6893 - (void) setUpdateDelegate:(id)delegate {
6894 updatedelegate_ = delegate;
6897 - (CGFloat) statusBarHeight {
6898 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6899 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6901 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6905 - (UIView *) transitionView {
6906 if ([self respondsToSelector:@selector(_transitionView)])
6907 return [self _transitionView];
6909 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6912 - (void) dropBar:(BOOL)animated {
6917 UIView *transition([self transitionView]);
6918 [[self view] addSubview:refreshbar_];
6920 CGRect barframe([refreshbar_ frame]);
6922 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6923 barframe.origin.y = [self statusBarHeight];
6925 barframe.origin.y = 0;
6927 [refreshbar_ setFrame:barframe];
6930 [UIView beginAnimations:nil context:NULL];
6932 CGRect viewframe = [transition frame];
6933 viewframe.origin.y += barframe.size.height;
6934 viewframe.size.height -= barframe.size.height;
6935 [transition setFrame:viewframe];
6938 [UIView commitAnimations];
6940 // Ensure bar has the proper width for our view, it might have changed
6941 barframe.size.width = viewframe.size.width;
6942 [refreshbar_ setFrame:barframe];
6944 // XXX: fix Apple's layout bug
6945 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6948 - (void) raiseBar:(BOOL)animated {
6953 UIView *transition([self transitionView]);
6954 [refreshbar_ removeFromSuperview];
6956 CGRect barframe([refreshbar_ frame]);
6959 [UIView beginAnimations:nil context:NULL];
6961 CGRect viewframe = [transition frame];
6962 viewframe.origin.y -= barframe.size.height;
6963 viewframe.size.height += barframe.size.height;
6964 [transition setFrame:viewframe];
6967 [UIView commitAnimations];
6969 // XXX: fix Apple's layout bug
6970 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6974 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6975 // XXX: fix Apple's layout bug
6976 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6980 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6981 bool dropped(dropped_);
6986 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6991 // XXX: fix Apple's layout bug
6992 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6995 - (void) statusBarFrameChanged:(NSNotification *)notification {
7004 /* Cydia Navigation Controller {{{ */
7005 @interface CYNavigationController : UINavigationController {
7006 _transient Database *database_;
7007 _transient id<UINavigationControllerDelegate> delegate_;
7010 - (NSArray *) navigationURLCollection;
7011 - (id) initWithDatabase:(Database *)database;
7012 - (void) reloadData;
7017 @implementation CYNavigationController
7019 - (NSArray *) navigationURLCollection {
7020 NSMutableArray *stack([NSMutableArray array]);
7022 for (CYViewController *controller in [self viewControllers]) {
7023 NSString *url = [[controller navigationURL] absoluteString];
7025 [stack addObject:url];
7031 - (void) reloadData {
7032 for (CYViewController *page in [self viewControllers]) {
7033 // Only reload controllers that have already loaded.
7034 // This prevents a page from accidentally loading too
7035 // early if it hasn't been shown on the screen yet.
7036 if ([page hasLoaded])
7041 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
7042 delegate_ = delegate;
7045 - (id) initWithDatabase:(Database *)database {
7046 if ((self = [super init]) != nil) {
7047 database_ = database;
7054 /* Cydia:// Protocol {{{ */
7055 @interface CydiaURLProtocol : NSURLProtocol {
7060 @implementation CydiaURLProtocol
7062 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7063 NSURL *url([request URL]);
7067 NSString *scheme([[url scheme] lowercaseString]);
7068 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7070 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7076 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7080 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7081 id<NSURLProtocolClient> client([self client]);
7083 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7085 NSData *data(UIImagePNGRepresentation(icon));
7087 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7088 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7089 [client URLProtocol:self didLoadData:data];
7090 [client URLProtocolDidFinishLoading:self];
7094 - (void) startLoading {
7095 id<NSURLProtocolClient> client([self client]);
7096 NSURLRequest *request([self request]);
7098 NSURL *url([request URL]);
7099 NSString *href([url absoluteString]);
7100 NSString *scheme([[url scheme] lowercaseString]);
7104 if ([scheme isEqualToString:@"cydia"])
7105 path = [href substringFromIndex:8];
7106 else if ([scheme isEqualToString:@"about"])
7107 path = [href substringFromIndex:12];
7108 else _assert(false);
7110 NSRange slash([path rangeOfString:@"/"]);
7113 if (slash.location == NSNotFound) {
7117 command = [path substringToIndex:slash.location];
7118 path = [path substringFromIndex:(slash.location + 1)];
7121 Database *database([Database sharedInstance]);
7123 if ([command isEqualToString:@"package-icon"]) {
7126 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7127 Package *package([database packageWithName:path]);
7130 UIImage *icon([package icon]);
7131 [self _returnPNGWithImage:icon forRequest:request];
7132 } else if ([command isEqualToString:@"source-icon"]) {
7135 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7136 NSString *source(Simplify(path));
7137 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7139 icon = [UIImage applicationImageNamed:@"unknown.png"];
7140 [self _returnPNGWithImage:icon forRequest:request];
7141 } else if ([command isEqualToString:@"uikit-image"]) {
7144 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7145 UIImage *icon(_UIImageWithName(path));
7146 [self _returnPNGWithImage:icon forRequest:request];
7147 } else if ([command isEqualToString:@"section-icon"]) {
7150 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7151 NSString *section(Simplify(path));
7152 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7154 icon = [UIImage applicationImageNamed:@"unknown.png"];
7155 [self _returnPNGWithImage:icon forRequest:request];
7157 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7161 - (void) stopLoading {
7167 /* Section Controller {{{ */
7168 @interface SectionController : FilteredPackageListController {
7169 _H<NSString> section_;
7172 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7176 @implementation SectionController
7178 - (NSURL *) navigationURL {
7179 NSString *name = section_;
7183 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7186 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7189 title = UCLocalize("ALL_PACKAGES");
7190 else if (![name isEqual:@""])
7191 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7193 title = UCLocalize("NO_SECTION");
7195 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7202 /* Sections Controller {{{ */
7203 @interface SectionsController : CYViewController <
7204 UITableViewDataSource,
7207 _transient Database *database_;
7208 NSMutableArray *sections_;
7209 NSMutableArray *filtered_;
7214 - (id) initWithDatabase:(Database *)database;
7215 - (void) editButtonClicked;
7219 @implementation SectionsController
7222 [self releaseSubviews];
7223 [sections_ release];
7224 [filtered_ release];
7229 - (NSURL *) navigationURL {
7230 return [NSURL URLWithString:@"cydia://sections"];
7233 - (void) updateNavigationItem {
7234 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7235 if ([sections_ count] == 0) {
7236 [[self navigationItem] setRightBarButtonItem:nil];
7238 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7239 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7241 action:@selector(editButtonClicked)
7242 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7246 - (BOOL) isEditing {
7250 - (void) setEditing:(BOOL)editing {
7251 if ((editing_ = editing))
7254 [delegate_ updateData];
7256 [self updateNavigationItem];
7259 - (void) viewDidAppear:(BOOL)animated {
7260 [super viewDidAppear:animated];
7261 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7264 - (void) viewWillDisappear:(BOOL)animated {
7265 [super viewWillDisappear:animated];
7266 if (editing_) [self setEditing:NO];
7269 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7270 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7274 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7275 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7278 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7282 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7283 static NSString *reuseIdentifier = @"SectionCell";
7285 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7287 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7289 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7294 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7298 Section *section = [self sectionAtIndexPath:indexPath];
7300 SectionController *controller = [[[SectionController alloc]
7301 initWithDatabase:database_
7302 section:[section name]
7304 [controller setDelegate:delegate_];
7306 [[self navigationController] pushViewController:controller animated:YES];
7310 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7312 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7313 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7314 [list_ setRowHeight:45.0f];
7315 [list_ setDataSource:self];
7316 [list_ setDelegate:self];
7317 [[self view] addSubview:list_];
7320 - (void) viewDidLoad {
7321 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7324 - (void) releaseSubviews {
7329 - (id) initWithDatabase:(Database *)database {
7330 if ((self = [super init]) != nil) {
7331 database_ = database;
7333 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7334 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7338 - (void) reloadData {
7341 NSArray *packages = [database_ packages];
7343 [sections_ removeAllObjects];
7344 [filtered_ removeAllObjects];
7346 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7349 for (Package *package in packages) {
7350 NSString *name([package section]);
7351 NSString *key(name == nil ? @"" : name);
7355 _profile(SectionsView$reloadData$Section)
7356 section = [sections objectForKey:key];
7357 if (section == nil) {
7358 _profile(SectionsView$reloadData$Section$Allocate)
7359 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7360 [sections setObject:section forKey:key];
7365 [section addToCount];
7367 _profile(SectionsView$reloadData$Filter)
7368 if (![package valid] || ![package visible])
7376 [sections_ addObjectsFromArray:[sections allValues]];
7378 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7380 for (Section *section in sections_) {
7381 size_t count([section row]);
7385 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7386 [section setCount:count];
7387 [filtered_ addObject:section];
7390 [self updateNavigationItem];
7395 - (void) editButtonClicked {
7396 [self setEditing:(!editing_)];
7402 /* Changes Controller {{{ */
7403 @interface ChangesController : CYViewController <
7404 UITableViewDataSource,
7407 _transient Database *database_;
7409 CFMutableArrayRef packages_;
7410 NSMutableArray *sections_;
7413 BOOL hasSentFirstLoad_;
7416 - (id) initWithDatabase:(Database *)database;
7420 @implementation ChangesController
7423 [self releaseSubviews];
7424 CFRelease(packages_);
7425 [sections_ release];
7430 - (NSURL *) navigationURL {
7431 return [NSURL URLWithString:@"cydia://changes"];
7434 - (void) viewWillAppear:(BOOL)animated {
7435 // Loads after it appears, so don't load beforehand.
7437 [super viewWillAppear:animated];
7440 - (void) viewDidAppear:(BOOL)animated {
7441 [super viewDidAppear:animated];
7443 if (!hasSentFirstLoad_) {
7444 hasSentFirstLoad_ = YES;
7445 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7447 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7451 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7452 NSInteger count([sections_ count]);
7453 return count == 0 ? 1 : count;
7456 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7457 if ([sections_ count] == 0)
7459 return [[sections_ objectAtIndex:section] name];
7462 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7463 if ([sections_ count] == 0)
7465 return [[sections_ objectAtIndex:section] count];
7468 - (Package *) packageAtIndex:(NSUInteger)index {
7469 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7472 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7473 @synchronized (database_) {
7474 if ([database_ era] != era_)
7477 NSUInteger sectionIndex([path section]);
7478 if (sectionIndex >= [sections_ count])
7480 Section *section([sections_ objectAtIndex:sectionIndex]);
7481 NSInteger row([path row]);
7482 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7485 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7486 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7488 cell = [[[PackageCell alloc] init] autorelease];
7489 [cell setPackage:[self packageAtIndexPath:path]];
7493 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7494 Package *package([self packageAtIndexPath:path]);
7495 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7496 [view setDelegate:delegate_];
7497 [[self navigationController] pushViewController:view animated:YES];
7501 - (void) refreshButtonClicked {
7502 [delegate_ beginUpdate];
7503 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7506 - (void) upgradeButtonClicked {
7507 [delegate_ distUpgrade];
7511 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7513 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7514 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7515 [list_ setRowHeight:73];
7516 [list_ setDataSource:self];
7517 [list_ setDelegate:self];
7518 [[self view] addSubview:list_];
7521 - (void) viewDidLoad {
7522 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7525 - (void) releaseSubviews {
7530 - (id) initWithDatabase:(Database *)database {
7531 if ((self = [super init]) != nil) {
7532 database_ = database;
7534 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7535 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7539 // this mostly works because reloadData (below) is @synchronized (database_)
7540 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7541 - (void) _reloadPackages:(NSArray *)packages {
7542 CFRelease(packages_);
7543 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7546 _profile(ChangesController$_reloadPackages$Filter)
7547 for (Package *package in packages)
7548 if ([package upgradableAndEssential:YES] || [package visible])
7549 CFArrayAppendValue(packages_, package);
7552 _profile(ChangesController$_reloadPackages$radixSort)
7553 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7558 - (void) reloadData {
7559 @synchronized (database_) {
7560 era_ = [database_ era];
7561 NSArray *packages = [database_ packages];
7563 [sections_ removeAllObjects];
7566 UIProgressHUD *hud([delegate_ addProgressHUD]);
7567 [hud setText:UCLocalize("LOADING")];
7568 //NSLog(@"HUD:%@::%@", delegate_, hud);
7569 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7570 [delegate_ removeProgressHUD:hud];
7572 [self _reloadPackages:packages];
7575 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7576 Section *ignored = nil;
7577 Section *section = nil;
7581 bool unseens = false;
7583 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7585 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7586 Package *package = [self packageAtIndex:offset];
7588 BOOL uae = [package upgradableAndEssential:YES];
7592 time_t seen([package seen]);
7594 if (section == nil || last != seen) {
7598 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7601 _profile(ChangesController$reloadData$Allocate)
7602 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7603 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7604 [sections_ addObject:section];
7608 [section addToCount];
7609 } else if ([package ignored]) {
7610 if (ignored == nil) {
7611 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7613 [ignored addToCount];
7616 [upgradable addToCount];
7621 CFRelease(formatter);
7624 Section *last = [sections_ lastObject];
7625 size_t count = [last count];
7626 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7627 [sections_ removeLastObject];
7630 if ([ignored count] != 0)
7631 [sections_ insertObject:ignored atIndex:0];
7633 [sections_ insertObject:upgradable atIndex:0];
7638 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7639 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7640 style:UIBarButtonItemStylePlain
7642 action:@selector(upgradeButtonClicked)
7645 if (![delegate_ updating])
7646 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7647 initWithTitle:UCLocalize("REFRESH")
7648 style:UIBarButtonItemStylePlain
7650 action:@selector(refreshButtonClicked)
7658 /* Search Controller {{{ */
7659 @interface SearchController : FilteredPackageListController <
7662 _H<UISearchBar> search_;
7666 - (id) initWithDatabase:(Database *)database;
7667 - (void) setSearchTerm:(NSString *)term;
7668 - (void) reloadData;
7672 @implementation SearchController
7675 [search_ setDelegate:nil];
7679 - (NSURL *) navigationURL {
7680 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7681 return [NSURL URLWithString:@"cydia://search"];
7683 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7686 - (void) setSearchTerm:(NSString *)searchTerm {
7687 [search_ setText:searchTerm];
7691 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7692 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7693 [search_ resignFirstResponder];
7697 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7698 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7702 - (id) initWithDatabase:(Database *)database {
7703 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7704 search_ = [[[UISearchBar alloc] init] autorelease];
7705 [search_ setDelegate:self];
7709 - (void) viewDidAppear:(BOOL)animated {
7710 [super viewDidAppear:animated];
7712 if (!searchloaded_) {
7713 searchloaded_ = YES;
7714 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7715 [search_ layoutSubviews];
7716 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7718 UITextField *textField;
7719 if ([search_ respondsToSelector:@selector(searchField)])
7720 textField = [search_ searchField];
7722 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7724 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7725 [textField setEnablesReturnKeyAutomatically:NO];
7726 [[self navigationItem] setTitleView:textField];
7730 - (void) reloadData {
7731 [self setObject:[search_ text]];
7736 - (void) didSelectPackage:(Package *)package {
7737 [search_ resignFirstResponder];
7738 [super didSelectPackage:package];
7743 /* Package Settings Controller {{{ */
7744 @interface PackageSettingsController : CYViewController <
7745 UITableViewDataSource,
7748 _transient Database *database_;
7751 UITableView *table_;
7752 UISwitch *subscribedSwitch_;
7753 UISwitch *ignoredSwitch_;
7754 UITableViewCell *subscribedCell_;
7755 UITableViewCell *ignoredCell_;
7758 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7762 @implementation PackageSettingsController
7765 [self releaseSubviews];
7772 - (NSURL *) navigationURL {
7773 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7776 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7777 if (package_ == nil)
7780 if ([package_ installed] == nil)
7786 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7787 if (package_ == nil)
7790 // both sections contain just one item right now.
7794 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7798 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7800 return UCLocalize("SHOW_ALL_CHANGES_EX");
7802 return UCLocalize("IGNORE_UPGRADES_EX");
7805 - (void) onSubscribed:(id)control {
7806 bool value([control isOn]);
7807 if (package_ == nil)
7809 if ([package_ setSubscribed:value])
7810 [delegate_ updateData];
7813 - (void) _updateIgnored {
7814 const char *package([name_ UTF8String]);
7815 bool on([ignoredSwitch_ isOn]);
7817 pid_t pid(ExecFork());
7819 FILE *dpkg(popen("dpkg --set-selections", "w"));
7820 fwrite(package, strlen(package), 1, dpkg);
7823 fwrite(" hold\n", 6, 1, dpkg);
7825 fwrite(" install\n", 9, 1, dpkg);
7835 int result(waitpid(pid, &status, 0));
7838 _assert(result == pid);
7844 - (void) onIgnored:(id)control {
7845 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7846 [invocation setTarget:self];
7847 [invocation setSelector:@selector(_updateIgnored)];
7849 [delegate_ reloadDataWithInvocation:invocation];
7852 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7853 if (package_ == nil)
7856 switch ([indexPath section]) {
7857 case 0: return subscribedCell_;
7858 case 1: return ignoredCell_;
7867 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7869 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7870 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7871 [table_ setDataSource:self];
7872 [table_ setDelegate:self];
7873 [[self view] addSubview:table_];
7875 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7876 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7877 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7879 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7880 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7881 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7883 subscribedCell_ = [[UITableViewCell alloc] init];
7884 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7885 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7886 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7888 ignoredCell_ = [[UITableViewCell alloc] init];
7889 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7890 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7891 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7894 - (void) viewDidLoad {
7895 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7898 - (void) releaseSubviews {
7899 [ignoredCell_ release];
7902 [subscribedCell_ release];
7903 subscribedCell_ = nil;
7908 [ignoredSwitch_ release];
7909 ignoredSwitch_ = nil;
7911 [subscribedSwitch_ release];
7912 subscribedSwitch_ = nil;
7915 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7916 if ((self = [super init]) != nil) {
7917 database_ = database;
7918 name_ = [package retain];
7922 - (void) reloadData {
7925 if (package_ != nil)
7926 [package_ autorelease];
7927 package_ = [database_ packageWithName:name_];
7929 if (package_ != nil) {
7930 package_ = [package_ retain];
7931 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7932 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7933 } // XXX: what now, G?
7935 [table_ reloadData];
7941 /* Installed Controller {{{ */
7942 @interface InstalledController : FilteredPackageListController {
7946 - (id) initWithDatabase:(Database *)database;
7948 - (void) updateRoleButton;
7949 - (void) queueStatusDidChange;
7953 @implementation InstalledController
7959 - (NSURL *) navigationURL {
7960 return [NSURL URLWithString:@"cydia://installed"];
7963 - (id) initWithDatabase:(Database *)database {
7964 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7965 [self updateRoleButton];
7966 [self queueStatusDidChange];
7971 - (void) queueButtonClicked {
7976 - (void) queueStatusDidChange {
7980 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7981 initWithTitle:UCLocalize("QUEUE")
7982 style:UIBarButtonItemStyleDone
7984 action:@selector(queueButtonClicked)
7987 [[self navigationItem] setLeftBarButtonItem:nil];
7993 - (void) updateRoleButton {
7994 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7995 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7996 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7997 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7999 action:@selector(roleButtonClicked)
8003 - (void) roleButtonClicked {
8004 [self setObject:[NSNumber numberWithBool:expert_]];
8008 [self updateRoleButton];
8014 /* Source Cell {{{ */
8015 @interface SourceCell : CYTableViewCell <
8023 - (void) setSource:(Source *)source;
8027 @implementation SourceCell
8029 - (void) clearSource {
8039 - (void) setSource:(Source *)source {
8043 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
8045 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8046 icon_ = [icon_ retain];
8048 origin_ = [[source name] retain];
8049 label_ = [[source uri] retain];
8051 [content_ setNeedsDisplay];
8059 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8060 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8061 UIView *content([self contentView]);
8062 CGRect bounds([content bounds]);
8064 content_ = [[ContentView alloc] initWithFrame:bounds];
8065 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8066 [content_ setBackgroundColor:[UIColor whiteColor]];
8067 [content addSubview:content_];
8069 [content_ setDelegate:self];
8070 [content_ setOpaque:YES];
8074 - (NSString *) accessibilityLabel {
8078 - (void) drawContentRect:(CGRect)rect {
8079 bool highlighted(highlighted_);
8080 float width(rect.size.width);
8083 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8090 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8094 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8099 /* Source Controller {{{ */
8100 @interface SourceController : FilteredPackageListController {
8101 _transient Source *source_;
8105 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8109 @implementation SourceController
8111 - (NSURL *) navigationURL {
8112 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8115 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8116 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8118 key_ = [[source key] retain];
8122 - (void) reloadData {
8123 source_ = [database_ sourceWithKey:key_];
8125 key_ = [[source_ key] retain];
8126 [self setObject:source_];
8127 [[self navigationItem] setTitle:[source_ label]];
8134 /* Sources Controller {{{ */
8135 @interface SourcesController : CYViewController <
8136 UITableViewDataSource,
8139 _transient Database *database_;
8141 NSMutableArray *sources_;
8145 UIProgressHUD *hud_;
8148 //NSURLConnection *installer_;
8149 NSURLConnection *trivial_;
8150 NSURLConnection *trivial_bz2_;
8151 NSURLConnection *trivial_gz_;
8152 //NSURLConnection *automatic_;
8157 - (id) initWithDatabase:(Database *)database;
8158 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8162 @implementation SourcesController
8164 - (void) _releaseConnection:(NSURLConnection *)connection {
8165 if (connection != nil) {
8166 [connection cancel];
8167 //[connection setDelegate:nil];
8168 [connection release];
8173 [self releaseSubviews];
8179 //[self _releaseConnection:installer_];
8180 [self _releaseConnection:trivial_];
8181 [self _releaseConnection:trivial_gz_];
8182 [self _releaseConnection:trivial_bz2_];
8183 //[self _releaseConnection:automatic_];
8189 - (NSURL *) navigationURL {
8190 return [NSURL URLWithString:@"cydia://sources"];
8193 - (void) viewDidAppear:(BOOL)animated {
8194 [super viewDidAppear:animated];
8195 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8198 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8199 return offset_ == 0 ? 1 : 2;
8202 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8203 switch (section + (offset_ == 0 ? 1 : 0)) {
8204 case 0: return UCLocalize("ENTERED_BY_USER");
8205 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8211 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8212 int count = [sources_ count];
8214 case 0: return (offset_ == 0 ? count : offset_);
8215 case 1: return count - offset_;
8221 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8223 switch (indexPath.section) {
8224 case 0: idx = indexPath.row; break;
8225 case 1: idx = indexPath.row + offset_; break;
8229 return [sources_ objectAtIndex:idx];
8232 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8233 static NSString *cellIdentifier = @"SourceCell";
8235 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8236 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8237 [cell setSource:[self sourceAtIndexPath:indexPath]];
8238 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8243 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8244 Source *source = [self sourceAtIndexPath:indexPath];
8246 SourceController *controller = [[[SourceController alloc]
8247 initWithDatabase:database_
8251 [controller setDelegate:delegate_];
8253 [[self navigationController] pushViewController:controller animated:YES];
8256 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8257 Source *source = [self sourceAtIndexPath:indexPath];
8258 return [source record] != nil;
8261 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8262 Source *source = [self sourceAtIndexPath:indexPath];
8263 [Sources_ removeObjectForKey:[source key]];
8264 [delegate_ syncData];
8268 [delegate_ addTrivialSource:href_];
8269 [delegate_ syncData];
8272 - (NSString *) getWarning {
8273 NSString *href(href_);
8274 NSRange colon([href rangeOfString:@"://"]);
8275 if (colon.location != NSNotFound)
8276 href = [href substringFromIndex:(colon.location + 3)];
8277 href = [href stringByAddingPercentEscapes];
8278 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8279 href = [href stringByCachingURLWithCurrentCDN];
8281 NSURL *url([NSURL URLWithString:href]);
8283 NSStringEncoding encoding;
8284 NSError *error(nil);
8286 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8287 return [warning length] == 0 ? nil : warning;
8291 - (void) _endConnection:(NSURLConnection *)connection {
8292 // XXX: the memory management in this method is horribly awkward
8294 NSURLConnection **field = NULL;
8295 if (connection == trivial_)
8297 else if (connection == trivial_bz2_)
8298 field = &trivial_bz2_;
8299 else if (connection == trivial_gz_)
8300 field = &trivial_gz_;
8301 _assert(field != NULL);
8302 [connection release];
8307 trivial_bz2_ == nil &&
8313 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8316 UIAlertView *alert = [[[UIAlertView alloc]
8317 initWithTitle:UCLocalize("SOURCE_WARNING")
8320 cancelButtonTitle:UCLocalize("CANCEL")
8322 UCLocalize("ADD_ANYWAY"),
8326 [alert setContext:@"warning"];
8327 [alert setNumberOfRows:1];
8331 } else if (error_ != nil) {
8332 UIAlertView *alert = [[[UIAlertView alloc]
8333 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8334 message:[error_ localizedDescription]
8336 cancelButtonTitle:UCLocalize("OK")
8337 otherButtonTitles:nil
8340 [alert setContext:@"urlerror"];
8343 UIAlertView *alert = [[[UIAlertView alloc]
8344 initWithTitle:UCLocalize("NOT_REPOSITORY")
8345 message:UCLocalize("NOT_REPOSITORY_EX")
8347 cancelButtonTitle:UCLocalize("OK")
8348 otherButtonTitles:nil
8351 [alert setContext:@"trivial"];
8355 [delegate_ releaseNetworkActivityIndicator];
8357 [delegate_ removeProgressHUD:hud_];
8366 if (error_ != nil) {
8373 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8374 switch ([response statusCode]) {
8380 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8381 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8383 error_ = [error retain];
8384 [self _endConnection:connection];
8387 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8388 [self _endConnection:connection];
8391 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8392 NSMutableURLRequest *request = [NSMutableURLRequest
8393 requestWithURL:[NSURL URLWithString:href]
8394 cachePolicy:NSURLRequestUseProtocolCachePolicy
8395 timeoutInterval:120.0
8398 [request setHTTPMethod:method];
8400 if (Machine_ != NULL)
8401 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8402 if (UniqueID_ != nil)
8403 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8405 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
8407 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8410 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8411 NSString *context([alert context]);
8413 if ([context isEqualToString:@"source"]) {
8416 NSString *href = [[alert textField] text];
8418 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8420 if (![href hasSuffix:@"/"])
8421 href_ = [href stringByAppendingString:@"/"];
8424 href_ = [href_ retain];
8426 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8427 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8428 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8429 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8433 // XXX: this is stupid
8434 hud_ = [[delegate_ addProgressHUD] retain];
8435 [hud_ setText:UCLocalize("VERIFYING_URL")];
8436 [delegate_ retainNetworkActivityIndicator];
8445 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8446 } else if ([context isEqualToString:@"trivial"])
8447 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8448 else if ([context isEqualToString:@"urlerror"])
8449 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8450 else if ([context isEqualToString:@"warning"]) {
8465 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8470 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8472 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8473 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8474 [list_ setRowHeight:56];
8475 [list_ setDataSource:self];
8476 [list_ setDelegate:self];
8477 [[self view] addSubview:list_];
8480 - (void) viewDidLoad {
8481 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8482 [self updateButtonsForEditingStatus:NO animated:NO];
8485 - (void) releaseSubviews {
8490 - (id) initWithDatabase:(Database *)database {
8491 if ((self = [super init]) != nil) {
8492 database_ = database;
8493 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8497 - (void) reloadData {
8501 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8504 [sources_ removeAllObjects];
8505 [sources_ addObjectsFromArray:[database_ sources]];
8507 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8510 int count([sources_ count]);
8512 for (int i = 0; i != count; i++) {
8513 if ([[sources_ objectAtIndex:i] record] == nil)
8518 [list_ setEditing:NO];
8519 [self updateButtonsForEditingStatus:NO animated:NO];
8523 - (void) showAddSourcePrompt {
8524 UIAlertView *alert = [[[UIAlertView alloc]
8525 initWithTitle:UCLocalize("ENTER_APT_URL")
8528 cancelButtonTitle:UCLocalize("CANCEL")
8530 UCLocalize("ADD_SOURCE"),
8534 [alert setContext:@"source"];
8535 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8537 [alert setNumberOfRows:1];
8538 [alert addTextFieldWithValue:@"http://" label:@""];
8540 UITextInputTraits *traits = [[alert textField] textInputTraits];
8541 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8542 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8543 [traits setKeyboardType:UIKeyboardTypeURL];
8544 // XXX: UIReturnKeyDone
8545 [traits setReturnKeyType:UIReturnKeyNext];
8550 - (void) addButtonClicked {
8551 [self showAddSourcePrompt];
8554 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8555 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8556 initWithTitle:UCLocalize("ADD")
8557 style:UIBarButtonItemStylePlain
8559 action:@selector(addButtonClicked)
8560 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8562 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8563 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8564 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8566 action:@selector(editButtonClicked)
8567 ] autorelease] animated:animated];
8569 if (IsWildcat_ && !editing)
8570 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8571 initWithTitle:UCLocalize("SETTINGS")
8572 style:UIBarButtonItemStylePlain
8574 action:@selector(settingsButtonClicked)
8578 - (void) settingsButtonClicked {
8579 [delegate_ showSettings];
8582 - (void) editButtonClicked {
8583 [list_ setEditing:![list_ isEditing] animated:YES];
8585 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8591 /* Settings Controller {{{ */
8592 @interface SettingsController : CYViewController <
8593 UITableViewDataSource,
8596 _transient Database *database_;
8597 // XXX: ok, "roledelegate_"?...
8598 _transient id roledelegate_;
8599 UITableView *table_;
8600 UISegmentedControl *segment_;
8604 - (void) showDoneButton;
8605 - (void) resizeSegmentedControl;
8609 @implementation SettingsController
8612 [self releaseSubviews];
8618 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8620 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8621 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8622 [table_ setDelegate:self];
8623 [table_ setDataSource:self];
8624 [[self view] addSubview:table_];
8626 NSArray *items = [NSArray arrayWithObjects:
8628 UCLocalize("HACKER"),
8629 UCLocalize("DEVELOPER"),
8631 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8632 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8633 [container_ addSubview:segment_];
8636 - (void) viewDidLoad {
8637 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8640 if ([Role_ isEqualToString:@"User"]) index = 0;
8641 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8642 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8644 [segment_ setSelectedSegmentIndex:index];
8645 [self showDoneButton];
8648 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8649 [self resizeSegmentedControl];
8652 - (void) releaseSubviews {
8659 [container_ release];
8663 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8664 if ((self = [super init]) != nil) {
8665 database_ = database;
8666 roledelegate_ = delegate;
8670 - (void) resizeSegmentedControl {
8671 CGFloat width = [[self view] frame].size.width;
8672 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8675 - (void) viewWillAppear:(BOOL)animated {
8676 [super viewWillAppear:animated];
8678 [self resizeSegmentedControl];
8681 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8682 [self resizeSegmentedControl];
8685 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8686 [self resizeSegmentedControl];
8690 NSString *role(nil);
8692 switch ([segment_ selectedSegmentIndex]) {
8693 case 0: role = @"User"; break;
8694 case 1: role = @"Hacker"; break;
8695 case 2: role = @"Developer"; break;
8700 if (![role isEqualToString:Role_]) {
8701 bool rolling(Role_ == nil);
8704 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8708 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8712 [roledelegate_ loadData];
8714 [roledelegate_ updateData];
8718 - (void) segmentChanged:(UISegmentedControl *)control {
8719 [self showDoneButton];
8722 - (void) saveAndClose {
8725 [[self navigationItem] setRightBarButtonItem:nil];
8726 [[self navigationController] dismissModalViewControllerAnimated:YES];
8729 - (void) doneButtonClicked {
8730 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8731 [spinner startAnimating];
8732 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8733 [[self navigationItem] setRightBarButtonItem:spinItem];
8735 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8738 - (void) showDoneButton {
8739 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8740 initWithTitle:UCLocalize("DONE")
8741 style:UIBarButtonItemStyleDone
8743 action:@selector(doneButtonClicked)
8744 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8747 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8748 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8752 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8756 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8757 return nil; // This method is required by the protocol.
8760 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8762 return UCLocalize("ROLE_EX");
8764 return [NSString stringWithFormat:
8765 @"%@: %@\n%@: %@\n%@: %@",
8766 UCLocalize("USER"), UCLocalize("USER_EX"),
8767 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8768 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8773 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8774 return section == 3 ? 44.0f : 0;
8777 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8778 return section == 3 ? container_ : nil;
8781 - (void) reloadData {
8783 [table_ reloadData];
8788 /* Stash Controller {{{ */
8789 @interface StashController : CYViewController {
8790 UIActivityIndicatorView *spinner_;
8797 @implementation StashController
8800 [self releaseSubviews];
8806 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8807 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8809 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8810 CGRect spinrect = [spinner_ frame];
8811 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8812 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8813 [spinner_ setFrame:spinrect];
8814 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8815 [[self view] addSubview:spinner_];
8816 [spinner_ startAnimating];
8819 captrect.size.width = [[self view] frame].size.width;
8820 captrect.size.height = 40.0f;
8821 captrect.origin.x = 0;
8822 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8823 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8824 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8825 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8826 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8827 [caption_ setTextColor:[UIColor whiteColor]];
8828 [caption_ setBackgroundColor:[UIColor clearColor]];
8829 [caption_ setShadowColor:[UIColor blackColor]];
8830 [caption_ setTextAlignment:UITextAlignmentCenter];
8831 [[self view] addSubview:caption_];
8834 statusrect.size.width = [[self view] frame].size.width;
8835 statusrect.size.height = 30.0f;
8836 statusrect.origin.x = 0;
8837 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8838 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8839 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8840 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8841 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8842 [status_ setTextColor:[UIColor whiteColor]];
8843 [status_ setBackgroundColor:[UIColor clearColor]];
8844 [status_ setShadowColor:[UIColor blackColor]];
8845 [status_ setTextAlignment:UITextAlignmentCenter];
8846 [[self view] addSubview:status_];
8849 - (void) releaseSubviews {
8863 @interface Cydia : UIApplication <
8864 ConfirmationControllerDelegate,
8867 UINavigationControllerDelegate,
8868 UITabBarControllerDelegate
8870 // XXX: evaluate all fields for _transient
8873 CYTabBarController *tabbar_;
8874 CYEmulatedLoadingController *emulated_;
8876 NSMutableArray *essential_;
8877 NSMutableArray *broken_;
8879 Database *database_;
8886 StashController *stash_;
8895 @implementation Cydia
8897 - (void) beginUpdate {
8898 [tabbar_ beginUpdate];
8902 return [tabbar_ updating];
8906 if ([broken_ count] != 0) {
8907 int count = [broken_ count];
8909 UIAlertView *alert = [[[UIAlertView alloc]
8910 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8911 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8913 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8915 UCLocalize("TEMPORARY_IGNORE"),
8919 [alert setContext:@"fixhalf"];
8920 [alert setNumberOfRows:2];
8922 } else if (!Ignored_ && [essential_ count] != 0) {
8923 int count = [essential_ count];
8925 UIAlertView *alert = [[[UIAlertView alloc]
8926 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8927 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8929 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8931 UCLocalize("UPGRADE_ESSENTIAL"),
8932 UCLocalize("COMPLETE_UPGRADE"),
8936 [alert setContext:@"upgrade"];
8941 - (void) _saveConfig {
8947 NSString *error(nil);
8949 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8951 NSError *error(nil);
8952 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8953 NSLog(@"failure to save metadata data: %@", error);
8958 NSLog(@"failure to serialize metadata: %@", error);
8963 // Navigation controller for the queuing badge.
8964 - (CYNavigationController *) queueNavigationController {
8965 NSArray *controllers = [tabbar_ viewControllers];
8966 return [controllers objectAtIndex:3];
8969 - (void) _updateData {
8972 [tabbar_ reloadData];
8974 CYNavigationController *navigation = [self queueNavigationController];
8976 id queuedelegate = nil;
8977 if ([[navigation viewControllers] count] > 0)
8978 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8980 [queuedelegate queueStatusDidChange];
8981 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8984 - (void) _refreshIfPossible:(NSDate *)update {
8985 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8987 bool recently = false;
8988 if (update != nil) {
8989 NSTimeInterval interval([update timeIntervalSinceNow]);
8990 if (interval <= 0 && interval > -(15*60))
8994 // Don't automatic refresh if:
8995 // - We already refreshed recently.
8996 // - We already auto-refreshed this launch.
8997 // - Auto-refresh is disabled.
8998 if (recently || loaded_ || ManualRefresh) {
8999 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9001 // If we are cancelling, we need to make sure it knows it's already loaded.
9005 // We are going to load, so remember that.
9009 SCNetworkReachabilityFlags flags; {
9010 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9011 SCNetworkReachabilityGetFlags(reachability, &flags);
9012 CFRelease(reachability);
9015 // XXX: this elaborate mess is what Apple is using to determine this? :(
9016 // XXX: do we care if the user has to intervene? maybe that's ok?
9018 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9019 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9020 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9021 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9022 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9023 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9027 // If we can reach the server, auto-refresh!
9029 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9034 - (void) refreshIfPossible {
9035 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9038 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
9039 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9040 [hud setText:UCLocalize("RELOADING_DATA")];
9042 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9045 [self removeProgressHUD:hud];
9049 [essential_ removeAllObjects];
9050 [broken_ removeAllObjects];
9052 NSArray *packages([database_ packages]);
9053 for (Package *package in packages) {
9055 [broken_ addObject:package];
9056 if ([package upgradableAndEssential:NO]) {
9057 if ([package essential])
9058 [essential_ addObject:package];
9063 NSLog(@"changes:#%u", changes);
9065 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9068 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9069 [changesItem setBadgeValue:badge];
9070 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9071 [self setApplicationIconBadgeNumber:changes];
9074 [changesItem setBadgeValue:nil];
9075 [changesItem setAnimatedBadge:NO];
9076 [self setApplicationIconBadgeNumber:0];
9081 [self refreshIfPossible];
9084 - (void) updateData {
9093 @synchronized (self) {
9094 [self _reloadDataWithInvocation:nil];
9098 - (void) disemulate {
9099 if (emulated_ == nil)
9102 [window_ addSubview:[tabbar_ view]];
9103 [[emulated_ view] removeFromSuperview];
9104 [emulated_ release];
9106 [window_ setUserInteractionEnabled:YES];
9109 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9110 UINavigationController *navigation([[[CYNavigationController alloc] initWithRootViewController:controller] autorelease]);
9112 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9114 UIViewController *parent;
9115 if (emulated_ == nil)
9124 [parent presentModalViewController:navigation animated:YES];
9127 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9128 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9130 if (navigation != nil)
9131 [navigation pushViewController:progress animated:YES];
9133 [self presentModalViewController:progress force:YES];
9135 [progress invoke:invocation withTitle:title];
9139 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9140 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9143 - (void) repairWithInvocation:(NSInvocation *)invocation {
9145 [self invokeNewProgress:invocation forController:nil withTitle:UCLocalize("REPAIRING")];
9149 - (void) repairWithSelector:(SEL)selector {
9150 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9156 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
9157 _assert(file != NULL);
9159 for (NSString *key in [Sources_ allKeys]) {
9160 NSDictionary *source([Sources_ objectForKey:key]);
9162 fprintf(file, "%s %s %s\n",
9163 [[source objectForKey:@"Type"] UTF8String],
9164 [[source objectForKey:@"URI"] UTF8String],
9165 [[source objectForKey:@"Distribution"] UTF8String]
9171 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:UCLocalize("UPDATING_SOURCES")];
9176 - (void) addTrivialSource:(NSString *)href {
9177 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
9180 @"./", @"Distribution",
9181 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
9186 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9187 @synchronized (self) {
9188 [self _reloadDataWithInvocation:invocation];
9192 - (void) reloadData {
9193 [self reloadDataWithInvocation:nil];
9197 pkgProblemResolver *resolver = [database_ resolver];
9199 resolver->InstallProtect();
9200 if (!resolver->Resolve(true))
9205 // XXX: this is a really crappy way of doing this.
9206 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9207 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9208 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9209 if ([tabbar_ updating])
9210 [tabbar_ cancelUpdate];
9212 if (![database_ prepare])
9215 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9216 [page setDelegate:self];
9217 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
9218 [confirm_ setDelegate:self];
9221 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9222 [tabbar_ presentModalViewController:confirm_ animated:YES];
9228 @synchronized (self) {
9233 - (void) clearPackage:(Package *)package {
9234 @synchronized (self) {
9241 - (void) installPackages:(NSArray *)packages {
9242 @synchronized (self) {
9243 for (Package *package in packages)
9250 - (void) installPackage:(Package *)package {
9251 @synchronized (self) {
9258 - (void) removePackage:(Package *)package {
9259 @synchronized (self) {
9266 - (void) distUpgrade {
9267 @synchronized (self) {
9268 if (![database_ upgrade])
9274 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9277 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:UCLocalize("RUNNING")];
9282 - (void) showSettings {
9283 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9284 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9286 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9287 [tabbar_ presentModalViewController:nav animated:YES];
9290 - (void) retainNetworkActivityIndicator {
9291 if (activity_++ == 0)
9292 [self setNetworkActivityIndicatorVisible:YES];
9295 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9299 - (void) releaseNetworkActivityIndicator {
9300 if (--activity_ == 0)
9301 [self setNetworkActivityIndicatorVisible:NO];
9304 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9309 - (void) cancelAndClear:(bool)clear {
9310 @synchronized (self) {
9322 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9323 NSString *context([alert context]);
9325 if ([context isEqualToString:@"conffile"]) {
9326 FILE *input = [database_ input];
9327 if (button == [alert cancelButtonIndex])
9328 fprintf(input, "N\n");
9329 else if (button == [alert firstOtherButtonIndex])
9330 fprintf(input, "Y\n");
9333 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9334 } else if ([context isEqualToString:@"fixhalf"]) {
9335 if (button == [alert cancelButtonIndex]) {
9336 @synchronized (self) {
9337 for (Package *broken in broken_) {
9340 NSString *id = [broken id];
9341 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9342 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9343 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9344 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9350 } else if (button == [alert firstOtherButtonIndex]) {
9351 [broken_ removeAllObjects];
9355 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9356 } else if ([context isEqualToString:@"upgrade"]) {
9357 if (button == [alert firstOtherButtonIndex]) {
9358 @synchronized (self) {
9359 for (Package *essential in essential_)
9360 [essential install];
9365 } else if (button == [alert firstOtherButtonIndex] + 1) {
9367 } else if (button == [alert cancelButtonIndex]) {
9371 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9375 - (void) system:(NSString *)command { _pooled
9377 system([command UTF8String]);
9381 - (void) applicationWillSuspend {
9383 [super applicationWillSuspend];
9386 - (BOOL) isSafeToSuspend {
9387 // Use external process status API internally.
9388 // This is probably a really bad idea.
9389 // XXX: what is the point of this? does this solve anything at all?
9390 uint64_t status = 0;
9392 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9393 notify_get_state(notify_token, &status);
9394 notify_cancel(notify_token);
9397 return locked_ == 0 && status == 0;
9400 - (void) applicationSuspend:(__GSEvent *)event {
9401 if ([self isSafeToSuspend])
9402 [super applicationSuspend:event];
9405 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9406 if ([self isSafeToSuspend])
9407 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9410 - (void) _setSuspended:(BOOL)value {
9411 if ([self isSafeToSuspend])
9412 [super _setSuspended:value];
9415 - (UIProgressHUD *) addProgressHUD {
9416 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9417 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9419 [window_ setUserInteractionEnabled:NO];
9422 UIViewController *target = tabbar_;
9423 while ([target modalViewController] != nil) target = [target modalViewController];
9424 [[target view] addSubview:hud];
9430 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9432 [hud removeFromSuperview];
9433 [window_ setUserInteractionEnabled:YES];
9437 - (CYViewController *) pageForPackage:(NSString *)name {
9438 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9441 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9442 NSString *scheme([[url scheme] lowercaseString]);
9443 if ([[url absoluteString] length] <= [scheme length] + 3)
9445 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9446 NSArray *components([path pathComponents]);
9448 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9449 return [self pageForPackage:[components objectAtIndex:1]];
9451 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9454 NSString *base([components objectAtIndex:0]);
9456 CYViewController *controller = nil;
9458 if ([base isEqualToString:@"url"]) {
9459 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9460 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9461 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9462 } else if (!external && [components count] == 1) {
9463 if ([base isEqualToString:@"manage"]) {
9464 controller = [[[ManageController alloc] init] autorelease];
9467 if ([base isEqualToString:@"sources"]) {
9468 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9471 if ([base isEqualToString:@"home"]) {
9472 controller = [[[HomeController alloc] init] autorelease];
9475 if ([base isEqualToString:@"sections"]) {
9476 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9479 if ([base isEqualToString:@"search"]) {
9480 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9483 if ([base isEqualToString:@"changes"]) {
9484 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9487 if ([base isEqualToString:@"installed"]) {
9488 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9490 } else if ([components count] == 2) {
9491 NSString *argument = [components objectAtIndex:1];
9493 if ([base isEqualToString:@"package"]) {
9494 controller = [self pageForPackage:argument];
9497 if (!external && [base isEqualToString:@"search"]) {
9498 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9499 [(SearchController *)controller setSearchTerm:argument];
9502 if (!external && [base isEqualToString:@"sections"]) {
9503 if ([argument isEqualToString:@"all"])
9505 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9508 if (!external && [base isEqualToString:@"sources"]) {
9509 if ([argument isEqualToString:@"add"]) {
9510 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9511 [(SourcesController *)controller showAddSourcePrompt];
9513 Source *source = [database_ sourceWithKey:argument];
9514 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9518 if (!external && [base isEqualToString:@"launch"]) {
9519 [self launchApplicationWithIdentifier:argument suspended:NO];
9522 } else if (!external && [components count] == 3) {
9523 NSString *arg1 = [components objectAtIndex:1];
9524 NSString *arg2 = [components objectAtIndex:2];
9526 if ([base isEqualToString:@"package"]) {
9527 if ([arg2 isEqualToString:@"settings"]) {
9528 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9529 } else if ([arg2 isEqualToString:@"files"]) {
9530 if (Package *package = [database_ packageWithName:arg1]) {
9531 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9532 [(FileTable *)controller setPackage:package];
9538 [controller setDelegate:self];
9542 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9543 CYViewController *page([self pageForURL:url forExternal:external]);
9546 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9547 [nav setViewControllers:[NSArray arrayWithObject:page]];
9548 [tabbar_ setUnselectedViewController:nav];
9554 - (void) applicationOpenURL:(NSURL *)url {
9555 [super applicationOpenURL:url];
9557 if (!loaded_) starturl_ = [url retain];
9558 else [self openCydiaURL:url forExternal:YES];
9561 - (void) applicationWillResignActive:(UIApplication *)application {
9562 // Stop refreshing if you get a phone call or lock the device.
9563 if ([tabbar_ updating])
9564 [tabbar_ cancelUpdate];
9566 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9567 [super applicationWillResignActive:application];
9570 - (void) applicationWillTerminate:(UIApplication *)application {
9572 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9573 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9574 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9579 - (void) setConfigurationData:(NSString *)data {
9580 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9582 if (!conffile_r(data)) {
9583 lprintf("E:invalid conffile\n");
9587 NSString *ofile = conffile_r[1];
9588 //NSString *nfile = conffile_r[2];
9590 UIAlertView *alert = [[[UIAlertView alloc]
9591 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9592 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9594 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9596 UCLocalize("ACCEPT_NEW_COPY"),
9597 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9601 [alert setContext:@"conffile"];
9602 [alert setNumberOfRows:2];
9606 - (void) addStashController {
9608 stash_ = [[StashController alloc] init];
9609 [window_ addSubview:[stash_ view]];
9612 - (void) removeStashController {
9613 [[stash_ view] removeFromSuperview];
9619 [self setIdleTimerDisabled:YES];
9621 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9622 UpdateExternalStatus(1);
9623 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9624 UpdateExternalStatus(0);
9626 [self removeStashController];
9628 if (ExecFork() == 0) {
9629 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9630 perror("launchctl stop");
9634 - (void) setupViewControllers {
9635 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9637 NSMutableArray *items([NSMutableArray arrayWithObjects:
9638 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9639 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9640 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9641 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9645 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9646 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9648 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9651 NSMutableArray *controllers([NSMutableArray array]);
9652 for (UITabBarItem *item in items) {
9653 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9654 [controller setTabBarItem:item];
9655 [controllers addObject:controller];
9657 [tabbar_ setViewControllers:controllers];
9659 [tabbar_ setUpdateDelegate:self];
9662 - (void) applicationDidFinishLaunching:(id)unused {
9664 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9665 [self setApplicationSupportsShakeToEdit:NO];
9667 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9668 initWithMemoryCapacity:524288
9669 diskCapacity:10485760
9670 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9673 [CYBrowserController _initialize];
9675 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9677 Font12_ = [[UIFont systemFontOfSize:12] retain];
9678 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9679 Font14_ = [[UIFont systemFontOfSize:14] retain];
9680 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9681 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9683 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9684 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9686 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9687 [window_ orderFront:self];
9688 [window_ makeKey:self];
9689 [window_ setHidden:NO];
9692 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9693 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9694 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9695 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9696 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9697 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9698 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9699 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9700 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9703 [self addStashController];
9704 // XXX: this would be much cleaner as a yieldToSelector:
9705 // that way the removeStashController could happen right here inline
9706 // we also could no longer require the useless stash_ field anymore
9707 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9711 database_ = [Database sharedInstance];
9712 [database_ setDelegate:self];
9714 [window_ setUserInteractionEnabled:NO];
9715 [self setupViewControllers];
9717 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9718 [window_ addSubview:[emulated_ view]];
9720 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9727 [window_ setUserInteractionEnabled:YES];
9728 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9731 if ([emulated_ modalViewController] != nil)
9732 [emulated_ dismissModalViewControllerAnimated:YES];
9733 [window_ setUserInteractionEnabled:NO];
9741 int selectedIndex = 0;
9742 NSMutableArray *items = nil;
9744 bool recently = false;
9745 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9746 if (closed != nil) {
9747 NSTimeInterval interval([closed timeIntervalSinceNow]);
9748 // XXX: Is 15 minutes the optimal time here?
9749 if (interval <= 0 && interval > -(15*60))
9753 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9754 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9757 for (NSArray *entry in items)
9758 if ([entry count] <= 0)
9761 if (!recently || !items || !enough) {
9763 items = [NSMutableArray array];
9764 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9765 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9766 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9768 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9770 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9771 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9773 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9776 [tabbar_ setSelectedIndex:selectedIndex];
9777 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9778 NSArray *stack = [items objectAtIndex:tab];
9779 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9780 NSMutableArray *current = [NSMutableArray array];
9782 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9783 NSString *addr = [stack objectAtIndex:nav];
9784 NSURL *url = [NSURL URLWithString:addr];
9785 CYViewController *page = [self pageForURL:url forExternal:NO];
9787 [current addObject:page];
9790 [navigation setViewControllers:current];
9793 // (Try to) show the startup URL.
9794 if (starturl_ != nil) {
9795 [self openCydiaURL:starturl_ forExternal:NO];
9796 [starturl_ release];
9801 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9802 if (item != nil && IsWildcat_) {
9803 [sheet showFromBarButtonItem:item animated:YES];
9805 [sheet showInView:window_];
9809 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9810 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9811 [progress setTitle:task];
9812 [progress addProgressEvent:event];
9815 - (void) addProgressEventForTask:(NSArray *)data {
9816 CydiaProgressEvent *event([data objectAtIndex:0]);
9817 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9818 [self addProgressEvent:event forTask:task];
9821 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9822 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9828 id Alloc_(id self, SEL selector) {
9829 id object = alloc_(self, selector);
9830 lprintf("[%s]A-%p\n", self->isa->name, object);
9835 id Dealloc_(id self, SEL selector) {
9836 id object = dealloc_(self, selector);
9837 lprintf("[%s]D-%p\n", self->isa->name, object);
9841 Class $WebDefaultUIKitDelegate;
9843 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9844 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9845 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9846 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9849 static NSNumber *shouldPlayKeyboardSounds;
9853 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9855 case 1104: // Keyboard Button Clicked
9856 case 1105: // Keyboard Delete Repeated
9857 if (shouldPlayKeyboardSounds == nil) {
9858 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9859 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9862 if (![shouldPlayKeyboardSounds boolValue])
9866 _UIHardware$_playSystemSound$(self, _cmd, sound);
9870 Class $UIApplication;
9872 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9873 static BOOL initialized = NO;
9874 static BOOL started = NO;
9876 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9877 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9879 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9880 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9881 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9882 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9884 if (initialized && !enabled) {
9886 [bundle performSelector:@selector(_accessibilityStopServer)];
9887 } else if (enabled) {
9891 [bundle performSelector:@selector(_accessibilityStartServer)];
9897 int main(int argc, char *argv[]) { _pooled
9900 UpdateExternalStatus(0);
9902 if (Class $UIDevice = objc_getClass("UIDevice")) {
9903 UIDevice *device([$UIDevice currentDevice]);
9904 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9908 UIScreen *screen([UIScreen mainScreen]);
9909 if ([screen respondsToSelector:@selector(scale)])
9910 ScreenScale_ = [screen scale];
9914 UIDevice *device([UIDevice currentDevice]);
9915 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9918 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9919 if (idiom == UIUserInterfaceIdiomPhone)
9921 else if (idiom == UIUserInterfaceIdiomPad)
9924 NSLog(@"unknown UIUserInterfaceIdiom!");
9927 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9929 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9931 /* Library Hacks {{{ */
9932 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9934 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9935 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9936 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9937 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9938 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9941 $UIHardware = objc_getClass("UIHardware");
9942 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9943 if (UIHardware$_playSystemSound$ != NULL) {
9944 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9945 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9948 $UIApplication = objc_getClass("UIApplication");
9949 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9950 if (UIApplication$_updateApplicationAccessibility != NULL) {
9951 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9952 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9955 /* Set Locale {{{ */
9956 Locale_ = CFLocaleCopyCurrent();
9957 Languages_ = [NSLocale preferredLanguages];
9958 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9959 //NSLog(@"%@", [Languages_ description]);
9962 if (Languages_ == nil || [Languages_ count] == 0)
9963 // XXX: consider just setting to C and then falling through?
9966 lang = [[Languages_ objectAtIndex:0] UTF8String];
9967 setenv("LANG", lang, true);
9968 std::setlocale(LC_ALL, lang);
9971 NSLog(@"Setting Language: %s", lang);
9974 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9976 /* Parse Arguments {{{ */
9977 bool substrate(false);
9983 for (int argi(1); argi != argc; ++argi)
9984 if (strcmp(argv[argi], "--") == 0) {
9986 argv[argi] = argv[0];
9992 for (int argi(1); argi != arge; ++argi)
9993 if (strcmp(args[argi], "--substrate") == 0)
9996 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10000 App_ = [[NSBundle mainBundle] bundlePath];
10006 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10007 alloc_ = alloc->method_imp;
10008 alloc->method_imp = (IMP) &Alloc_;*/
10010 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10011 dealloc_ = dealloc->method_imp;
10012 dealloc->method_imp = (IMP) &Dealloc_;*/
10014 /* System Information {{{ */
10018 size = sizeof(maxproc);
10019 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10020 perror("sysctlbyname(\"kern.maxproc\", ?)");
10021 else if (maxproc < 64) {
10023 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10024 perror("sysctlbyname(\"kern.maxproc\", #)");
10027 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10028 char *osversion = new char[size];
10029 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10030 perror("sysctlbyname(\"kern.osversion\", ?)");
10032 System_ = [NSString stringWithUTF8String:osversion];
10034 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10035 char *machine = new char[size];
10036 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10037 perror("sysctlbyname(\"hw.machine\", ?)");
10039 Machine_ = machine;
10041 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
10042 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
10043 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
10044 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
10048 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
10049 NSData *data((NSData *) ecid);
10050 size_t length([data length]);
10051 uint8_t bytes[length];
10052 [data getBytes:bytes];
10053 char string[length * 2 + 1];
10054 for (size_t i(0); i != length; ++i)
10055 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
10056 ChipID_ = [NSString stringWithUTF8String:string];
10060 IOObjectRelease(service);
10064 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
10066 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10067 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10068 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10070 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10071 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10072 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10074 if (mcc != NULL && mnc != NULL)
10075 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10082 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10083 Build_ = [system objectForKey:@"ProductBuildVersion"];
10084 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10085 Product_ = [info objectForKey:@"SafariProductVersion"];
10086 Safari_ = [info objectForKey:@"CFBundleVersion"];
10089 /* Load Database {{{ */
10091 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10093 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10095 if (Metadata_ == NULL)
10096 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10098 Settings_ = [Metadata_ objectForKey:@"Settings"];
10100 Packages_ = [Metadata_ objectForKey:@"Packages"];
10101 Sections_ = [Metadata_ objectForKey:@"Sections"];
10102 Sources_ = [Metadata_ objectForKey:@"Sources"];
10104 Token_ = [Metadata_ objectForKey:@"Token"];
10107 if (Settings_ != nil)
10108 Role_ = [Settings_ objectForKey:@"Role"];
10110 if (Sections_ == nil) {
10111 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10112 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10115 if (Sources_ == nil) {
10116 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10117 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10122 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10125 if (Packages_ != nil) {
10127 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10131 [Metadata_ removeObjectForKey:@"Packages"];
10137 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10139 #define MobileSubstrate_(name) \
10140 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10141 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10142 if (handle == NULL) \
10143 NSLog(@"%s", dlerror()); \
10146 MobileSubstrate_(Activator)
10147 MobileSubstrate_(libstatusbar)
10148 MobileSubstrate_(SimulatedKeyEvents)
10149 MobileSubstrate_(WinterBoard)
10151 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10152 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10154 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10156 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10157 unlink("/tmp/.cydia.fw");
10159 } else if (access("/User", F_OK) != 0 || version < 4) {
10162 system("/usr/libexec/cydia/firmware.sh");
10166 _assert([[NSFileManager defaultManager]
10167 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10168 withIntermediateDirectories:YES
10173 if (access("/tmp/cydia.chk", F_OK) == 0) {
10174 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10175 _assert(errno == ENOENT);
10176 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10177 _assert(errno == ENOENT);
10180 /* APT Initialization {{{ */
10181 _assert(pkgInitConfig(*_config));
10182 _assert(pkgInitSystem(*_config, _system));
10185 _config->Set("APT::Acquire::Translation", lang);
10187 // XXX: this timeout might be important :(
10188 //_config->Set("Acquire::http::Timeout", 15);
10190 _config->Set("Acquire::http::MaxParallel", 3);
10192 /* Color Choices {{{ */
10193 space_ = CGColorSpaceCreateDeviceRGB();
10195 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10196 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10197 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10198 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10199 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10200 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10201 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10202 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10203 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10205 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10206 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10208 /* UIKit Configuration {{{ */
10209 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10210 if ($GSFontSetUseLegacyFontMetrics != NULL)
10211 $GSFontSetUseLegacyFontMetrics(YES);
10213 // XXX: I have a feeling this was important
10214 //UIKeyboardDisableAutomaticAppearance();
10217 Colon_ = UCLocalize("COLON_DELIMITED");
10218 Elision_ = UCLocalize("ELISION");
10219 Error_ = UCLocalize("ERROR");
10220 Warning_ = UCLocalize("WARNING");
10223 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10225 CGColorSpaceRelease(space_);
10226 CFRelease(Locale_);