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_;
1070 static NSMutableSet *CydiaHosts_;
1073 /* Display Helpers {{{ */
1074 inline float Interpolate(float begin, float end, float fraction) {
1075 return (end - begin) * fraction + begin;
1078 static _finline const char *StripVersion_(const char *version) {
1079 const char *colon(strchr(version, ':'));
1080 return colon == NULL ? version : colon + 1;
1083 NSString *LocalizeSection(NSString *section) {
1084 static Pcre title_r("^(.*?) \\((.*)\\)$");
1085 if (title_r(section)) {
1086 NSString *parent(title_r[1]);
1087 NSString *child(title_r[2]);
1089 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1090 LocalizeSection(parent),
1091 LocalizeSection(child)
1095 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1098 NSString *Simplify(NSString *title) {
1099 const char *data = [title UTF8String];
1100 size_t size = [title length];
1102 static Pcre square_r("^\\[(.*)\\]$");
1103 if (square_r(data, size))
1104 return Simplify(square_r[1]);
1106 static Pcre paren_r("^\\((.*)\\)$");
1107 if (paren_r(data, size))
1108 return Simplify(paren_r[1]);
1110 static Pcre title_r("^(.*?) \\((.*)\\)$");
1111 if (title_r(data, size))
1112 return Simplify(title_r[1]);
1118 NSString *GetLastUpdate() {
1119 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1122 return UCLocalize("NEVER_OR_UNKNOWN");
1124 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1125 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1127 CFRelease(formatter);
1129 return [(NSString *) formatted autorelease];
1132 bool isSectionVisible(NSString *section) {
1133 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1134 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1135 return hidden == nil || ![hidden boolValue];
1140 /* Delegate Prototypes {{{ */
1143 @class CydiaProgressEvent;
1145 @protocol DatabaseDelegate
1146 - (void) repairWithSelector:(SEL)selector;
1147 - (void) setConfigurationData:(NSString *)data;
1148 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
1151 @class CYPackageController;
1153 @protocol CydiaDelegate
1154 - (void) retainNetworkActivityIndicator;
1155 - (void) releaseNetworkActivityIndicator;
1156 - (void) clearPackage:(Package *)package;
1157 - (void) installPackage:(Package *)package;
1158 - (void) installPackages:(NSArray *)packages;
1159 - (void) removePackage:(Package *)package;
1160 - (void) beginUpdate;
1162 - (void) distUpgrade;
1164 - (void) updateData;
1166 - (void) addTrivialSource:(NSString *)href;
1167 - (void) showSettings;
1168 - (UIProgressHUD *) addProgressHUD;
1169 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1170 - (CYViewController *) pageForPackage:(NSString *)name;
1171 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1172 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1173 - (void) addCydiaHost:(NSString *)host;
1177 /* ProgressEvent Interface/Delegate {{{ */
1178 @interface CydiaProgressEvent : NSObject {
1179 _H<NSString> message_;
1183 _H<NSString> package_;
1185 _H<NSString> version_;
1188 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type;
1189 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package;
1190 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item;
1192 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type;
1194 - (NSString *) message;
1195 - (NSString *) type;
1198 - (NSString *) package;
1200 - (NSString *) version;
1202 - (void) setItem:(NSArray *)item;
1203 - (void) setPackage:(NSString *)package;
1204 - (void) setURL:(NSString *)url;
1205 - (void) setVersion:(NSString *)version;
1207 - (NSString *) compound:(NSString *)value;
1208 - (NSString *) compoundMessage;
1209 - (NSString *) compoundTitle;
1213 @protocol ProgressDelegate
1214 - (void) addProgressEvent:(CydiaProgressEvent *)event;
1215 - (void) setProgressPercent:(NSNumber *)percent;
1216 - (void) setProgressStatus:(NSDictionary *)status;
1217 - (void) setProgressCancellable:(NSNumber *)cancellable;
1218 - (bool) isProgressCancelled;
1219 - (void) setTitle:(NSString *)title;
1222 /* Status Delegation {{{ */
1224 public pkgAcquireStatus
1227 _transient NSObject<ProgressDelegate> *delegate_;
1237 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1238 delegate_ = delegate;
1241 NSObject<ProgressDelegate> *getDelegate() const {
1245 virtual bool MediaChange(std::string media, std::string drive) {
1249 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1252 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1253 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1254 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:@"STATUS" forItem:item]);
1255 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1258 virtual void Done(pkgAcquire::ItemDesc &item) {
1261 virtual void Fail(pkgAcquire::ItemDesc &item) {
1263 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1264 item.Owner->Status == pkgAcquire::Item::StatDone
1268 std::string &error(item.Owner->ErrorText);
1272 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:@"ERROR" forItem:item]);
1273 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1276 virtual bool Pulse(pkgAcquire *Owner) {
1277 bool value = pkgAcquireStatus::Pulse(Owner);
1280 double(CurrentBytes + CurrentItems) /
1281 double(TotalBytes + TotalItems)
1284 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1285 [NSNumber numberWithDouble:percent], @"Percent",
1287 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1288 [NSNumber numberWithDouble:TotalBytes], @"Total",
1289 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1290 nil] waitUntilDone:YES];
1292 if (value && ![delegate_ isProgressCancelled])
1300 _finline bool WasCancelled() const {
1304 virtual void Start() {
1305 pkgAcquireStatus::Start();
1306 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1309 virtual void Stop() {
1310 pkgAcquireStatus::Stop();
1311 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1312 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1316 /* Database Interface {{{ */
1317 typedef std::map< unsigned long, _H<Source> > SourceMap;
1319 @interface Database : NSObject {
1325 pkgCacheFile cache_;
1326 pkgDepCache::Policy *policy_;
1327 pkgRecords *records_;
1328 pkgProblemResolver *resolver_;
1329 pkgAcquire *fetcher_;
1331 SPtr<pkgPackageManager> manager_;
1332 pkgSourceList *list_;
1334 SourceMap sourceMap_;
1335 NSMutableArray *sourceList_;
1337 CFMutableArrayRef packages_;
1339 _transient NSObject<DatabaseDelegate> *delegate_;
1340 _transient NSObject<ProgressDelegate> *progress_;
1348 std::map<const char *, _H<NSString> > sections_;
1351 + (Database *) sharedInstance;
1354 - (void) _readCydia:(NSNumber *)fd;
1355 - (void) _readStatus:(NSNumber *)fd;
1356 - (void) _readOutput:(NSNumber *)fd;
1360 - (Package *) packageWithName:(NSString *)name;
1362 - (pkgCacheFile &) cache;
1363 - (pkgDepCache::Policy *) policy;
1364 - (pkgRecords *) records;
1365 - (pkgProblemResolver *) resolver;
1366 - (pkgAcquire &) fetcher;
1367 - (pkgSourceList &) list;
1368 - (NSArray *) packages;
1369 - (NSArray *) sources;
1370 - (Source *) sourceWithKey:(NSString *)key;
1371 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1379 - (void) updateWithStatus:(Status &)status;
1381 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1383 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1384 - (NSObject<ProgressDelegate> *) progressDelegate;
1386 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1388 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1392 /* ProgressEvent Implementation {{{ */
1393 @implementation CydiaProgressEvent
1395 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1396 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1399 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1400 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1401 [event setPackage:package];
1405 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1406 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1408 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1409 NSArray *fields([description componentsSeparatedByString:@" "]);
1410 [event setItem:fields];
1412 if ([fields count] > 3) {
1413 [event setPackage:[fields objectAtIndex:2]];
1414 [event setVersion:[fields objectAtIndex:3]];
1417 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1422 + (NSArray *) _attributeKeys {
1423 return [NSArray arrayWithObjects:
1433 - (NSArray *) attributeKeys {
1434 return [[self class] _attributeKeys];
1437 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1438 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1441 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1442 if ((self = [super init]) != nil) {
1448 - (NSString *) message {
1452 - (NSString *) type {
1456 - (NSArray *) item {
1457 return (id) item_ ?: [NSNull null];
1460 - (void) setItem:(NSArray *)item {
1464 - (NSString *) package {
1465 return (id) package_ ?: [NSNull null];
1468 - (void) setPackage:(NSString *)package {
1472 - (NSString *) url {
1473 return (id) url_ ?: [NSNull null];
1476 - (void) setURL:(NSString *)url {
1480 - (void) setVersion:(NSString *)version {
1484 - (NSString *) version {
1485 return (id) version_ ?: [NSNull null];
1488 - (NSString *) compound:(NSString *)value {
1490 NSString *mode(nil); {
1491 NSString *type([self type]);
1492 if ([type isEqualToString:@"ERROR"])
1493 mode = UCLocalize("ERROR");
1494 else if ([type isEqualToString:@"WARNING"])
1495 mode = UCLocalize("WARNING");
1499 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1505 - (NSString *) compoundMessage {
1506 return [self compound:[self message]];
1509 - (NSString *) compoundTitle {
1512 if (package_ == nil)
1514 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1515 title = [package name];
1519 return [self compound:title];
1525 // Cytore Definitions {{{
1526 struct PackageValue :
1529 Cytore::Offset<PackageValue> next_;
1531 uint32_t index_ : 23;
1532 uint32_t subscribed_ : 1;
1549 Cytore::Offset<PackageValue> packages_[1 << 16];
1552 static Cytore::File<MetaValue> MetaFile_;
1554 // Cytore Helper Functions {{{
1555 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1556 SplitHash nhash = { hashlittle(name, length) };
1558 PackageValue *metadata;
1560 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1561 offset: if (offset->IsNull()) {
1562 *offset = MetaFile_.New<PackageValue>(length + 1);
1563 metadata = &MetaFile_.Get(*offset);
1565 if (metadata == NULL) {
1569 metadata = new PackageValue();
1570 memset(metadata, 0, sizeof(*metadata));
1573 memcpy(metadata->name_, name, length + 1);
1574 metadata->nhash_ = nhash.u16[1];
1576 metadata = &MetaFile_.Get(*offset);
1578 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1579 offset = &metadata->next_;
1587 static void PackageImport(const void *key, const void *value, void *context) {
1588 bool &fail(*reinterpret_cast<bool *>(context));
1591 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1592 NSLog(@"failed to import package %@", key);
1596 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1597 NSDictionary *package((NSDictionary *) value);
1599 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1600 if ([subscribed boolValue] && !metadata->subscribed_)
1601 metadata->subscribed_ = true;
1603 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1604 time_t time([date timeIntervalSince1970]);
1605 if (metadata->first_ > time || metadata->first_ == 0)
1606 metadata->first_ = time;
1609 NSDate *date([package objectForKey:@"LastSeen"]);
1610 NSString *version([package objectForKey:@"LastVersion"]);
1612 if (date != nil && version != nil) {
1613 time_t time([date timeIntervalSince1970]);
1614 if (metadata->last_ < time || metadata->last_ == 0)
1615 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1616 size_t length(strlen(buffer));
1617 uint16_t vhash(hashlittle(buffer, length));
1619 size_t capped(std::min<size_t>(8, length));
1620 char *latest(buffer + length - capped);
1622 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1623 metadata->vhash_ = vhash;
1625 metadata->last_ = time;
1631 /* Source Class {{{ */
1632 @interface Source : NSObject {
1633 CYString depiction_;
1634 CYString description_;
1640 CYString distribution_;
1645 _H<NSString> authority_;
1647 CYString defaultIcon_;
1649 _H<NSDictionary> record_;
1653 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1655 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1657 - (NSString *) depictionForPackage:(NSString *)package;
1658 - (NSString *) supportForPackage:(NSString *)package;
1660 - (NSDictionary *) record;
1664 - (NSString *) distribution;
1665 - (NSString *) type;
1667 - (NSString *) host;
1669 - (NSString *) name;
1670 - (NSString *) description;
1671 - (NSString *) label;
1672 - (NSString *) origin;
1673 - (NSString *) version;
1675 - (NSString *) defaultIcon;
1679 @implementation Source
1683 distribution_.clear();
1686 description_.clear();
1692 defaultIcon_.clear();
1700 // XXX: this is a very inefficient way to call these deconstructors
1705 + (NSArray *) _attributeKeys {
1706 return [NSArray arrayWithObjects:
1721 - (NSArray *) attributeKeys {
1722 return [[self class] _attributeKeys];
1725 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1726 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1729 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1732 trusted_ = index->IsTrusted();
1734 uri_.set(pool, index->GetURI());
1735 distribution_.set(pool, index->GetDist());
1736 type_.set(pool, index->GetType());
1738 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1739 if (dindex != NULL) {
1741 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1744 pkgTagFile tags(&fd);
1746 pkgTagSection section;
1753 {"default-icon", &defaultIcon_},
1754 {"depiction", &depiction_},
1755 {"description", &description_},
1757 {"origin", &origin_},
1758 {"support", &support_},
1759 {"version", &version_},
1762 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1763 const char *start, *end;
1765 if (section.Find(names[i].name_, start, end)) {
1766 CYString &value(*names[i].value_);
1767 value.set(pool, start, end - start);
1773 record_ = [Sources_ objectForKey:[self key]];
1775 NSURL *url([NSURL URLWithString:uri_]);
1779 host_ = [host_ lowercaseString];
1782 // XXX: this is due to a bug in _H<>
1783 authority_ = (id) host_;
1785 authority_ = [url path];
1788 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1789 if ((self = [super init]) != nil) {
1790 [self setMetaIndex:index inPool:pool];
1794 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1795 NSDictionary *lhr = [self record];
1796 NSDictionary *rhr = [source record];
1799 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1801 NSString *lhs = [self name];
1802 NSString *rhs = [source name];
1804 if ([lhs length] != 0 && [rhs length] != 0) {
1805 unichar lhc = [lhs characterAtIndex:0];
1806 unichar rhc = [rhs characterAtIndex:0];
1808 if (isalpha(lhc) && !isalpha(rhc))
1809 return NSOrderedAscending;
1810 else if (!isalpha(lhc) && isalpha(rhc))
1811 return NSOrderedDescending;
1814 return [lhs compare:rhs options:LaxCompareOptions_];
1817 - (NSString *) depictionForPackage:(NSString *)package {
1818 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1821 - (NSString *) supportForPackage:(NSString *)package {
1822 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1825 - (NSDictionary *) record {
1833 - (NSString *) uri {
1837 - (NSString *) distribution {
1838 return distribution_;
1841 - (NSString *) type {
1845 - (NSString *) key {
1846 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1849 - (NSString *) host {
1853 - (NSString *) name {
1854 return origin_.empty() ? (id) authority_ : origin_;
1857 - (NSString *) description {
1858 return description_;
1861 - (NSString *) label {
1862 return label_.empty() ? (id) authority_ : label_;
1865 - (NSString *) origin {
1869 - (NSString *) version {
1873 - (NSString *) defaultIcon {
1874 return defaultIcon_;
1879 /* CydiaOperation Class {{{ */
1880 @interface CydiaOperation : NSObject {
1881 NSString *operator_;
1885 - (NSString *) operator;
1886 - (NSString *) value;
1890 @implementation CydiaOperation
1893 [operator_ release];
1898 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1899 if ((self = [super init]) != nil) {
1900 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1901 value_ = [[NSString alloc] initWithUTF8String:value];
1905 + (NSArray *) _attributeKeys {
1906 return [NSArray arrayWithObjects:
1912 - (NSArray *) attributeKeys {
1913 return [[self class] _attributeKeys];
1916 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1917 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1920 - (NSString *) operator {
1924 - (NSString *) value {
1930 /* CydiaClause Class {{{ */
1931 @interface CydiaClause : NSObject {
1933 CydiaOperation *version_;
1936 - (NSString *) package;
1937 - (CydiaOperation *) version;
1941 @implementation CydiaClause
1949 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1950 if ((self = [super init]) != nil) {
1951 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1953 if (const char *version = dep.TargetVer())
1954 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1956 version_ = [[NSNull null] retain];
1960 + (NSArray *) _attributeKeys {
1961 return [NSArray arrayWithObjects:
1967 - (NSArray *) attributeKeys {
1968 return [[self class] _attributeKeys];
1971 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1972 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1975 - (NSString *) package {
1979 - (CydiaOperation *) version {
1985 /* CydiaRelation Class {{{ */
1986 @interface CydiaRelation : NSObject {
1987 NSString *relationship_;
1988 NSMutableArray *clauses_;
1991 - (NSString *) relationship;
1992 - (NSArray *) clauses;
1996 @implementation CydiaRelation
1999 [relationship_ release];
2004 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2005 if ((self = [super init]) != nil) {
2006 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
2007 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
2009 pkgCache::DepIterator start;
2010 pkgCache::DepIterator end;
2011 dep.GlobOr(start, end); // ++dep
2014 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2016 // yes, seriously. (wtf?)
2024 + (NSArray *) _attributeKeys {
2025 return [NSArray arrayWithObjects:
2031 - (NSArray *) attributeKeys {
2032 return [[self class] _attributeKeys];
2035 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2036 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2039 - (NSString *) relationship {
2040 return relationship_;
2043 - (NSArray *) clauses {
2047 - (void) addClause:(CydiaClause *)clause {
2048 [clauses_ addObject:clause];
2053 /* Package Class {{{ */
2054 struct ParsedPackage {
2059 CYString depiction_;
2069 @interface Package : NSObject {
2072 uint32_t essential_ : 1;
2073 uint32_t obsolete_ : 1;
2074 uint32_t ignored_ : 1;
2078 _transient Database *database_;
2080 pkgCache::VerIterator version_;
2081 pkgCache::PkgIterator iterator_;
2082 pkgCache::VerFileIterator file_;
2088 CYString installed_;
2090 const char *section_;
2091 _transient NSString *section$_;
2095 PackageValue *metadata_;
2096 ParsedPackage *parsed_;
2098 NSMutableArray *tags_;
2101 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2102 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2104 - (pkgCache::PkgIterator) iterator;
2107 - (NSString *) section;
2108 - (NSString *) simpleSection;
2110 - (NSString *) longSection;
2111 - (NSString *) shortSection;
2115 - (Address *) maintainer;
2117 - (NSString *) longDescription;
2118 - (NSString *) shortDescription;
2121 - (PackageValue *) metadata;
2124 - (bool) subscribed;
2125 - (bool) setSubscribed:(bool)subscribed;
2129 - (NSString *) latest;
2130 - (NSString *) installed;
2131 - (BOOL) uninstalled;
2134 - (BOOL) upgradableAndEssential:(BOOL)essential;
2137 - (BOOL) unfiltered;
2141 - (BOOL) halfConfigured;
2142 - (BOOL) halfInstalled;
2144 - (NSString *) mode;
2147 - (NSString *) name;
2149 - (NSString *) homepage;
2150 - (NSString *) depiction;
2151 - (Address *) author;
2153 - (NSString *) support;
2155 - (NSArray *) files;
2156 - (NSArray *) warnings;
2157 - (NSArray *) applications;
2159 - (Source *) source;
2161 - (BOOL) matches:(NSString *)text;
2163 - (bool) hasSupportingRole;
2164 - (BOOL) hasTag:(NSString *)tag;
2165 - (NSString *) primaryPurpose;
2166 - (NSArray *) purposes;
2167 - (bool) isCommercial;
2169 - (void) setIndex:(size_t)index;
2171 - (CYString &) cyname;
2173 - (uint32_t) compareBySection:(NSArray *)sections;
2178 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2179 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2180 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2181 - (bool) isVisibleInSection:(NSString *)section;
2182 - (bool) isVisibleInSource:(Source *)source;
2186 uint32_t PackageChangesRadix(Package *self, void *) {
2191 uint32_t timestamp : 30;
2192 uint32_t ignored : 1;
2193 uint32_t upgradable : 1;
2197 bool upgradable([self upgradableAndEssential:YES]);
2198 value.bits.upgradable = upgradable ? 1 : 0;
2201 value.bits.timestamp = 0;
2202 value.bits.ignored = [self ignored] ? 0 : 1;
2203 value.bits.upgradable = 1;
2205 value.bits.timestamp = [self seen] >> 2;
2206 value.bits.ignored = 0;
2207 value.bits.upgradable = 0;
2210 return _not(uint32_t) - value.key;
2213 uint32_t PackagePrefixRadix(Package *self, void *context) {
2214 size_t offset(reinterpret_cast<size_t>(context));
2215 CYString &name([self cyname]);
2217 size_t size(name.size());
2220 char *text(name.data());
2223 if (!isdigit(text[0]))
2227 while (size != digits && isdigit(text[digits]))
2235 if (offset == 0 && zeros != 0) {
2236 memset(data, '0', zeros);
2237 memcpy(data + zeros, text, 4 - zeros);
2239 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2240 if (size <= offset - zeros)
2243 text += offset - zeros;
2244 size -= offset - zeros;
2247 memcpy(data, text, 4);
2249 memcpy(data, text, size);
2250 memset(data + size, 0, 4 - size);
2253 for (size_t i(0); i != 4; ++i)
2254 if (isalpha(data[i]))
2262 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2264 /* XXX: ntohl may be more honest */
2265 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2268 CYString &(*PackageName)(Package *self, SEL sel);
2270 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2271 _profile(PackageNameCompare)
2272 CYString &lhi(PackageName(lhs, @selector(cyname)));
2273 CYString &rhi(PackageName(rhs, @selector(cyname)));
2274 CFStringRef lhn(lhi), rhn(rhi);
2277 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2278 else if (rhn == NULL)
2279 return NSOrderedDescending;
2281 _profile(PackageNameCompare$NumbersLast)
2282 if (!lhi.empty() && !rhi.empty()) {
2283 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2284 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2285 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2286 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2287 return lha ? NSOrderedAscending : NSOrderedDescending;
2291 CFIndex length = CFStringGetLength(lhn);
2293 _profile(PackageNameCompare$Compare)
2294 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2299 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2300 return PackageNameCompare(*lhs, *rhs, context);
2303 struct PackageNameOrdering :
2304 std::binary_function<Package *, Package *, bool>
2306 _finline bool operator ()(Package *lhs, Package *rhs) const {
2307 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2311 @implementation Package
2313 - (NSString *) description {
2314 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2318 if (parsed_ != NULL)
2327 + (NSString *) webScriptNameForSelector:(SEL)selector {
2329 else if (selector == @selector(clear))
2331 else if (selector == @selector(getField:))
2333 else if (selector == @selector(hasTag:))
2335 else if (selector == @selector(install))
2337 else if (selector == @selector(remove))
2343 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2344 return [self webScriptNameForSelector:selector] == nil;
2347 + (NSArray *) _attributeKeys {
2348 return [NSArray arrayWithObjects:
2367 @"shortDescription",
2380 - (NSArray *) attributeKeys {
2381 return [[self class] _attributeKeys];
2384 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2385 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2388 - (NSArray *) relations {
2389 @synchronized (database_) {
2390 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2391 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2392 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2396 - (NSString *) getField:(NSString *)name {
2397 @synchronized (database_) {
2398 if ([database_ era] != era_ || file_.end())
2401 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2403 const char *start, *end;
2404 if (!parser.Find([name UTF8String], start, end))
2405 return (NSString *) [NSNull null];
2407 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2411 if (parsed_ != NULL)
2413 @synchronized (database_) {
2414 if ([database_ era] != era_ || file_.end())
2417 ParsedPackage *parsed(new ParsedPackage);
2420 _profile(Package$parse)
2421 pkgRecords::Parser *parser;
2423 _profile(Package$parse$Lookup)
2424 parser = &[database_ records]->Lookup(file_);
2429 _profile(Package$parse$Find)
2434 {"icon", &parsed->icon_},
2435 {"depiction", &parsed->depiction_},
2436 {"homepage", &parsed->homepage_},
2437 {"website", &website},
2438 {"bugs", &parsed->bugs_},
2439 {"support", &parsed->support_},
2440 {"sponsor", &parsed->sponsor_},
2441 {"author", &parsed->author_},
2444 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2445 const char *start, *end;
2447 if (parser->Find(names[i].name_, start, end)) {
2448 CYString &value(*names[i].value_);
2449 _profile(Package$parse$Value)
2450 value.set(pool_, start, end - start);
2456 _profile(Package$parse$Tagline)
2457 const char *start, *end;
2458 if (parser->ShortDesc(start, end)) {
2459 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2462 while (stop != start && stop[-1] == '\r')
2464 parsed->tagline_.set(pool_, start, stop - start);
2468 _profile(Package$parse$Retain)
2469 if (parsed->homepage_.empty())
2470 parsed->homepage_ = website;
2471 if (parsed->homepage_ == parsed->depiction_)
2472 parsed->homepage_.clear();
2477 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2478 if ((self = [super init]) != nil) {
2479 _profile(Package$initWithVersion)
2482 database_ = database;
2483 era_ = [database era];
2487 pkgCache::PkgIterator iterator(version.ParentPkg());
2488 iterator_ = iterator;
2490 _profile(Package$initWithVersion$Version)
2491 if (!version_.end())
2492 file_ = version_.FileList();
2494 pkgCache &cache([database_ cache]);
2495 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2499 _profile(Package$initWithVersion$Cache)
2500 name_.set(NULL, iterator.Display());
2502 latest_.set(NULL, StripVersion_(version_.VerStr()));
2504 pkgCache::VerIterator current(iterator.CurrentVer());
2506 installed_.set(NULL, StripVersion_(current.VerStr()));
2509 _profile(Package$initWithVersion$Tags)
2510 pkgCache::TagIterator tag(iterator.TagList());
2512 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2514 const char *name(tag.Name());
2515 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2517 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2518 if (strcmp(name + 6, "enduser") == 0)
2520 else if (strcmp(name + 6, "hacker") == 0)
2522 else if (strcmp(name + 6, "developer") == 0)
2524 else if (strcmp(name + 6, "cydia") == 0)
2530 if (strncmp(name, "cydia::", 7) == 0) {
2531 if (strcmp(name + 7, "essential") == 0)
2533 else if (strcmp(name + 7, "obsolete") == 0)
2538 } while (!tag.end());
2542 _profile(Package$initWithVersion$Metadata)
2543 const char *mixed(iterator.Name());
2544 size_t size(strlen(mixed));
2545 char lower[size + 1];
2547 for (size_t i(0); i != size; ++i)
2548 lower[i] = mixed[i] | 0x20;
2551 PackageValue *metadata(PackageFind(lower, size));
2552 metadata_ = metadata;
2554 id_.set(NULL, metadata->name_, size);
2556 const char *latest(version_.VerStr());
2557 size_t length(strlen(latest));
2559 uint16_t vhash(hashlittle(latest, length));
2561 size_t capped(std::min<size_t>(8, length));
2562 latest = latest + length - capped;
2564 if (metadata->first_ == 0)
2565 metadata->first_ = now_;
2567 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2568 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2569 metadata->vhash_ = vhash;
2570 metadata->last_ = now_;
2571 } else if (metadata->last_ == 0)
2572 metadata->last_ = metadata->first_;
2575 _profile(Package$initWithVersion$Section)
2576 section_ = iterator.Section();
2579 _profile(Package$initWithVersion$Flags)
2580 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2581 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2586 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2587 pkgCache::VerIterator version;
2589 _profile(Package$packageWithIterator$GetCandidateVer)
2590 version = [database policy]->GetCandidateVer(iterator);
2598 _profile(Package$packageWithIterator$Allocate)
2599 package = [Package allocWithZone:zone];
2602 _profile(Package$packageWithIterator$Initialize)
2604 initWithVersion:version
2611 _profile(Package$packageWithIterator$Autorelease)
2612 package = [package autorelease];
2618 - (pkgCache::PkgIterator) iterator {
2622 - (NSString *) section {
2623 if (section$_ == nil) {
2624 if (section_ == NULL)
2627 _profile(Package$section$mappedSectionForPointer)
2628 section$_ = [database_ mappedSectionForPointer:section_];
2633 - (NSString *) simpleSection {
2634 if (NSString *section = [self section])
2635 return Simplify(section);
2640 - (NSString *) longSection {
2641 return LocalizeSection([self section]);
2644 - (NSString *) shortSection {
2645 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2648 - (NSString *) uri {
2651 pkgIndexFile *index;
2652 pkgCache::PkgFileIterator file(file_.File());
2653 if (![database_ list].FindIndex(file, index))
2655 return [NSString stringWithUTF8String:iterator_->Path];
2656 //return [NSString stringWithUTF8String:file.Site()];
2657 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2661 - (Address *) maintainer {
2662 @synchronized (database_) {
2663 if ([database_ era] != era_ || file_.end())
2666 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2667 const std::string &maintainer(parser->Maintainer());
2668 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2672 @synchronized (database_) {
2673 if ([database_ era] != era_ || version_.end())
2676 return version_->InstalledSize;
2679 - (NSString *) longDescription {
2680 @synchronized (database_) {
2681 if ([database_ era] != era_ || file_.end())
2684 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2685 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2687 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2688 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2689 if ([lines count] < 2)
2692 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2693 for (size_t i(1), e([lines count]); i != e; ++i) {
2694 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2695 [trimmed addObject:trim];
2698 return [trimmed componentsJoinedByString:@"\n"];
2701 - (NSString *) shortDescription {
2702 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2706 _profile(Package$index)
2707 CFStringRef name((CFStringRef) [self name]);
2708 if (CFStringGetLength(name) == 0)
2710 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2711 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2713 return toupper(character);
2717 - (PackageValue *) metadata {
2722 PackageValue *metadata([self metadata]);
2723 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2726 - (bool) subscribed {
2727 return [self metadata]->subscribed_;
2730 - (bool) setSubscribed:(bool)subscribed {
2731 PackageValue *metadata([self metadata]);
2732 if (metadata->subscribed_ == subscribed)
2734 metadata->subscribed_ = subscribed;
2742 - (NSString *) latest {
2746 - (NSString *) installed {
2750 - (BOOL) uninstalled {
2751 return installed_.empty();
2755 return !version_.end();
2758 - (BOOL) upgradableAndEssential:(BOOL)essential {
2759 _profile(Package$upgradableAndEssential)
2760 pkgCache::VerIterator current(iterator_.CurrentVer());
2762 return essential && essential_;
2764 return !version_.end() && version_ != current;
2768 - (BOOL) essential {
2773 return [database_ cache][iterator_].InstBroken();
2776 - (BOOL) unfiltered {
2777 _profile(Package$unfiltered$obsolete)
2778 if (_unlikely(obsolete_))
2782 _profile(Package$unfiltered$hasSupportingRole)
2783 if (_unlikely(![self hasSupportingRole]))
2791 if (![self unfiltered])
2796 _profile(Package$visible$section)
2797 section = [self section];
2800 _profile(Package$visible$isSectionVisible)
2801 if (!isSectionVisible(section))
2809 unsigned char current(iterator_->CurrentState);
2810 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2813 - (BOOL) halfConfigured {
2814 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2817 - (BOOL) halfInstalled {
2818 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2822 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2823 return state.Mode != pkgDepCache::ModeKeep;
2826 - (NSString *) mode {
2827 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2829 switch (state.Mode) {
2830 case pkgDepCache::ModeDelete:
2831 if ((state.iFlags & pkgDepCache::Purge) != 0)
2835 case pkgDepCache::ModeKeep:
2836 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2837 return @"REINSTALL";
2838 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2842 case pkgDepCache::ModeInstall:
2843 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2844 return @"REINSTALL";
2845 else*/ switch (state.Status) {
2847 return @"DOWNGRADE";
2853 return @"NEW_INSTALL";
2864 - (NSString *) name {
2865 return name_.empty() ? id_ : name_;
2868 - (UIImage *) icon {
2869 NSString *section = [self simpleSection];
2872 if (parsed_ != NULL)
2873 if (NSString *href = parsed_->icon_)
2874 if ([href hasPrefix:@"file:///"])
2875 // XXX: correct escaping
2876 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2877 if (icon == nil) if (section != nil)
2878 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2879 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2880 if ([dicon hasPrefix:@"file:///"])
2881 // XXX: correct escaping
2882 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2884 icon = [UIImage applicationImageNamed:@"unknown.png"];
2888 - (NSString *) homepage {
2889 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2892 - (NSString *) depiction {
2893 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2896 - (Address *) sponsor {
2897 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2900 - (Address *) author {
2901 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2904 - (NSString *) support {
2905 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2908 - (NSArray *) files {
2909 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2910 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2913 fin.open([path UTF8String]);
2918 while (std::getline(fin, line))
2919 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2924 - (NSString *) state {
2925 @synchronized (database_) {
2926 if ([database_ era] != era_ || file_.end())
2929 switch (iterator_->CurrentState) {
2930 case pkgCache::State::NotInstalled:
2931 return @"NotInstalled";
2932 case pkgCache::State::UnPacked:
2934 case pkgCache::State::HalfConfigured:
2935 return @"HalfConfigured";
2936 case pkgCache::State::HalfInstalled:
2937 return @"HalfInstalled";
2938 case pkgCache::State::ConfigFiles:
2939 return @"ConfigFiles";
2940 case pkgCache::State::Installed:
2941 return @"Installed";
2942 case pkgCache::State::TriggersAwaited:
2943 return @"TriggersAwaited";
2944 case pkgCache::State::TriggersPending:
2945 return @"TriggersPending";
2948 return (NSString *) [NSNull null];
2951 - (NSString *) selection {
2952 @synchronized (database_) {
2953 if ([database_ era] != era_ || file_.end())
2956 switch (iterator_->SelectedState) {
2957 case pkgCache::State::Unknown:
2959 case pkgCache::State::Install:
2961 case pkgCache::State::Hold:
2963 case pkgCache::State::DeInstall:
2964 return @"DeInstall";
2965 case pkgCache::State::Purge:
2969 return (NSString *) [NSNull null];
2972 - (NSArray *) warnings {
2973 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2974 const char *name(iterator_.Name());
2976 size_t length(strlen(name));
2977 if (length < 2) invalid:
2978 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2979 else for (size_t i(0); i != length; ++i)
2981 /* XXX: technically this is not allowed */
2982 (name[i] < 'A' || name[i] > 'Z') &&
2983 (name[i] < 'a' || name[i] > 'z') &&
2984 (name[i] < '0' || name[i] > '9') &&
2985 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2988 if (strcmp(name, "cydia") != 0) {
2991 bool _private = false;
2994 bool repository = [[self section] isEqualToString:@"Repositories"];
2996 if (NSArray *files = [self files])
2997 for (NSString *file in files)
2998 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3000 else if (!user && [file isEqualToString:@"/User"])
3002 else if (!_private && [file isEqualToString:@"/private"])
3004 else if (!stash && [file isEqualToString:@"/var/stash"])
3007 /* XXX: this is not sensitive enough. only some folders are valid. */
3008 if (cydia && !repository)
3009 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3011 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3013 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3015 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3018 return [warnings count] == 0 ? nil : warnings;
3021 - (NSArray *) applications {
3022 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3024 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3026 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
3027 if (NSArray *files = [self files])
3028 for (NSString *file in files)
3029 if (application_r(file)) {
3030 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3031 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3032 if ([id isEqualToString:me])
3035 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3037 display = application_r[1];
3039 NSString *bundle([file stringByDeletingLastPathComponent]);
3040 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3041 if (icon == nil || [icon length] == 0)
3043 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3045 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3046 [applications addObject:application];
3048 [application addObject:id];
3049 [application addObject:display];
3050 [application addObject:url];
3053 return [applications count] == 0 ? nil : applications;
3056 - (Source *) source {
3057 if (source_ == nil) {
3058 @synchronized (database_) {
3059 if ([database_ era] != era_ || file_.end())
3060 source_ = (Source *) [NSNull null];
3062 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
3066 return source_ == (Source *) [NSNull null] ? nil : source_;
3069 - (BOOL) matches:(NSString *)text {
3075 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
3076 if (range.location != NSNotFound)
3079 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
3080 if (range.location != NSNotFound)
3085 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
3086 if (range.location != NSNotFound)
3092 - (bool) hasSupportingRole {
3097 if ([Role_ isEqualToString:@"User"])
3101 if ([Role_ isEqualToString:@"Hacker"])
3105 if ([Role_ isEqualToString:@"Developer"])
3110 - (NSArray *) tags {
3114 - (BOOL) hasTag:(NSString *)tag {
3115 return tags_ == nil ? NO : [tags_ containsObject:tag];
3118 - (NSString *) primaryPurpose {
3119 for (NSString *tag in tags_)
3120 if ([tag hasPrefix:@"purpose::"])
3121 return [tag substringFromIndex:9];
3125 - (NSArray *) purposes {
3126 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3127 for (NSString *tag in tags_)
3128 if ([tag hasPrefix:@"purpose::"])
3129 [purposes addObject:[tag substringFromIndex:9]];
3130 return [purposes count] == 0 ? nil : purposes;
3133 - (bool) isCommercial {
3134 return [self hasTag:@"cydia::commercial"];
3137 - (void) setIndex:(size_t)index {
3138 if (metadata_->index_ != index)
3139 metadata_->index_ = index;
3142 - (CYString &) cyname {
3143 return name_.empty() ? id_ : name_;
3146 - (uint32_t) compareBySection:(NSArray *)sections {
3147 NSString *section([self section]);
3148 for (size_t i(0), e([sections count]); i != e; ++i) {
3149 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3153 return _not(uint32_t);
3157 @synchronized (database_) {
3158 pkgProblemResolver *resolver = [database_ resolver];
3159 resolver->Clear(iterator_);
3161 pkgCacheFile &cache([database_ cache]);
3162 cache->SetReInstall(iterator_, false);
3163 cache->MarkKeep(iterator_, false);
3167 @synchronized (database_) {
3168 pkgProblemResolver *resolver = [database_ resolver];
3169 resolver->Clear(iterator_);
3170 resolver->Protect(iterator_);
3172 pkgCacheFile &cache([database_ cache]);
3173 cache->SetReInstall(iterator_, false);
3174 cache->MarkInstall(iterator_, false);
3176 pkgDepCache::StateCache &state((*cache)[iterator_]);
3177 if (!state.Install())
3178 cache->SetReInstall(iterator_, true);
3182 @synchronized (database_) {
3183 pkgProblemResolver *resolver = [database_ resolver];
3184 resolver->Clear(iterator_);
3185 resolver->Remove(iterator_);
3186 resolver->Protect(iterator_);
3188 pkgCacheFile &cache([database_ cache]);
3189 cache->SetReInstall(iterator_, false);
3190 cache->MarkDelete(iterator_, true);
3193 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3194 _profile(Package$isUnfilteredAndSearchedForBy)
3197 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3198 value &= [self unfiltered];
3201 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3202 value &= [self matches:search];
3209 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3210 if ([search length] == 0)
3213 _profile(Package$isUnfilteredAndSelectedForBy)
3216 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3217 value &= [self unfiltered];
3220 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3221 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3228 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3229 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3232 - (bool) isVisibleInSection:(NSString *)name {
3233 NSString *section([self section]);
3237 section == nil && [name length] == 0 ||
3238 [name isEqualToString:section]
3239 ) && [self visible];
3242 - (bool) isVisibleInSource:(Source *)source {
3243 return [self source] == source && [self visible];
3248 /* Section Class {{{ */
3249 @interface Section : NSObject {
3254 NSString *localized_;
3257 - (NSComparisonResult) compareByLocalized:(Section *)section;
3258 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3259 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3260 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3261 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3262 - (NSString *) name;
3269 - (void) addToCount;
3271 - (void) setCount:(size_t)count;
3272 - (NSString *) localized;
3276 @implementation Section
3280 if (localized_ != nil)
3281 [localized_ release];
3285 - (NSComparisonResult) compareByLocalized:(Section *)section {
3286 NSString *lhs(localized_);
3287 NSString *rhs([section localized]);
3289 /*if ([lhs length] != 0 && [rhs length] != 0) {
3290 unichar lhc = [lhs characterAtIndex:0];
3291 unichar rhc = [rhs characterAtIndex:0];
3293 if (isalpha(lhc) && !isalpha(rhc))
3294 return NSOrderedAscending;
3295 else if (!isalpha(lhc) && isalpha(rhc))
3296 return NSOrderedDescending;
3299 return [lhs compare:rhs options:LaxCompareOptions_];
3302 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3303 if ((self = [self initWithName:name localize:NO]) != nil) {
3304 if (localized != nil)
3305 localized_ = [localized retain];
3309 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3310 return [self initWithName:name row:0 localize:localize];
3313 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3314 if ((self = [super init]) != nil) {
3315 name_ = [name retain];
3319 localized_ = [LocalizeSection(name_) retain];
3323 /* XXX: localize the index thingees */
3324 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3325 if ((self = [super init]) != nil) {
3326 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3332 - (NSString *) name {
3352 - (void) addToCount {
3356 - (void) setCount:(size_t)count {
3360 - (NSString *) localized {
3367 static NSString *Colon_;
3368 static NSString *Elision_;
3369 static NSString *Error_;
3370 static NSString *Warning_;
3372 /* Database Implementation {{{ */
3373 @implementation Database
3375 + (Database *) sharedInstance {
3376 static Database *instance;
3377 if (instance == nil)
3378 instance = [[Database alloc] init];
3386 - (void) releasePackages {
3387 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3388 CFArrayRemoveAllValues(packages_);
3392 // XXX: actually implement this thing
3394 [sourceList_ release];
3395 [self releasePackages];
3396 apr_pool_destroy(pool_);
3397 NSRecycleZone(zone_);
3401 - (void) _readCydia:(NSNumber *)fd { _pooled
3402 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3403 std::istream is(&ib);
3406 static Pcre finish_r("^finish:([^:]*)$");
3408 while (std::getline(is, line)) {
3409 const char *data(line.c_str());
3410 size_t size = line.size();
3411 lprintf("C:%s\n", data);
3413 if (finish_r(data, size)) {
3414 NSString *finish = finish_r[1];
3415 int index = [Finishes_ indexOfObject:finish];
3416 if (index != INT_MAX && index > Finish_)
3424 - (void) _readStatus:(NSNumber *)fd { _pooled
3425 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3426 std::istream is(&ib);
3429 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3430 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3432 while (std::getline(is, line)) {
3433 const char *data(line.c_str());
3434 size_t size(line.size());
3435 lprintf("S:%s\n", data);
3437 if (conffile_r(data, size)) {
3438 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3439 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3440 } else if (strncmp(data, "status: ", 8) == 0) {
3441 // status: <package>: {unpacked,half-configured,installed}
3442 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:@"STATUS"]);
3443 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3444 } else if (strncmp(data, "processing: ", 12) == 0) {
3445 // processing: configure: config-test
3446 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:@"STATUS"]);
3447 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3448 } else if (pmstatus_r(data, size)) {
3449 std::string type([pmstatus_r[1] UTF8String]);
3451 NSString *package = pmstatus_r[2];
3452 if ([package isEqualToString:@"dpkg-exec"])
3455 float percent([pmstatus_r[3] floatValue]);
3456 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3458 NSString *string = pmstatus_r[4];
3460 if (type == "pmerror") {
3461 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:@"ERROR" forPackage:package]);
3462 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3463 } else if (type == "pmstatus") {
3464 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:@"STATUS" forPackage:package]);
3465 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3466 } else if (type == "pmconffile")
3467 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3469 lprintf("E:unknown pmstatus\n");
3471 lprintf("E:unknown status\n");
3477 - (void) _readOutput:(NSNumber *)fd { _pooled
3478 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3479 std::istream is(&ib);
3482 while (std::getline(is, line)) {
3483 lprintf("O:%s\n", line.c_str());
3485 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:@"INFORMATION"]);
3486 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3496 - (Package *) packageWithName:(NSString *)name {
3497 @synchronized (self) {
3498 if (static_cast<pkgDepCache *>(cache_) == NULL)
3500 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3501 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3505 if ((self = [super init]) != nil) {
3512 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3513 apr_pool_create(&pool_, NULL);
3515 size_t capacity(MetaFile_->active_);
3521 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3522 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3526 _assert(pipe(fds) != -1);
3529 _config->Set("APT::Keep-Fds::", cydiafd_);
3530 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3533 detachNewThreadSelector:@selector(_readCydia:)
3535 withObject:[NSNumber numberWithInt:fds[0]]
3538 _assert(pipe(fds) != -1);
3542 detachNewThreadSelector:@selector(_readStatus:)
3544 withObject:[NSNumber numberWithInt:fds[0]]
3547 _assert(pipe(fds) != -1);
3548 _assert(dup2(fds[0], 0) != -1);
3549 _assert(close(fds[0]) != -1);
3551 input_ = fdopen(fds[1], "a");
3553 _assert(pipe(fds) != -1);
3554 _assert(dup2(fds[1], 1) != -1);
3555 _assert(close(fds[1]) != -1);
3558 detachNewThreadSelector:@selector(_readOutput:)
3560 withObject:[NSNumber numberWithInt:fds[0]]
3565 - (pkgCacheFile &) cache {
3569 - (pkgDepCache::Policy *) policy {
3573 - (pkgRecords *) records {
3577 - (pkgProblemResolver *) resolver {
3581 - (pkgAcquire &) fetcher {
3585 - (pkgSourceList &) list {
3589 - (NSArray *) packages {
3590 return (NSArray *) packages_;
3593 - (NSArray *) sources {
3597 - (Source *) sourceWithKey:(NSString *)key {
3598 for (Source *source in [self sources]) {
3599 if ([[source key] isEqualToString:key])
3604 - (bool) popErrorWithTitle:(NSString *)title {
3607 while (!_error->empty()) {
3609 bool warning(!_error->PopMessage(error));
3614 size_t size(error.size());
3615 if (size == 0 || error[size - 1] != '\n')
3617 error.resize(size - 1);
3620 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3622 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? @"WARNING" : @"ERROR")] forTask:title];
3628 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3629 return [self popErrorWithTitle:title] || !success;
3632 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3633 @synchronized (self) {
3636 [self releasePackages];
3639 [sourceList_ removeAllObjects];
3659 apr_pool_clear(pool_);
3661 NSRecycleZone(zone_);
3662 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3664 int chk(creat("/tmp/cydia.chk", 0644));
3668 if (invocation != nil)
3669 [invocation invoke];
3671 NSString *title(UCLocalize("DATABASE"));
3674 OpProgress progress;
3675 while (!cache_.Open(progress, true)) { pop:
3677 bool warning(!_error->PopMessage(error));
3678 lprintf("cache_.Open():[%s]\n", error.c_str());
3680 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3681 [delegate_ repairWithSelector:@selector(configure)];
3682 else if (error == "The package lists or status file could not be parsed or opened.")
3683 [delegate_ repairWithSelector:@selector(update)];
3684 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3685 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3686 // else if (error == "Malformed Status line")
3687 // else if (error == "The list of sources could not be read.")
3689 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? @"WARNING" : @"ERROR")] forTask:title];
3699 unlink("/tmp/cydia.chk");
3701 now_ = [[NSDate date] timeIntervalSince1970];
3703 policy_ = new pkgDepCache::Policy();
3704 records_ = new pkgRecords(cache_);
3705 resolver_ = new pkgProblemResolver(cache_);
3706 fetcher_ = new pkgAcquire(&status_);
3709 list_ = new pkgSourceList();
3710 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3713 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3714 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:@"ERROR"] forTask:title];
3718 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3721 if (cache_->BrokenCount() != 0) {
3722 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3725 if (cache_->BrokenCount() != 0) {
3726 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:@"ERROR"] forTask:title];
3730 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3734 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3735 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3736 [sourceList_ addObject:object];
3738 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3739 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3740 // XXX: this could be more intelligent
3741 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3742 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3744 sourceMap_[cached->ID] = object;
3749 /*std::vector<Package *> packages;
3750 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3751 [packages_ release];
3756 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3757 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3758 //packages.push_back(package);
3759 CFArrayAppendValue(packages_, [package retain]);
3763 /*if (packages.empty())
3764 packages_ = [[NSArray alloc] init];
3766 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3769 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3770 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3771 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3779 /*if (!packages.empty())
3780 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3781 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3783 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3785 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3787 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3791 size_t count(CFArrayGetCount(packages_));
3792 MetaFile_->active_ = count;
3794 for (size_t index(0); index != count; ++index)
3795 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3799 } } CYPoolEnd() _trace(); }
3802 @synchronized (self) {
3804 resolver_ = new pkgProblemResolver(cache_);
3806 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3807 if (!cache_[iterator].Keep())
3808 cache_->MarkKeep(iterator, false);
3809 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3810 cache_->SetReInstall(iterator, false);
3813 - (void) configure {
3814 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3816 system([dpkg UTF8String]);
3821 // XXX: I don't remember this condition
3826 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3828 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3830 if ([self popErrorWithTitle:title])
3834 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3837 public pkgArchiveCleaner
3840 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3845 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3852 fetcher_->Shutdown();
3854 pkgRecords records(cache_);
3856 lock_ = new FileFd();
3857 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3859 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3861 if ([self popErrorWithTitle:title])
3865 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3868 manager_ = (_system->CreatePM(cache_));
3869 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3876 bool substrate(RestartSubstrate_);
3877 RestartSubstrate_ = false;
3879 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3881 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3883 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3885 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3886 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3889 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3891 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3893 [self popErrorWithTitle:title];
3897 bool failed = false;
3898 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3899 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3901 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3907 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3915 RestartSubstrate_ = true;
3918 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3920 if (_error->PendingError()) {
3925 if (result == pkgPackageManager::Failed) {
3930 if (result != pkgPackageManager::Completed) {
3935 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3937 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3939 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3940 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3943 if (![before isEqualToArray:after])
3948 NSString *title(UCLocalize("UPGRADE"));
3949 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3955 [self updateWithStatus:status_];
3958 - (void) updateWithStatus:(Status &)status {
3959 NSString *title(UCLocalize("REFRESHING_DATA"));
3962 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3966 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3967 if ([self popErrorWithTitle:title])
3970 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3972 bool success(ListUpdate(status, list, PulseInterval_));
3973 if (status.WasCancelled())
3976 [self popErrorWithTitle:title forOperation:success];
3978 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3980 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3984 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3985 delegate_ = delegate;
3988 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3989 progress_ = delegate;
3990 status_.setDelegate(delegate);
3993 - (NSObject<ProgressDelegate> *) progressDelegate {
3997 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3998 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3999 return i == sourceMap_.end() ? nil : i->second;
4002 - (NSString *) mappedSectionForPointer:(const char *)section {
4003 _H<NSString> *mapped;
4005 _profile(Database$mappedSectionForPointer$Cache)
4006 mapped = §ions_[section];
4009 if (*mapped == NULL) {
4010 size_t length(strlen(section));
4011 char spaced[length + 1];
4013 _profile(Database$mappedSectionForPointer$Replace)
4014 for (size_t index(0); index != length; ++index)
4015 spaced[index] = section[index] == '_' ? ' ' : section[index];
4016 spaced[length] = '\0';
4021 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4022 string = [NSString stringWithUTF8String:spaced];
4025 _profile(Database$mappedSectionForPointer$Map)
4026 string = [SectionMap_ objectForKey:string] ?: string;
4036 /* Web Scripting {{{ */
4037 @interface CydiaObject : NSObject {
4039 _transient id delegate_;
4042 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4046 @implementation CydiaObject
4049 [indirect_ release];
4053 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4054 if ((self = [super init]) != nil) {
4055 indirect_ = [indirect retain];
4059 - (void) setDelegate:(id)delegate {
4060 delegate_ = delegate;
4063 + (NSArray *) _attributeKeys {
4064 return [NSArray arrayWithObjects:
4079 - (NSArray *) attributeKeys {
4080 return [[self class] _attributeKeys];
4083 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4084 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4087 - (NSString *) version {
4091 - (NSString *) device {
4092 return [[UIDevice currentDevice] uniqueIdentifier];
4095 - (NSString *) firmware {
4096 return [[UIDevice currentDevice] systemVersion];
4099 - (NSString *) hostname {
4100 return [[UIDevice currentDevice] name];
4103 - (NSString *) idiom {
4104 return (id) Idiom_ ?: [NSNull null];
4107 - (NSString *) plmn {
4108 return (id) PLMN_ ?: [NSNull null];
4111 - (NSString *) ecid {
4112 return (id) ChipID_ ?: [NSNull null];
4115 - (NSString *) serial {
4116 return SerialNumber_;
4119 - (NSString *) role {
4120 return (id) Role_ ?: [NSNull null];
4123 - (NSString *) model {
4124 return [NSString stringWithUTF8String:Machine_];
4127 - (NSString *) token {
4128 return (id) Token_ ?: [NSNull null];
4131 + (NSString *) webScriptNameForSelector:(SEL)selector {
4133 else if (selector == @selector(addCydiaHost:))
4134 return @"addCydiaHost";
4135 else if (selector == @selector(addTrivialSource:))
4136 return @"addTrivialSource";
4137 else if (selector == @selector(close))
4139 else if (selector == @selector(du:))
4141 else if (selector == @selector(stringWithFormat:arguments:))
4143 else if (selector == @selector(getAllSources))
4144 return @"getAllSourcs";
4145 else if (selector == @selector(getKernelNumber:))
4146 return @"getKernelNumber";
4147 else if (selector == @selector(getKernelString:))
4148 return @"getKernelString";
4149 else if (selector == @selector(getInstalledPackages))
4150 return @"getInstalledPackages";
4151 else if (selector == @selector(getPackageById:))
4152 return @"getPackageById";
4153 else if (selector == @selector(installPackages:))
4154 return @"installPackages";
4155 else if (selector == @selector(localizedStringForKey:value:table:))
4157 else if (selector == @selector(refreshSources))
4158 return @"refreshSources";
4159 else if (selector == @selector(removeButton))
4160 return @"removeButton";
4161 else if (selector == @selector(substitutePackageNames:))
4162 return @"substitutePackageNames";
4163 else if (selector == @selector(scrollToBottom:))
4164 return @"scrollToBottom";
4165 else if (selector == @selector(setAllowsNavigationAction:))
4166 return @"setAllowsNavigationAction";
4167 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4168 return @"setButtonImage";
4169 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4170 return @"setButtonTitle";
4171 else if (selector == @selector(setHidesBackButton:))
4172 return @"setHidesBackButton";
4173 else if (selector == @selector(setHidesNavigationBar:))
4174 return @"setHidesNavigationBar";
4175 else if (selector == @selector(setNavigationBarStyle:))
4176 return @"setNavigationBarStyle";
4177 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4178 return @"setNavigationBarTintColor";
4179 else if (selector == @selector(setPopupHook:))
4180 return @"setPopupHook";
4181 else if (selector == @selector(setToken:))
4183 else if (selector == @selector(setViewportWidth:))
4184 return @"setViewportWidth";
4185 else if (selector == @selector(statfs:))
4187 else if (selector == @selector(supports:))
4193 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4194 return [self webScriptNameForSelector:selector] == nil;
4197 - (BOOL) supports:(NSString *)feature {
4198 return [feature isEqualToString:@"window.open"];
4201 - (NSNumber *) getKernelNumber:(NSString *)name {
4202 const char *string([name UTF8String]);
4205 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4206 return (id) [NSNull null];
4208 if (size != sizeof(int))
4209 return (id) [NSNull null];
4212 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4213 return (id) [NSNull null];
4215 return [NSNumber numberWithInt:value];
4218 - (NSString *) getKernelString:(NSString *)name {
4219 const char *string([name UTF8String]);
4222 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4223 return (id) [NSNull null];
4225 char value[size + 1];
4226 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4227 return (id) [NSNull null];
4229 // XXX: just in case you request something ludicrous
4232 return [NSString stringWithCString:value];
4235 - (void) addCydiaHost:(NSString *)host {
4236 [delegate_ performSelectorOnMainThread:@selector(addCydiaHost:) withObject:host waitUntilDone:NO];
4239 - (void) addTrivialSource:(NSString *)href {
4240 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4243 - (void) refreshSources {
4244 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4247 - (NSArray *) getAllSources {
4248 return [[Database sharedInstance] sources];
4251 - (NSArray *) getInstalledPackages {
4252 Database *database([Database sharedInstance]);
4253 @synchronized (database) {
4254 NSArray *packages([database packages]);
4255 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4256 for (Package *package in packages)
4257 if (![package uninstalled])
4258 [installed addObject:package];
4262 - (Package *) getPackageById:(NSString *)id {
4263 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4267 return (Package *) [NSNull null];
4270 - (NSArray *) statfs:(NSString *)path {
4273 if (path == nil || statfs([path UTF8String], &stat) == -1)
4276 return [NSArray arrayWithObjects:
4277 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4278 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4279 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4283 - (NSNumber *) du:(NSString *)path {
4284 NSNumber *value(nil);
4287 _assert(pipe(fds) != -1);
4289 pid_t pid(ExecFork());
4291 _assert(dup2(fds[1], 1) != -1);
4292 _assert(close(fds[0]) != -1);
4293 _assert(close(fds[1]) != -1);
4294 /* XXX: this should probably not use du */
4295 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4300 _assert(close(fds[1]) != -1);
4302 if (FILE *du = fdopen(fds[0], "r")) {
4304 while (fgets(line, sizeof(line), du) != NULL) {
4305 size_t length(strlen(line));
4306 while (length != 0 && line[length - 1] == '\n')
4307 line[--length] = '\0';
4308 if (char *tab = strchr(line, '\t')) {
4310 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4315 } else _assert(close(fds[0]));
4319 if (waitpid(pid, &status, 0) == -1)
4322 else _assert(false);
4328 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4331 - (void) installPackages:(NSArray *)packages {
4332 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4335 - (NSString *) substitutePackageNames:(NSString *)message {
4336 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4337 for (size_t i(0), e([words count]); i != e; ++i) {
4338 NSString *word([words objectAtIndex:i]);
4339 if (Package *package = [[Database sharedInstance] packageWithName:word])
4340 [words replaceObjectAtIndex:i withObject:[package name]];
4343 return [words componentsJoinedByString:@" "];
4346 - (void) removeButton {
4347 [indirect_ removeButton];
4350 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4351 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4354 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4355 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4358 - (void) setAllowsNavigationAction:(NSString *)value {
4359 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4362 - (void) setHidesBackButton:(NSString *)value {
4363 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4366 - (void) setHidesNavigationBar:(NSString *)value {
4367 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4370 - (void) setNavigationBarStyle:(NSString *)value {
4371 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4374 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4375 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4376 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4377 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4380 - (void) _setToken:(NSString *)token {
4384 [Metadata_ removeObjectForKey:@"Token"];
4386 [Metadata_ setObject:Token_ forKey:@"Token"];
4391 - (void) setToken:(NSString *)token {
4392 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4395 - (void) setPopupHook:(id)function {
4396 [indirect_ setPopupHook:function];
4399 - (void) scrollToBottom:(NSNumber *)animated {
4400 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4403 - (void) setViewportWidth:(float)width {
4404 [indirect_ setViewportWidthOnMainThread:width];
4407 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4408 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4409 unsigned count([arguments count]);
4411 for (unsigned i(0); i != count; ++i)
4412 values[i] = [arguments objectAtIndex:i];
4413 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4416 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4417 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4419 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4421 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4427 /* @ Loading... Indicator {{{ */
4428 @interface CYLoadingIndicator : UIView {
4429 _H<UIActivityIndicatorView> spinner_;
4431 _H<UIView> container_;
4434 @property (readonly, nonatomic) UILabel *label;
4435 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4439 @implementation CYLoadingIndicator
4441 - (id) initWithFrame:(CGRect)frame {
4442 if ((self = [super initWithFrame:frame]) != nil) {
4443 container_ = [[[UIView alloc] init] autorelease];
4444 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4446 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4447 [spinner_ startAnimating];
4448 [container_ addSubview:spinner_];
4450 label_ = [[[UILabel alloc] init] autorelease];
4451 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4452 [label_ setBackgroundColor:[UIColor clearColor]];
4453 [label_ setTextColor:[UIColor blackColor]];
4454 [label_ setShadowColor:[UIColor whiteColor]];
4455 [label_ setShadowOffset:CGSizeMake(0, 1)];
4456 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4457 [container_ addSubview:label_];
4459 CGSize viewsize = frame.size;
4460 CGSize spinnersize = [spinner_ bounds].size;
4461 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4462 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4464 CGRect containrect = {
4465 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4466 CGSizeMake(bothwidth, spinnersize.height)
4469 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4477 [container_ setFrame:containrect];
4478 [spinner_ setFrame:spinrect];
4479 [label_ setFrame:textrect];
4480 [self addSubview:container_];
4484 - (UILabel *) label {
4488 - (UIActivityIndicatorView *) activityIndicatorView {
4494 /* Emulated Loading Controller {{{ */
4495 @interface CYEmulatedLoadingController : CYViewController {
4496 _transient Database *database_;
4497 _H<CYLoadingIndicator> indicator_;
4498 _H<UITabBar> tabbar_;
4499 _H<UINavigationBar> navbar_;
4504 @implementation CYEmulatedLoadingController
4506 - (id) initWithDatabase:(Database *)database {
4507 if ((self = [super init]) != nil) {
4508 database_ = database;
4512 // XXX: factor this out somewhere
4513 - (UIColor *) groupTableViewBackgroundColor {
4514 UIDevice *device([UIDevice currentDevice]);
4515 bool iPad([device respondsToSelector:@selector(userInterfaceIdiom)] && [device userInterfaceIdiom] == UIUserInterfaceIdiomPad);
4516 return iPad ? [UIColor colorWithRed:0.821 green:0.834 blue:0.860 alpha:1] : [UIColor groupTableViewBackgroundColor];
4520 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4521 [[self view] setBackgroundColor:[self groupTableViewBackgroundColor]];
4523 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4524 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4525 [[self view] addSubview:indicator_];
4527 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4528 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4529 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4530 [[self view] addSubview:tabbar_];
4532 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4533 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4534 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4535 [[self view] addSubview:navbar_];
4538 - (void) releaseSubviews {
4547 /* Cydia Browser Controller {{{ */
4548 @interface CYBrowserController : BrowserController {
4549 CydiaObject *cydia_;
4554 @implementation CYBrowserController
4561 - (NSURL *) navigationURL {
4562 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4565 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4568 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4569 [super webView:view didClearWindowObject:window forFrame:frame];
4571 WebDataSource *source([frame dataSource]);
4572 NSURLResponse *response([source response]);
4574 NSURL *url([response URL]);
4575 //NSString *scheme([url scheme]);
4576 NSString *host([url host]);
4578 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4579 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4580 NSDictionary *headers([http allHeaderFields]);
4581 [self setHeaders:headers forHost:host];
4584 if ([CydiaHosts_ containsObject:host])
4585 [window setValue:cydia_ forKey:@"cydia"];
4588 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4589 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4591 if (System_ != NULL)
4592 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4593 if (Machine_ != NULL)
4594 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4596 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4598 [copy setValue:Role_ forHTTPHeaderField:@"X-Role"];
4603 - (void) setDelegate:(id)delegate {
4604 [super setDelegate:delegate];
4605 [cydia_ setDelegate:delegate];
4609 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4610 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4612 WebView *webview([[webview_ _documentView] webView]);
4614 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4617 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4619 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4620 if (Product_ != nil)
4621 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4623 [webview setApplicationNameForUserAgent:application];
4631 @interface NSObject (CydiaScript)
4632 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4635 @implementation NSObject (CydiaScript)
4637 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4643 @implementation NSArray (CydiaScript)
4645 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4646 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4647 for (size_t i(0), e([self count]); i != e; ++i)
4648 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4654 @implementation NSDictionary (CydiaScript)
4656 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4657 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4659 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4666 /* Confirmation Controller {{{ */
4667 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4668 if (!iterator.end())
4669 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4670 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4672 pkgCache::PkgIterator package(dep.TargetPkg());
4675 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4682 @protocol ConfirmationControllerDelegate
4683 - (void) cancelAndClear:(bool)clear;
4684 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4688 @interface ConfirmationController : CYBrowserController {
4689 _transient Database *database_;
4691 UIAlertView *essential_;
4693 NSDictionary *changes_;
4694 NSMutableArray *issues_;
4695 NSDictionary *sizes_;
4700 - (id) initWithDatabase:(Database *)database;
4704 @implementation ConfirmationController
4711 if (essential_ != nil)
4712 [essential_ release];
4719 RestartSubstrate_ = true;
4720 [delegate_ confirmWithNavigationController:[self navigationController]];
4723 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4724 NSString *context([alert context]);
4726 if ([context isEqualToString:@"remove"]) {
4727 if (button == [alert cancelButtonIndex])
4728 [self dismissModalViewControllerAnimated:YES];
4729 else if (button == [alert firstOtherButtonIndex]) {
4733 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4734 } else if ([context isEqualToString:@"unable"]) {
4735 [self dismissModalViewControllerAnimated:YES];
4736 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4738 [super alertView:alert clickedButtonAtIndex:button];
4742 - (void) _doContinue {
4743 [self dismissModalViewControllerAnimated:YES];
4744 [delegate_ cancelAndClear:NO];
4747 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4748 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4752 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4753 [super webView:view didClearWindowObject:window forFrame:frame];
4755 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4756 changes_, @"changes",
4760 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4763 - (id) initWithDatabase:(Database *)database {
4764 if ((self = [super init]) != nil) {
4765 database_ = database;
4767 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4768 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4769 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4770 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4771 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4775 pkgCacheFile &cache([database_ cache]);
4776 NSArray *packages([database_ packages]);
4777 pkgDepCache::Policy *policy([database_ policy]);
4779 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4781 for (Package *package in packages) {
4782 pkgCache::PkgIterator iterator([package iterator]);
4783 NSString *name([package id]);
4785 if ([package broken]) {
4786 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4788 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4790 reasons, @"reasons",
4793 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4797 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4798 pkgCache::DepIterator start;
4799 pkgCache::DepIterator end;
4800 dep.GlobOr(start, end); // ++dep
4802 if (!cache->IsImportantDep(end))
4804 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4807 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4809 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4810 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4811 clauses, @"clauses",
4815 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4817 pkgCache::PkgIterator target(start.TargetPkg());
4818 if (target->ProvidesList != 0)
4819 reason = @"missing";
4821 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4823 reason = @"installed";
4824 installed = [NSString stringWithUTF8String:ver.VerStr()];
4825 } else if (!cache[target].CandidateVerIter(cache).end())
4826 reason = @"uninstalled";
4827 else if (target->ProvidesList == 0)
4828 reason = @"uninstallable";
4830 reason = @"virtual";
4833 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4834 [NSString stringWithUTF8String:start.CompType()], @"operator",
4835 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4838 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4839 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4840 version, @"version",
4842 installed, @"installed",
4845 // yes, seriously. (wtf?)
4853 pkgDepCache::StateCache &state(cache[iterator]);
4855 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4857 if (state.NewInstall())
4858 [installs addObject:name];
4859 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4860 [reinstalls addObject:name];
4861 else if (state.Upgrade())
4862 [upgrades addObject:name];
4863 else if (state.Downgrade())
4864 [downgrades addObject:name];
4865 else if (!state.Delete())
4867 else if (special_r(name))
4868 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4869 [NSNull null], @"package",
4870 [NSArray arrayWithObjects:
4871 [NSDictionary dictionaryWithObjectsAndKeys:
4872 @"Conflicts", @"relationship",
4873 [NSArray arrayWithObjects:
4874 [NSDictionary dictionaryWithObjectsAndKeys:
4876 [NSNull null], @"version",
4877 @"installed", @"reason",
4884 if ([package essential])
4886 [removes addObject:name];
4889 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4890 substrate_ |= DepSubstrate(iterator.CurrentVer());
4895 else if (Advanced_) {
4896 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4898 essential_ = [[UIAlertView alloc]
4899 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4900 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4902 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4904 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4908 [essential_ setContext:@"remove"];
4910 essential_ = [[UIAlertView alloc]
4911 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4912 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4914 cancelButtonTitle:UCLocalize("OKAY")
4915 otherButtonTitles:nil
4918 [essential_ setContext:@"unable"];
4921 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4922 installs, @"installs",
4923 reinstalls, @"reinstalls",
4924 upgrades, @"upgrades",
4925 downgrades, @"downgrades",
4926 removes, @"removes",
4929 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4930 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4931 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4934 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4936 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4937 initWithTitle:UCLocalize("CANCEL")
4938 style:UIBarButtonItemStylePlain
4940 action:@selector(cancelButtonClicked)
4946 - (void) applyRightButton {
4947 if ([issues_ count] == 0 && ![self isLoading])
4948 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4949 initWithTitle:UCLocalize("CONFIRM")
4950 style:UIBarButtonItemStyleDone
4952 action:@selector(confirmButtonClicked)
4955 [[self navigationItem] setRightBarButtonItem:nil];
4959 - (void) cancelButtonClicked {
4960 [self dismissModalViewControllerAnimated:YES];
4961 [delegate_ cancelAndClear:YES];
4965 - (void) confirmButtonClicked {
4966 if (essential_ != nil)
4976 /* Progress Data {{{ */
4977 @interface CydiaProgressData : NSObject {
4978 _transient id delegate_;
4987 _H<NSMutableArray> events_;
4988 _H<NSString> title_;
4990 _H<NSString> status_;
4991 _H<NSString> finish_;
4996 @implementation CydiaProgressData
4998 + (NSArray *) _attributeKeys {
4999 return [NSArray arrayWithObjects:
5011 - (NSArray *) attributeKeys {
5012 return [[self class] _attributeKeys];
5015 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5016 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5020 if ((self = [super init]) != nil) {
5021 events_ = [NSMutableArray arrayWithCapacity:32];
5025 - (void) setDelegate:(id)delegate {
5026 delegate_ = delegate;
5029 - (void) setPercent:(float)value {
5033 - (NSNumber *) percent {
5034 return [NSNumber numberWithFloat:percent_];
5037 - (void) setCurrent:(float)value {
5041 - (NSNumber *) current {
5042 return [NSNumber numberWithFloat:current_];
5045 - (void) setTotal:(float)value {
5049 - (NSNumber *) total {
5050 return [NSNumber numberWithFloat:total_];
5053 - (void) setSpeed:(float)value {
5057 - (NSNumber *) speed {
5058 return [NSNumber numberWithFloat:speed_];
5061 - (NSArray *) events {
5065 - (void) removeAllEvents {
5066 [events_ removeAllObjects];
5069 - (void) addEvent:(CydiaProgressEvent *)event {
5070 [events_ addObject:event];
5073 - (void) setTitle:(NSString *)text {
5077 - (NSString *) title {
5081 - (void) setFinish:(NSString *)text {
5085 - (NSString *) finish {
5086 return (id) finish_ ?: [NSNull null];
5089 - (void) setRunning:(bool)running {
5093 - (NSNumber *) running {
5094 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5099 /* Progress Controller {{{ */
5100 @interface ProgressController : CYBrowserController <
5103 _transient Database *database_;
5104 _H<CydiaProgressData> progress_;
5108 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5110 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5112 - (void) setTitle:(NSString *)title;
5113 - (void) setCancellable:(bool)cancellable;
5117 @implementation ProgressController
5120 [database_ setProgressDelegate:nil];
5121 [progress_ setDelegate:nil];
5125 - (void) updateCancel {
5126 [[self navigationItem] setLeftBarButtonItem:(cancel_ == 1 ? [[[UIBarButtonItem alloc]
5127 initWithTitle:UCLocalize("CANCEL")
5128 style:UIBarButtonItemStylePlain
5130 action:@selector(cancel)
5131 ] autorelease] : nil)];
5134 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5135 if ((self = [super init]) != nil) {
5136 database_ = database;
5137 delegate_ = delegate;
5139 [database_ setProgressDelegate:self];
5141 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5142 [progress_ setDelegate:self];
5144 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5146 [scroller_ setBackgroundColor:[UIColor blackColor]];
5148 [[self navigationItem] setHidesBackButton:YES];
5150 [self updateCancel];
5154 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5155 [super webView:view didClearWindowObject:window forFrame:frame];
5156 [window setValue:progress_ forKey:@"cydiaProgress"];
5159 - (void) updateProgress {
5160 [self dispatchEvent:@"CydiaProgressUpdate"];
5163 - (void) viewWillAppear:(BOOL)animated {
5164 if (![self hasLoaded])
5165 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5167 [super viewWillAppear:animated];
5171 UpdateExternalStatus(0);
5178 [delegate_ terminateWithSuccess];
5179 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5180 [delegate_ suspendWithAnimation:YES];
5182 [delegate_ suspend];*/
5194 system("/usr/bin/sbreload");
5200 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5201 SBReboot(SBSSpringBoardServerPort());
5203 reboot2(RB_AUTOBOOT);
5210 - (void) setTitle:(NSString *)title {
5211 [progress_ setTitle:title];
5212 [self updateProgress];
5215 - (UIBarButtonItem *) rightButton {
5216 return [[progress_ running] boolValue] ? nil : [[[UIBarButtonItem alloc]
5217 initWithTitle:UCLocalize("CLOSE")
5218 style:UIBarButtonItemStylePlain
5220 action:@selector(close)
5224 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5225 UpdateExternalStatus(1);
5227 [progress_ setRunning:true];
5228 [self setTitle:title];
5229 // implicit updateProgress
5231 SHA1SumValue notifyconf; {
5233 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5236 MMap mmap(file, MMap::ReadOnly);
5238 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5239 notifyconf = sha1.Result();
5243 SHA1SumValue springlist; {
5245 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5248 MMap mmap(file, MMap::ReadOnly);
5250 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5251 springlist = sha1.Result();
5255 if (invocation != nil) {
5256 [invocation yieldToSelector:@selector(invoke)];
5257 [self setTitle:@"COMPLETE"];
5262 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5265 MMap mmap(file, MMap::ReadOnly);
5267 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5268 if (!(notifyconf == sha1.Result()))
5275 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5278 MMap mmap(file, MMap::ReadOnly);
5280 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5281 if (!(springlist == sha1.Result()))
5287 if (RestartSubstrate_)
5291 RestartSubstrate_ = false;
5294 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5295 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5296 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5297 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5298 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5302 system("su -c /usr/bin/uicache mobile");
5305 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5307 [progress_ setRunning:false];
5308 [self updateProgress];
5310 [self applyRightButton];
5313 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5314 [progress_ addEvent:event];
5315 [self updateProgress];
5318 - (bool) isProgressCancelled {
5319 return cancel_ == 2;
5324 [self updateCancel];
5327 - (void) setCancellable:(bool)cancellable {
5328 unsigned cancel(cancel_);
5332 else if (cancel_ == 0)
5335 if (cancel != cancel_)
5336 [self updateCancel];
5339 - (void) setProgressCancellable:(NSNumber *)cancellable {
5340 [self setCancellable:[cancellable boolValue]];
5343 - (void) setProgressPercent:(NSNumber *)percent {
5344 [progress_ setPercent:[percent floatValue]];
5345 [self updateProgress];
5348 - (void) setProgressStatus:(NSDictionary *)status {
5349 if (status == nil) {
5350 [progress_ setCurrent:0];
5351 [progress_ setTotal:0];
5352 [progress_ setSpeed:0];
5354 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5356 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5357 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5358 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5361 [self updateProgress];
5367 /* Cell Content View {{{ */
5368 @protocol ContentDelegate
5369 - (void) drawContentRect:(CGRect)rect;
5372 @interface ContentView : UIView {
5373 _transient id<ContentDelegate> delegate_;
5378 @implementation ContentView
5380 - (id) initWithFrame:(CGRect)frame {
5381 if ((self = [super initWithFrame:frame]) != nil) {
5382 [self setNeedsDisplayOnBoundsChange:YES];
5386 - (void) setDelegate:(id<ContentDelegate>)delegate {
5387 delegate_ = delegate;
5390 - (void) drawRect:(CGRect)rect {
5391 [super drawRect:rect];
5392 [delegate_ drawContentRect:rect];
5397 /* Cydia TableView Cell {{{ */
5398 @interface CYTableViewCell : UITableViewCell {
5399 ContentView *content_;
5405 @implementation CYTableViewCell
5412 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5413 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5415 if (view == content_) {
5416 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5417 highlighted_ = highlighted;
5420 [super _updateHighlightColorsForView:view highlighted:highlighted];
5423 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5424 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5425 highlighted_ = selected;
5427 [super setSelected:selected animated:animated];
5428 [content_ setNeedsDisplay];
5434 /* Package Cell {{{ */
5435 @interface PackageCell : CYTableViewCell <
5440 NSString *description_;
5448 - (PackageCell *) init;
5449 - (void) setPackage:(Package *)package;
5451 - (void) drawContentRect:(CGRect)rect;
5455 @implementation PackageCell
5457 - (void) clearPackage {
5468 if (description_ != nil) {
5469 [description_ release];
5473 if (source_ != nil) {
5478 if (badge_ != nil) {
5483 if (placard_ != nil) {
5493 [self clearPackage];
5497 - (PackageCell *) init {
5498 CGRect frame(CGRectMake(0, 0, 320, 74));
5499 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5500 UIView *content([self contentView]);
5501 CGRect bounds([content bounds]);
5503 content_ = [[ContentView alloc] initWithFrame:bounds];
5504 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5505 [content addSubview:content_];
5507 [content_ setDelegate:self];
5508 [content_ setOpaque:YES];
5512 - (NSString *) accessibilityLabel {
5513 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5516 - (void) setPackage:(Package *)package {
5517 [self clearPackage];
5520 Source *source = [package source];
5522 icon_ = [[package icon] retain];
5523 name_ = [[package name] retain];
5526 description_ = [package longDescription];
5527 if (description_ == nil)
5528 description_ = [package shortDescription];
5529 if (description_ != nil)
5530 description_ = [description_ retain];
5532 commercial_ = [package isCommercial];
5534 package_ = [package retain];
5536 NSString *label = nil;
5537 bool trusted = false;
5539 if (source != nil) {
5540 label = [source label];
5541 trusted = [source trusted];
5542 } else if ([[package id] isEqualToString:@"firmware"])
5543 label = UCLocalize("APPLE");
5545 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5547 NSString *from(label);
5549 NSString *section = [package simpleSection];
5550 if (section != nil && ![section isEqualToString:label]) {
5551 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5552 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5555 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5556 source_ = [from retain];
5558 if (NSString *purpose = [package primaryPurpose])
5559 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5560 badge_ = [badge_ retain];
5565 if (NSString *mode = [package_ mode]) {
5566 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5567 color = RemovingColor_;
5568 //placard = @"removing";
5570 color = InstallingColor_;
5571 //placard = @"installing";
5574 // XXX: the removing/installing placards are not @2x
5577 color = [UIColor whiteColor];
5579 if ([package installed] != nil)
5580 placard = @"installed";
5585 [content_ setBackgroundColor:color];
5588 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5589 placard_ = [placard_ retain];
5591 [self setNeedsDisplay];
5592 [content_ setNeedsDisplay];
5595 - (void) drawContentRect:(CGRect)rect {
5596 bool highlighted(highlighted_);
5597 float width([self bounds].size.width);
5600 CGContextRef context(UIGraphicsGetCurrentContext());
5601 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5602 CGContextFillRect(context, rect);
5607 rect.size = [icon_ size];
5609 rect.size.width /= 2;
5610 rect.size.height /= 2;
5612 rect.origin.x = 25 - rect.size.width / 2;
5613 rect.origin.y = 25 - rect.size.height / 2;
5615 [icon_ drawInRect:rect];
5618 if (badge_ != nil) {
5620 rect.size = [badge_ size];
5622 rect.size.width /= 2;
5623 rect.size.height /= 2;
5625 rect.origin.x = 36 - rect.size.width / 2;
5626 rect.origin.y = 36 - rect.size.height / 2;
5628 [badge_ drawInRect:rect];
5635 UISetColor(commercial_ ? Purple_ : Black_);
5636 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5637 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5640 UISetColor(commercial_ ? Purplish_ : Gray_);
5641 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5643 if (placard_ != nil)
5644 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5649 /* Section Cell {{{ */
5650 @interface SectionCell : CYTableViewCell <
5662 - (void) setSection:(Section *)section editing:(BOOL)editing;
5666 @implementation SectionCell
5668 - (void) clearSection {
5669 if (basic_ != nil) {
5674 if (section_ != nil) {
5684 if (count_ != nil) {
5691 [self clearSection];
5697 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5698 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5699 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5700 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5701 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5703 UIView *content([self contentView]);
5704 CGRect bounds([content bounds]);
5706 content_ = [[ContentView alloc] initWithFrame:bounds];
5707 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5708 [content addSubview:content_];
5709 [content_ setBackgroundColor:[UIColor whiteColor]];
5711 [content_ setDelegate:self];
5715 - (void) onSwitch:(id)sender {
5716 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5717 if (metadata == nil) {
5718 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5719 [Sections_ setObject:metadata forKey:basic_];
5722 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5726 - (void) setSection:(Section *)section editing:(BOOL)editing {
5727 if (editing != editing_) {
5729 [switch_ removeFromSuperview];
5731 [self addSubview:switch_];
5735 [self clearSection];
5737 if (section == nil) {
5738 name_ = [UCLocalize("ALL_PACKAGES") retain];
5741 basic_ = [section name];
5743 basic_ = [basic_ retain];
5745 section_ = [section localized];
5746 if (section_ != nil)
5747 section_ = [section_ retain];
5749 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5750 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5753 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5756 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5757 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5759 [content_ setNeedsDisplay];
5762 - (void) setFrame:(CGRect)frame {
5763 [super setFrame:frame];
5765 CGRect rect([switch_ frame]);
5766 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5769 - (NSString *) accessibilityLabel {
5773 - (void) drawContentRect:(CGRect)rect {
5774 bool highlighted(highlighted_ && !editing_);
5776 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5781 float width(rect.size.width);
5787 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5789 CGSize size = [count_ sizeWithFont:Font14_];
5793 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5799 /* File Table {{{ */
5800 @interface FileTable : CYViewController <
5801 UITableViewDataSource,
5804 _transient Database *database_;
5807 NSMutableArray *files_;
5811 - (id) initWithDatabase:(Database *)database;
5812 - (void) setPackage:(Package *)package;
5816 @implementation FileTable
5819 [self releaseSubviews];
5828 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5829 return files_ == nil ? 0 : [files_ count];
5832 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5836 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5837 static NSString *reuseIdentifier = @"Cell";
5839 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5841 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5842 [cell setFont:[UIFont systemFontOfSize:16]];
5844 [cell setText:[files_ objectAtIndex:indexPath.row]];
5845 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5850 - (NSURL *) navigationURL {
5851 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5855 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5857 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5858 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5859 [list_ setRowHeight:24.0f];
5860 [list_ setDataSource:self];
5861 [list_ setDelegate:self];
5862 [[self view] addSubview:list_];
5865 - (void) viewDidLoad {
5866 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5869 - (void) releaseSubviews {
5874 - (id) initWithDatabase:(Database *)database {
5875 if ((self = [super init]) != nil) {
5876 database_ = database;
5878 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5882 - (void) setPackage:(Package *)package {
5883 if (package_ != nil) {
5884 [package_ autorelease];
5893 [files_ removeAllObjects];
5895 if (package != nil) {
5896 package_ = [package retain];
5897 name_ = [[package id] retain];
5899 if (NSArray *files = [package files])
5900 [files_ addObjectsFromArray:files];
5902 if ([files_ count] != 0) {
5903 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5904 [files_ removeObjectAtIndex:0];
5905 [files_ sortUsingSelector:@selector(compareByPath:)];
5907 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5908 [stack addObject:@"/"];
5910 for (int i(0), e([files_ count]); i != e; ++i) {
5911 NSString *file = [files_ objectAtIndex:i];
5912 while (![file hasPrefix:[stack lastObject]])
5913 [stack removeLastObject];
5914 NSString *directory = [stack lastObject];
5915 [stack addObject:[file stringByAppendingString:@"/"]];
5916 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5917 ([stack count] - 2) * 3, "",
5918 [file substringFromIndex:[directory length]]
5927 - (void) reloadData {
5930 [self setPackage:[database_ packageWithName:name_]];
5935 /* Package Controller {{{ */
5936 @interface CYPackageController : CYBrowserController <
5937 UIActionSheetDelegate
5939 _transient Database *database_;
5940 _H<Package> package_;
5943 _H<NSMutableArray> buttons_;
5944 _H<UIBarButtonItem> button_;
5947 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5951 @implementation CYPackageController
5953 - (NSURL *) navigationURL {
5954 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5957 /* XXX: this is not safe at all... localization of /fail/ */
5958 - (void) _clickButtonWithName:(NSString *)name {
5959 if ([name isEqualToString:UCLocalize("CLEAR")])
5960 [delegate_ clearPackage:package_];
5961 else if ([name isEqualToString:UCLocalize("INSTALL")])
5962 [delegate_ installPackage:package_];
5963 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5964 [delegate_ installPackage:package_];
5965 else if ([name isEqualToString:UCLocalize("REMOVE")])
5966 [delegate_ removePackage:package_];
5967 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5968 [delegate_ installPackage:package_];
5969 else _assert(false);
5972 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5973 NSString *context([sheet context]);
5975 if ([context isEqualToString:@"modify"]) {
5976 if (button != [sheet cancelButtonIndex]) {
5977 NSString *buttonName = [buttons_ objectAtIndex:button];
5978 [self _clickButtonWithName:buttonName];
5981 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5985 - (bool) _allowJavaScriptPanel {
5990 - (void) _customButtonClicked {
5991 int count([buttons_ count]);
5996 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5998 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5999 [buttons addObjectsFromArray:buttons_];
6001 UIActionSheet *sheet = [[[UIActionSheet alloc]
6004 cancelButtonTitle:nil
6005 destructiveButtonTitle:nil
6006 otherButtonTitles:nil
6009 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6011 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6012 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6014 [sheet setContext:@"modify"];
6016 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6020 // We don't want to allow non-commercial packages to do custom things to the install button,
6021 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6022 - (void) customButtonClicked {
6024 [super customButtonClicked];
6026 [self _customButtonClicked];
6029 - (void) reloadButtonClicked {
6030 // Don't reload a commerical package by tapping the loading button,
6031 // but if it's not an Install button, we should forward it on.
6032 if (![package_ uninstalled])
6033 [self _customButtonClicked];
6036 - (void) applyLoadingTitle {
6037 // Don't show "Loading" as the title. Ever.
6040 - (UIBarButtonItem *) rightButton {
6045 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
6046 if ((self = [super init]) != nil) {
6047 database_ = database;
6048 buttons_ = [NSMutableArray arrayWithCapacity:4];
6049 name_ = [NSString stringWithString:name];
6050 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
6054 - (void) reloadData {
6055 package_ = [database_ packageWithName:name_];
6057 [buttons_ removeAllObjects];
6059 if (package_ != nil) {
6060 [(Package *) package_ parse];
6062 commercial_ = [package_ isCommercial];
6064 if ([package_ mode] != nil)
6065 [buttons_ addObject:UCLocalize("CLEAR")];
6066 if ([package_ source] == nil);
6067 else if ([package_ upgradableAndEssential:NO])
6068 [buttons_ addObject:UCLocalize("UPGRADE")];
6069 else if ([package_ uninstalled])
6070 [buttons_ addObject:UCLocalize("INSTALL")];
6072 [buttons_ addObject:UCLocalize("REINSTALL")];
6073 if (![package_ uninstalled])
6074 [buttons_ addObject:UCLocalize("REMOVE")];
6078 switch ([buttons_ count]) {
6079 case 0: title = nil; break;
6080 case 1: title = [buttons_ objectAtIndex:0]; break;
6081 default: title = UCLocalize("MODIFY"); break;
6084 button_ = [[[UIBarButtonItem alloc]
6086 style:UIBarButtonItemStylePlain
6088 action:@selector(customButtonClicked)
6094 - (bool) isLoading {
6095 return commercial_ ? [super isLoading] : false;
6101 /* Package List Controller {{{ */
6102 @interface PackageListController : CYViewController <
6103 UITableViewDataSource,
6106 _transient Database *database_;
6108 NSMutableArray *packages_;
6109 NSMutableArray *sections_;
6111 NSMutableArray *index_;
6112 NSMutableDictionary *indices_;
6116 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6117 - (void) setDelegate:(id)delegate;
6118 - (void) resetCursor;
6122 @implementation PackageListController
6125 [packages_ release];
6126 [sections_ release];
6135 - (void) deselectWithAnimation:(BOOL)animated {
6136 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6139 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6140 CGRect base = [[self view] bounds];
6141 base.size.height -= bounds.size.height;
6142 base.origin = [list_ frame].origin;
6144 [UIView beginAnimations:nil context:NULL];
6145 [UIView setAnimationBeginsFromCurrentState:YES];
6146 [UIView setAnimationCurve:curve];
6147 [UIView setAnimationDuration:duration];
6148 [list_ setFrame:base];
6149 [UIView commitAnimations];
6152 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6153 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6156 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6157 [self resizeForKeyboardBounds:bounds duration:0];
6160 - (void) keyboardWillShow:(NSNotification *)notification {
6163 NSTimeInterval duration;
6164 UIViewAnimationCurve curve;
6165 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6166 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6167 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6168 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6170 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);
6171 UIViewController *base = self;
6172 while ([base parentViewController] != nil)
6173 base = [base parentViewController];
6174 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6175 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6177 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6180 - (void) keyboardWillHide:(NSNotification *)notification {
6181 NSTimeInterval duration;
6182 UIViewAnimationCurve curve;
6183 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6184 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6186 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6189 - (void) viewWillAppear:(BOOL)animated {
6190 [super viewWillAppear:animated];
6192 [self resizeForKeyboardBounds:CGRectZero];
6193 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6194 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6197 - (void) viewWillDisappear:(BOOL)animated {
6198 [super viewWillDisappear:animated];
6200 [self resizeForKeyboardBounds:CGRectZero];
6201 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6202 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6205 - (void) viewDidAppear:(BOOL)animated {
6206 [super viewDidAppear:animated];
6207 [self deselectWithAnimation:animated];
6210 - (void) didSelectPackage:(Package *)package {
6211 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6212 [view setDelegate:delegate_];
6213 [[self navigationController] pushViewController:view animated:YES];
6216 #if TryIndexedCollation
6217 + (BOOL) hasIndexedCollation {
6218 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6222 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6223 NSInteger count([sections_ count]);
6224 return count == 0 ? 1 : count;
6227 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6228 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6230 return [[sections_ objectAtIndex:section] name];
6233 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6234 if ([sections_ count] == 0)
6236 return [[sections_ objectAtIndex:section] count];
6239 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6240 @synchronized (database_) {
6241 if ([database_ era] != era_)
6244 Section *section([sections_ objectAtIndex:[path section]]);
6245 NSInteger row([path row]);
6246 Package *package([packages_ objectAtIndex:([section row] + row)]);
6247 return [[package retain] autorelease];
6250 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6251 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6253 cell = [[[PackageCell alloc] init] autorelease];
6254 [cell setPackage:[self packageAtIndexPath:path]];
6258 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6259 Package *package([self packageAtIndexPath:path]);
6260 package = [database_ packageWithName:[package id]];
6261 [self didSelectPackage:package];
6264 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6265 // XXX: is 20 the most optimal number here?
6266 return [packages_ count] > 20 ? index_ : nil;
6269 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6270 #if TryIndexedCollation
6271 if ([[self class] hasIndexedCollation]) {
6272 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6279 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6280 if ((self = [super init]) != nil) {
6281 database_ = database;
6282 title_ = [title copy];
6283 [[self navigationItem] setTitle:title_];
6285 #if TryIndexedCollation
6286 if ([[self class] hasIndexedCollation])
6287 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6290 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6292 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6294 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6295 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6297 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6298 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6299 [list_ setRowHeight:73];
6300 [[self view] addSubview:list_];
6302 [list_ setDataSource:self];
6303 [list_ setDelegate:self];
6307 - (void) setDelegate:(id)delegate {
6308 delegate_ = delegate;
6311 - (bool) hasPackage:(Package *)package {
6315 - (void) reloadData {
6318 era_ = [database_ era];
6319 NSArray *packages = [database_ packages];
6321 [packages_ removeAllObjects];
6322 [sections_ removeAllObjects];
6324 _profile(PackageTable$reloadData$Filter)
6325 for (Package *package in packages)
6326 if ([self hasPackage:package])
6327 [packages_ addObject:package];
6330 [indices_ removeAllObjects];
6332 Section *section = nil;
6334 #if TryIndexedCollation
6335 if ([[self class] hasIndexedCollation]) {
6336 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6337 NSArray *titles = [collation sectionIndexTitles];
6340 _profile(PackageTable$reloadData$Section)
6341 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6345 _profile(PackageTable$reloadData$Section$Package)
6346 package = [packages_ objectAtIndex:offset];
6347 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6350 while (secidx < index) {
6353 _profile(PackageTable$reloadData$Section$Allocate)
6354 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6357 _profile(PackageTable$reloadData$Section$Add)
6358 [sections_ addObject:section];
6362 [section addToCount];
6368 [index_ removeAllObjects];
6370 _profile(PackageTable$reloadData$Section)
6371 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6375 _profile(PackageTable$reloadData$Section$Package)
6376 package = [packages_ objectAtIndex:offset];
6377 index = [package index];
6380 if (section == nil || [section index] != index) {
6381 _profile(PackageTable$reloadData$Section$Allocate)
6382 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6385 [index_ addObject:[section name]];
6386 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6388 _profile(PackageTable$reloadData$Section$Add)
6389 [sections_ addObject:section];
6393 [section addToCount];
6398 _profile(PackageTable$reloadData$List)
6403 - (void) resetCursor {
6404 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6409 /* Filtered Package List Controller {{{ */
6410 @interface FilteredPackageListController : PackageListController {
6416 - (void) setObject:(id)object;
6417 - (void) setObject:(id)object forFilter:(SEL)filter;
6419 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6423 @implementation FilteredPackageListController
6431 - (void) setFilter:(SEL)filter {
6434 /* XXX: this is an unsafe optimization of doomy hell */
6435 Method method(class_getInstanceMethod([Package class], filter));
6436 _assert(method != NULL);
6437 imp_ = method_getImplementation(method);
6438 _assert(imp_ != NULL);
6441 - (void) setObject:(id)object {
6447 object_ = [object retain];
6450 - (void) setObject:(id)object forFilter:(SEL)filter {
6451 [self setFilter:filter];
6452 [self setObject:object];
6455 - (bool) hasPackage:(Package *)package {
6456 _profile(FilteredPackageTable$hasPackage)
6457 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6461 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6462 if ((self = [super initWithDatabase:database title:title]) != nil) {
6463 [self setFilter:filter];
6464 [self setObject:object];
6471 /* Home Controller {{{ */
6472 @interface HomeController : CYBrowserController {
6477 @implementation HomeController
6480 if ((self = [super init]) != nil) {
6481 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6485 - (NSURL *) navigationURL {
6486 return [NSURL URLWithString:@"cydia://home"];
6489 - (void) aboutButtonClicked {
6490 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6492 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6493 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6494 [alert setCancelButtonIndex:0];
6497 @"Copyright (C) 2008-2011\n"
6498 "Jay Freeman (saurik)\n"
6499 "saurik@saurik.com\n"
6500 "http://www.saurik.com/"
6506 - (void) viewDidLoad {
6507 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6508 initWithTitle:UCLocalize("ABOUT")
6509 style:UIBarButtonItemStylePlain
6511 action:@selector(aboutButtonClicked)
6517 /* Manage Controller {{{ */
6518 @interface ManageController : CYBrowserController {
6521 - (void) queueStatusDidChange;
6525 @implementation ManageController
6528 if ((self = [super init]) != nil) {
6529 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6533 - (NSURL *) navigationURL {
6534 return [NSURL URLWithString:@"cydia://manage"];
6537 - (void) viewDidLoad {
6538 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6539 initWithTitle:UCLocalize("SETTINGS")
6540 style:UIBarButtonItemStylePlain
6542 action:@selector(settingsButtonClicked)
6545 [self queueStatusDidChange];
6548 - (void) settingsButtonClicked {
6549 [delegate_ showSettings];
6553 - (void) queueButtonClicked {
6557 - (void) applyLoadingTitle {
6558 // Disable "Loading" title.
6561 - (void) applyRightButton {
6562 // Disable right button.
6566 - (void) queueStatusDidChange {
6568 if (!IsWildcat_ && Queuing_) {
6569 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6570 initWithTitle:UCLocalize("QUEUE")
6571 style:UIBarButtonItemStyleDone
6573 action:@selector(queueButtonClicked)
6576 [[self navigationItem] setRightBarButtonItem:nil];
6581 - (bool) isLoading {
6582 // Never show as loading.
6589 /* Refresh Bar {{{ */
6590 @interface RefreshBar : UINavigationBar {
6591 UIProgressIndicator *indicator_;
6592 UITextLabel *prompt_;
6593 UIProgressBar *progress_;
6594 UINavigationButton *cancel_;
6599 @implementation RefreshBar
6602 [indicator_ release];
6604 [progress_ release];
6609 - (void) positionViews {
6610 CGRect frame = [cancel_ frame];
6611 frame.size = [cancel_ sizeThatFits:frame.size];
6612 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6613 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6614 [cancel_ setFrame:frame];
6616 CGSize prgsize = {75, 100};
6618 [self frame].size.width - prgsize.width - 10,
6619 ([self frame].size.height - prgsize.height) / 2
6621 [progress_ setFrame:prgrect];
6623 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6624 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6625 CGRect indrect = {{indoffset, indoffset}, indsize};
6626 [indicator_ setFrame:indrect];
6628 CGSize prmsize = {215, indsize.height + 4};
6630 indoffset * 2 + indsize.width,
6631 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6633 [prompt_ setFrame:prmrect];
6636 - (void) setFrame:(CGRect)frame {
6637 [super setFrame:frame];
6638 [self positionViews];
6641 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6642 if ((self = [super initWithFrame:frame]) != nil) {
6643 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6645 [self setBarStyle:UIBarStyleBlack];
6647 UIBarStyle barstyle([self _barStyle:NO]);
6648 bool ugly(barstyle == UIBarStyleDefault);
6650 UIProgressIndicatorStyle style = ugly ?
6651 UIProgressIndicatorStyleMediumBrown :
6652 UIProgressIndicatorStyleMediumWhite;
6654 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6655 [indicator_ setStyle:style];
6656 [indicator_ startAnimation];
6657 [self addSubview:indicator_];
6659 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6660 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6661 [prompt_ setBackgroundColor:[UIColor clearColor]];
6662 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6663 [self addSubview:prompt_];
6665 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6666 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6667 [progress_ setStyle:0];
6668 [self addSubview:progress_];
6670 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6671 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6672 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6673 [cancel_ setBarStyle:barstyle];
6675 [self positionViews];
6679 - (void) setCancellable:(bool)cancellable {
6681 [self addSubview:cancel_];
6683 [cancel_ removeFromSuperview];
6687 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6688 [progress_ setProgress:0];
6692 [self setCancellable:NO];
6695 - (void) setPrompt:(NSString *)prompt {
6696 [prompt_ setText:prompt];
6699 - (void) setProgress:(float)progress {
6700 [progress_ setProgress:progress];
6706 @class CYNavigationController;
6708 /* Cydia Tab Bar Controller {{{ */
6709 @interface CYTabBarController : UITabBarController <
6710 UITabBarControllerDelegate,
6713 _transient Database *database_;
6714 RefreshBar *refreshbar_;
6718 // XXX: ok, "updatedelegate_"?...
6719 _transient NSObject<CydiaDelegate> *updatedelegate_;
6722 UIViewController *remembered_;
6723 _transient UIViewController *transient_;
6726 - (NSArray *) navigationURLCollection;
6727 - (void) dropBar:(BOOL)animated;
6728 - (void) beginUpdate;
6729 - (void) raiseBar:(BOOL)animated;
6734 @implementation CYTabBarController
6736 - (void) setUnselectedViewController:(UIViewController *)transient {
6737 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6738 if (transient != nil) {
6739 if (transient_ == nil)
6740 remembered_ = [[controllers objectAtIndex:0] retain];
6741 transient_ = transient;
6742 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6743 [controllers replaceObjectAtIndex:0 withObject:transient_];
6744 [self setSelectedIndex:0];
6745 [self setViewControllers:controllers];
6746 [self concealTabBarSelection];
6747 } else if (remembered_ != nil) {
6748 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6749 transient_ = transient;
6750 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6751 [remembered_ release];
6753 [self setViewControllers:controllers];
6754 [self revealTabBarSelection];
6758 - (UIViewController *) unselectedViewController {
6762 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6763 if ([self unselectedViewController])
6764 [self setUnselectedViewController:nil];
6767 - (NSArray *) navigationURLCollection {
6768 NSMutableArray *items([NSMutableArray array]);
6770 // XXX: Should this deal with transient view controllers?
6771 for (id navigation in [self viewControllers]) {
6772 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6774 [items addObject:stack];
6780 - (void) reloadData {
6781 for (CYViewController *controller in [self viewControllers])
6782 [controller reloadData];
6784 [(CYNavigationController *)[self unselectedViewController] reloadData];
6788 [refreshbar_ release];
6789 [[NSNotificationCenter defaultCenter] removeObserver:self];
6794 - (id) initWithDatabase:(Database *)database {
6795 if ((self = [super init]) != nil) {
6796 database_ = database;
6797 [self setDelegate:self];
6799 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6800 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6802 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6806 - (void) setUpdate:(NSDate *)date {
6810 - (void) beginUpdate {
6811 [refreshbar_ start];
6814 [updatedelegate_ retainNetworkActivityIndicator];
6818 detachNewThreadSelector:@selector(performUpdate)
6824 - (void) performUpdate { _pooled
6826 status.setDelegate(self);
6827 [database_ updateWithStatus:status];
6830 performSelectorOnMainThread:@selector(completeUpdate)
6836 - (void) stopUpdateWithSelector:(SEL)selector {
6838 [updatedelegate_ releaseNetworkActivityIndicator];
6840 [self raiseBar:YES];
6843 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6846 - (void) completeUpdate {
6849 [self stopUpdateWithSelector:@selector(reloadData)];
6852 - (void) cancelUpdate {
6853 [self stopUpdateWithSelector:@selector(updateData)];
6856 - (void) cancelPressed {
6857 [self cancelUpdate];
6864 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6865 [refreshbar_ setPrompt:[event compoundMessage]];
6868 - (bool) isProgressCancelled {
6872 - (void) setProgressCancellable:(NSNumber *)cancellable {
6873 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6876 - (void) setProgressPercent:(NSNumber *)percent {
6877 [refreshbar_ setProgress:[percent floatValue]];
6880 - (void) setProgressStatus:(NSDictionary *)status {
6882 [self setProgressPercent:[status objectForKey:@"Percent"]];
6885 - (void) setUpdateDelegate:(id)delegate {
6886 updatedelegate_ = delegate;
6889 - (CGFloat) statusBarHeight {
6890 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6891 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6893 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6897 - (UIView *) transitionView {
6898 if ([self respondsToSelector:@selector(_transitionView)])
6899 return [self _transitionView];
6901 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6904 - (void) dropBar:(BOOL)animated {
6909 UIView *transition([self transitionView]);
6910 [[self view] addSubview:refreshbar_];
6912 CGRect barframe([refreshbar_ frame]);
6914 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6915 barframe.origin.y = [self statusBarHeight];
6917 barframe.origin.y = 0;
6919 [refreshbar_ setFrame:barframe];
6922 [UIView beginAnimations:nil context:NULL];
6924 CGRect viewframe = [transition frame];
6925 viewframe.origin.y += barframe.size.height;
6926 viewframe.size.height -= barframe.size.height;
6927 [transition setFrame:viewframe];
6930 [UIView commitAnimations];
6932 // Ensure bar has the proper width for our view, it might have changed
6933 barframe.size.width = viewframe.size.width;
6934 [refreshbar_ setFrame:barframe];
6936 // XXX: fix Apple's layout bug
6937 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6940 - (void) raiseBar:(BOOL)animated {
6945 UIView *transition([self transitionView]);
6946 [refreshbar_ removeFromSuperview];
6948 CGRect barframe([refreshbar_ frame]);
6951 [UIView beginAnimations:nil context:NULL];
6953 CGRect viewframe = [transition frame];
6954 viewframe.origin.y -= barframe.size.height;
6955 viewframe.size.height += barframe.size.height;
6956 [transition setFrame:viewframe];
6959 [UIView commitAnimations];
6961 // XXX: fix Apple's layout bug
6962 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6966 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6967 // XXX: fix Apple's layout bug
6968 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6972 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6973 bool dropped(dropped_);
6978 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6983 // XXX: fix Apple's layout bug
6984 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6987 - (void) statusBarFrameChanged:(NSNotification *)notification {
6996 /* Cydia Navigation Controller {{{ */
6997 @interface CYNavigationController : UINavigationController {
6998 _transient Database *database_;
6999 _transient id<UINavigationControllerDelegate> delegate_;
7002 - (NSArray *) navigationURLCollection;
7003 - (id) initWithDatabase:(Database *)database;
7004 - (void) reloadData;
7009 @implementation CYNavigationController
7011 - (NSArray *) navigationURLCollection {
7012 NSMutableArray *stack([NSMutableArray array]);
7014 for (CYViewController *controller in [self viewControllers]) {
7015 NSString *url = [[controller navigationURL] absoluteString];
7017 [stack addObject:url];
7023 - (void) reloadData {
7024 for (CYViewController *page in [self viewControllers]) {
7025 // Only reload controllers that have already loaded.
7026 // This prevents a page from accidentally loading too
7027 // early if it hasn't been shown on the screen yet.
7028 if ([page hasLoaded])
7033 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
7034 delegate_ = delegate;
7037 - (id) initWithDatabase:(Database *)database {
7038 if ((self = [super init]) != nil) {
7039 database_ = database;
7046 /* Cydia:// Protocol {{{ */
7047 @interface CydiaURLProtocol : NSURLProtocol {
7052 @implementation CydiaURLProtocol
7054 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7055 NSURL *url([request URL]);
7059 NSString *scheme([[url scheme] lowercaseString]);
7060 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7062 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7068 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7072 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7073 id<NSURLProtocolClient> client([self client]);
7075 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7077 NSData *data(UIImagePNGRepresentation(icon));
7079 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7080 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7081 [client URLProtocol:self didLoadData:data];
7082 [client URLProtocolDidFinishLoading:self];
7086 - (void) startLoading {
7087 id<NSURLProtocolClient> client([self client]);
7088 NSURLRequest *request([self request]);
7090 NSURL *url([request URL]);
7091 NSString *href([url absoluteString]);
7092 NSString *scheme([[url scheme] lowercaseString]);
7096 if ([scheme isEqualToString:@"cydia"])
7097 path = [href substringFromIndex:8];
7098 else if ([scheme isEqualToString:@"about"])
7099 path = [href substringFromIndex:12];
7100 else _assert(false);
7102 NSRange slash([path rangeOfString:@"/"]);
7105 if (slash.location == NSNotFound) {
7109 command = [path substringToIndex:slash.location];
7110 path = [path substringFromIndex:(slash.location + 1)];
7113 Database *database([Database sharedInstance]);
7115 if ([command isEqualToString:@"package-icon"]) {
7118 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7119 Package *package([database packageWithName:path]);
7122 UIImage *icon([package icon]);
7123 [self _returnPNGWithImage:icon forRequest:request];
7124 } else if ([command isEqualToString:@"source-icon"]) {
7127 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7128 NSString *source(Simplify(path));
7129 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7131 icon = [UIImage applicationImageNamed:@"unknown.png"];
7132 [self _returnPNGWithImage:icon forRequest:request];
7133 } else if ([command isEqualToString:@"uikit-image"]) {
7136 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7137 UIImage *icon(_UIImageWithName(path));
7138 [self _returnPNGWithImage:icon forRequest:request];
7139 } else if ([command isEqualToString:@"section-icon"]) {
7142 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7143 NSString *section(Simplify(path));
7144 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7146 icon = [UIImage applicationImageNamed:@"unknown.png"];
7147 [self _returnPNGWithImage:icon forRequest:request];
7149 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7153 - (void) stopLoading {
7159 /* Section Controller {{{ */
7160 @interface SectionController : FilteredPackageListController {
7161 _H<NSString> section_;
7164 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7168 @implementation SectionController
7170 - (NSURL *) navigationURL {
7171 NSString *name = section_;
7175 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7178 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7181 title = UCLocalize("ALL_PACKAGES");
7182 else if (![name isEqual:@""])
7183 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7185 title = UCLocalize("NO_SECTION");
7187 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7194 /* Sections Controller {{{ */
7195 @interface SectionsController : CYViewController <
7196 UITableViewDataSource,
7199 _transient Database *database_;
7200 NSMutableArray *sections_;
7201 NSMutableArray *filtered_;
7206 - (id) initWithDatabase:(Database *)database;
7207 - (void) editButtonClicked;
7211 @implementation SectionsController
7214 [self releaseSubviews];
7215 [sections_ release];
7216 [filtered_ release];
7221 - (NSURL *) navigationURL {
7222 return [NSURL URLWithString:@"cydia://sections"];
7225 - (void) updateNavigationItem {
7226 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7227 if ([sections_ count] == 0) {
7228 [[self navigationItem] setRightBarButtonItem:nil];
7230 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7231 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7233 action:@selector(editButtonClicked)
7234 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7238 - (BOOL) isEditing {
7242 - (void) setEditing:(BOOL)editing {
7243 if ((editing_ = editing))
7246 [delegate_ updateData];
7248 [self updateNavigationItem];
7251 - (void) viewDidAppear:(BOOL)animated {
7252 [super viewDidAppear:animated];
7253 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7256 - (void) viewWillDisappear:(BOOL)animated {
7257 [super viewWillDisappear:animated];
7258 if (editing_) [self setEditing:NO];
7261 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7262 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7266 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7267 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7270 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7274 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7275 static NSString *reuseIdentifier = @"SectionCell";
7277 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7279 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7281 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7286 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7290 Section *section = [self sectionAtIndexPath:indexPath];
7292 SectionController *controller = [[[SectionController alloc]
7293 initWithDatabase:database_
7294 section:[section name]
7296 [controller setDelegate:delegate_];
7298 [[self navigationController] pushViewController:controller animated:YES];
7302 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7304 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7305 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7306 [list_ setRowHeight:45.0f];
7307 [list_ setDataSource:self];
7308 [list_ setDelegate:self];
7309 [[self view] addSubview:list_];
7312 - (void) viewDidLoad {
7313 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7316 - (void) releaseSubviews {
7321 - (id) initWithDatabase:(Database *)database {
7322 if ((self = [super init]) != nil) {
7323 database_ = database;
7325 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7326 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7330 - (void) reloadData {
7333 NSArray *packages = [database_ packages];
7335 [sections_ removeAllObjects];
7336 [filtered_ removeAllObjects];
7338 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7341 for (Package *package in packages) {
7342 NSString *name([package section]);
7343 NSString *key(name == nil ? @"" : name);
7347 _profile(SectionsView$reloadData$Section)
7348 section = [sections objectForKey:key];
7349 if (section == nil) {
7350 _profile(SectionsView$reloadData$Section$Allocate)
7351 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7352 [sections setObject:section forKey:key];
7357 [section addToCount];
7359 _profile(SectionsView$reloadData$Filter)
7360 if (![package valid] || ![package visible])
7368 [sections_ addObjectsFromArray:[sections allValues]];
7370 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7372 for (Section *section in sections_) {
7373 size_t count([section row]);
7377 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7378 [section setCount:count];
7379 [filtered_ addObject:section];
7382 [self updateNavigationItem];
7387 - (void) editButtonClicked {
7388 [self setEditing:(!editing_)];
7394 /* Changes Controller {{{ */
7395 @interface ChangesController : CYViewController <
7396 UITableViewDataSource,
7399 _transient Database *database_;
7401 CFMutableArrayRef packages_;
7402 NSMutableArray *sections_;
7405 BOOL hasSentFirstLoad_;
7408 - (id) initWithDatabase:(Database *)database;
7412 @implementation ChangesController
7415 [self releaseSubviews];
7416 CFRelease(packages_);
7417 [sections_ release];
7422 - (NSURL *) navigationURL {
7423 return [NSURL URLWithString:@"cydia://changes"];
7426 - (void) viewWillAppear:(BOOL)animated {
7427 // Loads after it appears, so don't load beforehand.
7429 [super viewWillAppear:animated];
7432 - (void) viewDidAppear:(BOOL)animated {
7433 [super viewDidAppear:animated];
7435 if (!hasSentFirstLoad_) {
7436 hasSentFirstLoad_ = YES;
7437 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7439 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7443 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7444 NSInteger count([sections_ count]);
7445 return count == 0 ? 1 : count;
7448 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7449 if ([sections_ count] == 0)
7451 return [[sections_ objectAtIndex:section] name];
7454 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7455 if ([sections_ count] == 0)
7457 return [[sections_ objectAtIndex:section] count];
7460 - (Package *) packageAtIndex:(NSUInteger)index {
7461 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7464 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7465 @synchronized (database_) {
7466 if ([database_ era] != era_)
7469 NSUInteger sectionIndex([path section]);
7470 if (sectionIndex >= [sections_ count])
7472 Section *section([sections_ objectAtIndex:sectionIndex]);
7473 NSInteger row([path row]);
7474 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7477 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7478 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7480 cell = [[[PackageCell alloc] init] autorelease];
7481 [cell setPackage:[self packageAtIndexPath:path]];
7485 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7486 Package *package([self packageAtIndexPath:path]);
7487 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7488 [view setDelegate:delegate_];
7489 [[self navigationController] pushViewController:view animated:YES];
7493 - (void) refreshButtonClicked {
7494 [delegate_ beginUpdate];
7495 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7498 - (void) upgradeButtonClicked {
7499 [delegate_ distUpgrade];
7503 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7505 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7506 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7507 [list_ setRowHeight:73];
7508 [list_ setDataSource:self];
7509 [list_ setDelegate:self];
7510 [[self view] addSubview:list_];
7513 - (void) viewDidLoad {
7514 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7517 - (void) releaseSubviews {
7522 - (id) initWithDatabase:(Database *)database {
7523 if ((self = [super init]) != nil) {
7524 database_ = database;
7526 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7527 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7531 // this mostly works because reloadData (below) is @synchronized (database_)
7532 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7533 - (void) _reloadPackages:(NSArray *)packages {
7534 CFRelease(packages_);
7535 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7538 _profile(ChangesController$_reloadPackages$Filter)
7539 for (Package *package in packages)
7540 if ([package upgradableAndEssential:YES] || [package visible])
7541 CFArrayAppendValue(packages_, package);
7544 _profile(ChangesController$_reloadPackages$radixSort)
7545 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7550 - (void) reloadData {
7551 @synchronized (database_) {
7552 era_ = [database_ era];
7553 NSArray *packages = [database_ packages];
7555 [sections_ removeAllObjects];
7558 UIProgressHUD *hud([delegate_ addProgressHUD]);
7559 [hud setText:UCLocalize("LOADING")];
7560 //NSLog(@"HUD:%@::%@", delegate_, hud);
7561 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7562 [delegate_ removeProgressHUD:hud];
7564 [self _reloadPackages:packages];
7567 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7568 Section *ignored = nil;
7569 Section *section = nil;
7573 bool unseens = false;
7575 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7577 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7578 Package *package = [self packageAtIndex:offset];
7580 BOOL uae = [package upgradableAndEssential:YES];
7584 time_t seen([package seen]);
7586 if (section == nil || last != seen) {
7590 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7593 _profile(ChangesController$reloadData$Allocate)
7594 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7595 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7596 [sections_ addObject:section];
7600 [section addToCount];
7601 } else if ([package ignored]) {
7602 if (ignored == nil) {
7603 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7605 [ignored addToCount];
7608 [upgradable addToCount];
7613 CFRelease(formatter);
7616 Section *last = [sections_ lastObject];
7617 size_t count = [last count];
7618 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7619 [sections_ removeLastObject];
7622 if ([ignored count] != 0)
7623 [sections_ insertObject:ignored atIndex:0];
7625 [sections_ insertObject:upgradable atIndex:0];
7630 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7631 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7632 style:UIBarButtonItemStylePlain
7634 action:@selector(upgradeButtonClicked)
7637 if (![delegate_ updating])
7638 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7639 initWithTitle:UCLocalize("REFRESH")
7640 style:UIBarButtonItemStylePlain
7642 action:@selector(refreshButtonClicked)
7650 /* Search Controller {{{ */
7651 @interface SearchController : FilteredPackageListController <
7654 _H<UISearchBar> search_;
7658 - (id) initWithDatabase:(Database *)database;
7659 - (void) setSearchTerm:(NSString *)term;
7660 - (void) reloadData;
7664 @implementation SearchController
7667 [search_ setDelegate:nil];
7671 - (NSURL *) navigationURL {
7672 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7673 return [NSURL URLWithString:@"cydia://search"];
7675 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7678 - (void) setSearchTerm:(NSString *)searchTerm {
7679 [search_ setText:searchTerm];
7683 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7684 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7685 [search_ resignFirstResponder];
7689 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7690 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7694 - (id) initWithDatabase:(Database *)database {
7695 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7696 search_ = [[[UISearchBar alloc] init] autorelease];
7697 [search_ setDelegate:self];
7701 - (void) viewDidAppear:(BOOL)animated {
7702 [super viewDidAppear:animated];
7704 if (!searchloaded_) {
7705 searchloaded_ = YES;
7706 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7707 [search_ layoutSubviews];
7708 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7710 UITextField *textField;
7711 if ([search_ respondsToSelector:@selector(searchField)])
7712 textField = [search_ searchField];
7714 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7716 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7717 [textField setEnablesReturnKeyAutomatically:NO];
7718 [[self navigationItem] setTitleView:textField];
7722 - (void) reloadData {
7723 [self setObject:[search_ text]];
7728 - (void) didSelectPackage:(Package *)package {
7729 [search_ resignFirstResponder];
7730 [super didSelectPackage:package];
7735 /* Package Settings Controller {{{ */
7736 @interface PackageSettingsController : CYViewController <
7737 UITableViewDataSource,
7740 _transient Database *database_;
7743 UITableView *table_;
7744 UISwitch *subscribedSwitch_;
7745 UISwitch *ignoredSwitch_;
7746 UITableViewCell *subscribedCell_;
7747 UITableViewCell *ignoredCell_;
7750 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7754 @implementation PackageSettingsController
7757 [self releaseSubviews];
7764 - (NSURL *) navigationURL {
7765 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7768 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7769 if (package_ == nil)
7772 if ([package_ installed] == nil)
7778 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7779 if (package_ == nil)
7782 // both sections contain just one item right now.
7786 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7790 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7792 return UCLocalize("SHOW_ALL_CHANGES_EX");
7794 return UCLocalize("IGNORE_UPGRADES_EX");
7797 - (void) onSubscribed:(id)control {
7798 bool value([control isOn]);
7799 if (package_ == nil)
7801 if ([package_ setSubscribed:value])
7802 [delegate_ updateData];
7805 - (void) _updateIgnored {
7806 const char *package([name_ UTF8String]);
7807 bool on([ignoredSwitch_ isOn]);
7809 pid_t pid(ExecFork());
7811 FILE *dpkg(popen("dpkg --set-selections", "w"));
7812 fwrite(package, strlen(package), 1, dpkg);
7815 fwrite(" hold\n", 6, 1, dpkg);
7817 fwrite(" install\n", 9, 1, dpkg);
7827 int result(waitpid(pid, &status, 0));
7830 _assert(result == pid);
7836 - (void) onIgnored:(id)control {
7837 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7838 [invocation setTarget:self];
7839 [invocation setSelector:@selector(_updateIgnored)];
7841 [delegate_ reloadDataWithInvocation:invocation];
7844 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7845 if (package_ == nil)
7848 switch ([indexPath section]) {
7849 case 0: return subscribedCell_;
7850 case 1: return ignoredCell_;
7859 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7861 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7862 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7863 [table_ setDataSource:self];
7864 [table_ setDelegate:self];
7865 [[self view] addSubview:table_];
7867 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7868 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7869 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7871 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7872 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7873 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7875 subscribedCell_ = [[UITableViewCell alloc] init];
7876 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7877 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7878 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7880 ignoredCell_ = [[UITableViewCell alloc] init];
7881 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7882 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7883 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7886 - (void) viewDidLoad {
7887 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7890 - (void) releaseSubviews {
7891 [ignoredCell_ release];
7894 [subscribedCell_ release];
7895 subscribedCell_ = nil;
7900 [ignoredSwitch_ release];
7901 ignoredSwitch_ = nil;
7903 [subscribedSwitch_ release];
7904 subscribedSwitch_ = nil;
7907 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7908 if ((self = [super init]) != nil) {
7909 database_ = database;
7910 name_ = [package retain];
7914 - (void) reloadData {
7917 if (package_ != nil)
7918 [package_ autorelease];
7919 package_ = [database_ packageWithName:name_];
7921 if (package_ != nil) {
7922 package_ = [package_ retain];
7923 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7924 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7925 } // XXX: what now, G?
7927 [table_ reloadData];
7933 /* Installed Controller {{{ */
7934 @interface InstalledController : FilteredPackageListController {
7938 - (id) initWithDatabase:(Database *)database;
7940 - (void) updateRoleButton;
7941 - (void) queueStatusDidChange;
7945 @implementation InstalledController
7951 - (NSURL *) navigationURL {
7952 return [NSURL URLWithString:@"cydia://installed"];
7955 - (id) initWithDatabase:(Database *)database {
7956 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7957 [self updateRoleButton];
7958 [self queueStatusDidChange];
7963 - (void) queueButtonClicked {
7968 - (void) queueStatusDidChange {
7972 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7973 initWithTitle:UCLocalize("QUEUE")
7974 style:UIBarButtonItemStyleDone
7976 action:@selector(queueButtonClicked)
7979 [[self navigationItem] setLeftBarButtonItem:nil];
7985 - (void) updateRoleButton {
7986 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7987 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7988 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7989 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7991 action:@selector(roleButtonClicked)
7995 - (void) roleButtonClicked {
7996 [self setObject:[NSNumber numberWithBool:expert_]];
8000 [self updateRoleButton];
8006 /* Source Cell {{{ */
8007 @interface SourceCell : CYTableViewCell <
8015 - (void) setSource:(Source *)source;
8019 @implementation SourceCell
8021 - (void) clearSource {
8031 - (void) setSource:(Source *)source {
8035 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
8037 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8038 icon_ = [icon_ retain];
8040 origin_ = [[source name] retain];
8041 label_ = [[source uri] retain];
8043 [content_ setNeedsDisplay];
8051 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8052 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8053 UIView *content([self contentView]);
8054 CGRect bounds([content bounds]);
8056 content_ = [[ContentView alloc] initWithFrame:bounds];
8057 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8058 [content_ setBackgroundColor:[UIColor whiteColor]];
8059 [content addSubview:content_];
8061 [content_ setDelegate:self];
8062 [content_ setOpaque:YES];
8066 - (NSString *) accessibilityLabel {
8070 - (void) drawContentRect:(CGRect)rect {
8071 bool highlighted(highlighted_);
8072 float width(rect.size.width);
8075 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8082 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8086 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8091 /* Source Controller {{{ */
8092 @interface SourceController : FilteredPackageListController {
8093 _transient Source *source_;
8097 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8101 @implementation SourceController
8103 - (NSURL *) navigationURL {
8104 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8107 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8108 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8110 key_ = [[source key] retain];
8114 - (void) reloadData {
8115 source_ = [database_ sourceWithKey:key_];
8117 key_ = [[source_ key] retain];
8118 [self setObject:source_];
8119 [[self navigationItem] setTitle:[source_ label]];
8126 /* Sources Controller {{{ */
8127 @interface SourcesController : CYViewController <
8128 UITableViewDataSource,
8131 _transient Database *database_;
8133 NSMutableArray *sources_;
8137 UIProgressHUD *hud_;
8140 //NSURLConnection *installer_;
8141 NSURLConnection *trivial_;
8142 NSURLConnection *trivial_bz2_;
8143 NSURLConnection *trivial_gz_;
8144 //NSURLConnection *automatic_;
8149 - (id) initWithDatabase:(Database *)database;
8150 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8154 @implementation SourcesController
8156 - (void) _releaseConnection:(NSURLConnection *)connection {
8157 if (connection != nil) {
8158 [connection cancel];
8159 //[connection setDelegate:nil];
8160 [connection release];
8165 [self releaseSubviews];
8171 //[self _releaseConnection:installer_];
8172 [self _releaseConnection:trivial_];
8173 [self _releaseConnection:trivial_gz_];
8174 [self _releaseConnection:trivial_bz2_];
8175 //[self _releaseConnection:automatic_];
8181 - (NSURL *) navigationURL {
8182 return [NSURL URLWithString:@"cydia://sources"];
8185 - (void) viewDidAppear:(BOOL)animated {
8186 [super viewDidAppear:animated];
8187 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8190 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8191 return offset_ == 0 ? 1 : 2;
8194 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8195 switch (section + (offset_ == 0 ? 1 : 0)) {
8196 case 0: return UCLocalize("ENTERED_BY_USER");
8197 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8203 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8204 int count = [sources_ count];
8206 case 0: return (offset_ == 0 ? count : offset_);
8207 case 1: return count - offset_;
8213 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8215 switch (indexPath.section) {
8216 case 0: idx = indexPath.row; break;
8217 case 1: idx = indexPath.row + offset_; break;
8221 return [sources_ objectAtIndex:idx];
8224 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8225 static NSString *cellIdentifier = @"SourceCell";
8227 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8228 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8229 [cell setSource:[self sourceAtIndexPath:indexPath]];
8230 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8235 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8236 Source *source = [self sourceAtIndexPath:indexPath];
8238 SourceController *controller = [[[SourceController alloc]
8239 initWithDatabase:database_
8243 [controller setDelegate:delegate_];
8245 [[self navigationController] pushViewController:controller animated:YES];
8248 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8249 Source *source = [self sourceAtIndexPath:indexPath];
8250 return [source record] != nil;
8253 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8254 Source *source = [self sourceAtIndexPath:indexPath];
8255 [Sources_ removeObjectForKey:[source key]];
8256 [delegate_ syncData];
8260 [delegate_ addTrivialSource:href_];
8261 [delegate_ syncData];
8264 - (NSString *) getWarning {
8265 NSString *href(href_);
8266 NSRange colon([href rangeOfString:@"://"]);
8267 if (colon.location != NSNotFound)
8268 href = [href substringFromIndex:(colon.location + 3)];
8269 href = [href stringByAddingPercentEscapes];
8270 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8271 href = [href stringByCachingURLWithCurrentCDN];
8273 NSURL *url([NSURL URLWithString:href]);
8275 NSStringEncoding encoding;
8276 NSError *error(nil);
8278 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8279 return [warning length] == 0 ? nil : warning;
8283 - (void) _endConnection:(NSURLConnection *)connection {
8284 // XXX: the memory management in this method is horribly awkward
8286 NSURLConnection **field = NULL;
8287 if (connection == trivial_)
8289 else if (connection == trivial_bz2_)
8290 field = &trivial_bz2_;
8291 else if (connection == trivial_gz_)
8292 field = &trivial_gz_;
8293 _assert(field != NULL);
8294 [connection release];
8299 trivial_bz2_ == nil &&
8305 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8308 UIAlertView *alert = [[[UIAlertView alloc]
8309 initWithTitle:UCLocalize("SOURCE_WARNING")
8312 cancelButtonTitle:UCLocalize("CANCEL")
8314 UCLocalize("ADD_ANYWAY"),
8318 [alert setContext:@"warning"];
8319 [alert setNumberOfRows:1];
8323 } else if (error_ != nil) {
8324 UIAlertView *alert = [[[UIAlertView alloc]
8325 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8326 message:[error_ localizedDescription]
8328 cancelButtonTitle:UCLocalize("OK")
8329 otherButtonTitles:nil
8332 [alert setContext:@"urlerror"];
8335 UIAlertView *alert = [[[UIAlertView alloc]
8336 initWithTitle:UCLocalize("NOT_REPOSITORY")
8337 message:UCLocalize("NOT_REPOSITORY_EX")
8339 cancelButtonTitle:UCLocalize("OK")
8340 otherButtonTitles:nil
8343 [alert setContext:@"trivial"];
8347 [delegate_ releaseNetworkActivityIndicator];
8349 [delegate_ removeProgressHUD:hud_];
8358 if (error_ != nil) {
8365 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8366 switch ([response statusCode]) {
8372 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8373 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8375 error_ = [error retain];
8376 [self _endConnection:connection];
8379 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8380 [self _endConnection:connection];
8383 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8384 NSMutableURLRequest *request = [NSMutableURLRequest
8385 requestWithURL:[NSURL URLWithString:href]
8386 cachePolicy:NSURLRequestUseProtocolCachePolicy
8387 timeoutInterval:120.0
8390 [request setHTTPMethod:method];
8392 if (Machine_ != NULL)
8393 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8394 if (UniqueID_ != nil)
8395 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8397 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
8399 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8402 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8403 NSString *context([alert context]);
8405 if ([context isEqualToString:@"source"]) {
8408 NSString *href = [[alert textField] text];
8410 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8412 if (![href hasSuffix:@"/"])
8413 href_ = [href stringByAppendingString:@"/"];
8416 href_ = [href_ retain];
8418 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8419 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8420 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8421 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8425 // XXX: this is stupid
8426 hud_ = [[delegate_ addProgressHUD] retain];
8427 [hud_ setText:UCLocalize("VERIFYING_URL")];
8428 [delegate_ retainNetworkActivityIndicator];
8437 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8438 } else if ([context isEqualToString:@"trivial"])
8439 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8440 else if ([context isEqualToString:@"urlerror"])
8441 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8442 else if ([context isEqualToString:@"warning"]) {
8457 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8462 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8464 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8465 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8466 [list_ setRowHeight:56];
8467 [list_ setDataSource:self];
8468 [list_ setDelegate:self];
8469 [[self view] addSubview:list_];
8472 - (void) viewDidLoad {
8473 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8474 [self updateButtonsForEditingStatus:NO animated:NO];
8477 - (void) releaseSubviews {
8482 - (id) initWithDatabase:(Database *)database {
8483 if ((self = [super init]) != nil) {
8484 database_ = database;
8485 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8489 - (void) reloadData {
8493 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8496 [sources_ removeAllObjects];
8497 [sources_ addObjectsFromArray:[database_ sources]];
8499 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8502 int count([sources_ count]);
8504 for (int i = 0; i != count; i++) {
8505 if ([[sources_ objectAtIndex:i] record] == nil)
8510 [list_ setEditing:NO];
8511 [self updateButtonsForEditingStatus:NO animated:NO];
8515 - (void) showAddSourcePrompt {
8516 UIAlertView *alert = [[[UIAlertView alloc]
8517 initWithTitle:UCLocalize("ENTER_APT_URL")
8520 cancelButtonTitle:UCLocalize("CANCEL")
8522 UCLocalize("ADD_SOURCE"),
8526 [alert setContext:@"source"];
8527 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8529 [alert setNumberOfRows:1];
8530 [alert addTextFieldWithValue:@"http://" label:@""];
8532 UITextInputTraits *traits = [[alert textField] textInputTraits];
8533 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8534 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8535 [traits setKeyboardType:UIKeyboardTypeURL];
8536 // XXX: UIReturnKeyDone
8537 [traits setReturnKeyType:UIReturnKeyNext];
8542 - (void) addButtonClicked {
8543 [self showAddSourcePrompt];
8546 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8547 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8548 initWithTitle:UCLocalize("ADD")
8549 style:UIBarButtonItemStylePlain
8551 action:@selector(addButtonClicked)
8552 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8554 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8555 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8556 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8558 action:@selector(editButtonClicked)
8559 ] autorelease] animated:animated];
8561 if (IsWildcat_ && !editing)
8562 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8563 initWithTitle:UCLocalize("SETTINGS")
8564 style:UIBarButtonItemStylePlain
8566 action:@selector(settingsButtonClicked)
8570 - (void) settingsButtonClicked {
8571 [delegate_ showSettings];
8574 - (void) editButtonClicked {
8575 [list_ setEditing:![list_ isEditing] animated:YES];
8577 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8583 /* Settings Controller {{{ */
8584 @interface SettingsController : CYViewController <
8585 UITableViewDataSource,
8588 _transient Database *database_;
8589 // XXX: ok, "roledelegate_"?...
8590 _transient id roledelegate_;
8591 UITableView *table_;
8592 UISegmentedControl *segment_;
8596 - (void) showDoneButton;
8597 - (void) resizeSegmentedControl;
8601 @implementation SettingsController
8604 [self releaseSubviews];
8610 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8612 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8613 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8614 [table_ setDelegate:self];
8615 [table_ setDataSource:self];
8616 [[self view] addSubview:table_];
8618 NSArray *items = [NSArray arrayWithObjects:
8620 UCLocalize("HACKER"),
8621 UCLocalize("DEVELOPER"),
8623 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8624 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8625 [container_ addSubview:segment_];
8628 - (void) viewDidLoad {
8629 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8632 if ([Role_ isEqualToString:@"User"]) index = 0;
8633 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8634 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8636 [segment_ setSelectedSegmentIndex:index];
8637 [self showDoneButton];
8640 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8641 [self resizeSegmentedControl];
8644 - (void) releaseSubviews {
8651 [container_ release];
8655 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8656 if ((self = [super init]) != nil) {
8657 database_ = database;
8658 roledelegate_ = delegate;
8662 - (void) resizeSegmentedControl {
8663 CGFloat width = [[self view] frame].size.width;
8664 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8667 - (void) viewWillAppear:(BOOL)animated {
8668 [super viewWillAppear:animated];
8670 [self resizeSegmentedControl];
8673 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8674 [self resizeSegmentedControl];
8677 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8678 [self resizeSegmentedControl];
8682 NSString *role(nil);
8684 switch ([segment_ selectedSegmentIndex]) {
8685 case 0: role = @"User"; break;
8686 case 1: role = @"Hacker"; break;
8687 case 2: role = @"Developer"; break;
8692 if (![role isEqualToString:Role_]) {
8693 bool rolling(Role_ == nil);
8696 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8700 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8704 [roledelegate_ loadData];
8706 [roledelegate_ updateData];
8710 - (void) segmentChanged:(UISegmentedControl *)control {
8711 [self showDoneButton];
8714 - (void) saveAndClose {
8717 [[self navigationItem] setRightBarButtonItem:nil];
8718 [[self navigationController] dismissModalViewControllerAnimated:YES];
8721 - (void) doneButtonClicked {
8722 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8723 [spinner startAnimating];
8724 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8725 [[self navigationItem] setRightBarButtonItem:spinItem];
8727 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8730 - (void) showDoneButton {
8731 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8732 initWithTitle:UCLocalize("DONE")
8733 style:UIBarButtonItemStyleDone
8735 action:@selector(doneButtonClicked)
8736 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8739 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8740 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8744 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8748 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8749 return nil; // This method is required by the protocol.
8752 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8754 return UCLocalize("ROLE_EX");
8756 return [NSString stringWithFormat:
8757 @"%@: %@\n%@: %@\n%@: %@",
8758 UCLocalize("USER"), UCLocalize("USER_EX"),
8759 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8760 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8765 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8766 return section == 3 ? 44.0f : 0;
8769 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8770 return section == 3 ? container_ : nil;
8773 - (void) reloadData {
8775 [table_ reloadData];
8780 /* Stash Controller {{{ */
8781 @interface StashController : CYViewController {
8782 UIActivityIndicatorView *spinner_;
8789 @implementation StashController
8792 [self releaseSubviews];
8798 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8799 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8801 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8802 CGRect spinrect = [spinner_ frame];
8803 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8804 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8805 [spinner_ setFrame:spinrect];
8806 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8807 [[self view] addSubview:spinner_];
8808 [spinner_ startAnimating];
8811 captrect.size.width = [[self view] frame].size.width;
8812 captrect.size.height = 40.0f;
8813 captrect.origin.x = 0;
8814 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8815 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8816 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8817 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8818 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8819 [caption_ setTextColor:[UIColor whiteColor]];
8820 [caption_ setBackgroundColor:[UIColor clearColor]];
8821 [caption_ setShadowColor:[UIColor blackColor]];
8822 [caption_ setTextAlignment:UITextAlignmentCenter];
8823 [[self view] addSubview:caption_];
8826 statusrect.size.width = [[self view] frame].size.width;
8827 statusrect.size.height = 30.0f;
8828 statusrect.origin.x = 0;
8829 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8830 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8831 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8832 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8833 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8834 [status_ setTextColor:[UIColor whiteColor]];
8835 [status_ setBackgroundColor:[UIColor clearColor]];
8836 [status_ setShadowColor:[UIColor blackColor]];
8837 [status_ setTextAlignment:UITextAlignmentCenter];
8838 [[self view] addSubview:status_];
8841 - (void) releaseSubviews {
8855 @interface Cydia : UIApplication <
8856 ConfirmationControllerDelegate,
8859 UINavigationControllerDelegate,
8860 UITabBarControllerDelegate
8862 // XXX: evaluate all fields for _transient
8865 CYTabBarController *tabbar_;
8866 CYEmulatedLoadingController *emulated_;
8868 NSMutableArray *essential_;
8869 NSMutableArray *broken_;
8871 Database *database_;
8878 StashController *stash_;
8887 @implementation Cydia
8889 - (void) beginUpdate {
8890 [tabbar_ beginUpdate];
8894 return [tabbar_ updating];
8898 if ([broken_ count] != 0) {
8899 int count = [broken_ count];
8901 UIAlertView *alert = [[[UIAlertView alloc]
8902 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8903 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8905 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8907 UCLocalize("TEMPORARY_IGNORE"),
8911 [alert setContext:@"fixhalf"];
8912 [alert setNumberOfRows:2];
8914 } else if (!Ignored_ && [essential_ count] != 0) {
8915 int count = [essential_ count];
8917 UIAlertView *alert = [[[UIAlertView alloc]
8918 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8919 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8921 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8923 UCLocalize("UPGRADE_ESSENTIAL"),
8924 UCLocalize("COMPLETE_UPGRADE"),
8928 [alert setContext:@"upgrade"];
8933 - (void) _saveConfig {
8939 NSString *error(nil);
8941 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8943 NSError *error(nil);
8944 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8945 NSLog(@"failure to save metadata data: %@", error);
8950 NSLog(@"failure to serialize metadata: %@", error);
8955 // Navigation controller for the queuing badge.
8956 - (CYNavigationController *) queueNavigationController {
8957 NSArray *controllers = [tabbar_ viewControllers];
8958 return [controllers objectAtIndex:3];
8961 - (void) _updateData {
8964 [tabbar_ reloadData];
8966 CYNavigationController *navigation = [self queueNavigationController];
8968 id queuedelegate = nil;
8969 if ([[navigation viewControllers] count] > 0)
8970 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8972 [queuedelegate queueStatusDidChange];
8973 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8976 - (void) _refreshIfPossible:(NSDate *)update {
8977 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8979 bool recently = false;
8980 if (update != nil) {
8981 NSTimeInterval interval([update timeIntervalSinceNow]);
8982 if (interval <= 0 && interval > -(15*60))
8986 // Don't automatic refresh if:
8987 // - We already refreshed recently.
8988 // - We already auto-refreshed this launch.
8989 // - Auto-refresh is disabled.
8990 if (recently || loaded_ || ManualRefresh) {
8991 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8993 // If we are cancelling, we need to make sure it knows it's already loaded.
8997 // We are going to load, so remember that.
9001 SCNetworkReachabilityFlags flags; {
9002 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9003 SCNetworkReachabilityGetFlags(reachability, &flags);
9004 CFRelease(reachability);
9007 // XXX: this elaborate mess is what Apple is using to determine this? :(
9008 // XXX: do we care if the user has to intervene? maybe that's ok?
9010 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9011 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9012 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9013 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9014 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9015 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9019 // If we can reach the server, auto-refresh!
9021 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9026 - (void) refreshIfPossible {
9027 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9030 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
9031 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9032 [hud setText:UCLocalize("RELOADING_DATA")];
9034 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9037 [self removeProgressHUD:hud];
9041 [essential_ removeAllObjects];
9042 [broken_ removeAllObjects];
9044 NSArray *packages([database_ packages]);
9045 for (Package *package in packages) {
9047 [broken_ addObject:package];
9048 if ([package upgradableAndEssential:NO]) {
9049 if ([package essential])
9050 [essential_ addObject:package];
9055 NSLog(@"changes:#%u", changes);
9057 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9060 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9061 [changesItem setBadgeValue:badge];
9062 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9063 [self setApplicationIconBadgeNumber:changes];
9066 [changesItem setBadgeValue:nil];
9067 [changesItem setAnimatedBadge:NO];
9068 [self setApplicationIconBadgeNumber:0];
9073 [self refreshIfPossible];
9076 - (void) updateData {
9085 @synchronized (self) {
9086 [self _reloadDataWithInvocation:nil];
9090 - (void) disemulate {
9091 if (emulated_ == nil)
9094 [window_ addSubview:[tabbar_ view]];
9095 [[emulated_ view] removeFromSuperview];
9096 [emulated_ release];
9098 [window_ setUserInteractionEnabled:YES];
9101 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9102 UINavigationController *navigation([[[CYNavigationController alloc] initWithRootViewController:controller] autorelease]);
9104 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9106 UIViewController *parent;
9107 if (emulated_ == nil)
9116 [parent presentModalViewController:navigation animated:YES];
9119 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9120 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9122 if (navigation != nil)
9123 [navigation pushViewController:progress animated:YES];
9125 [self presentModalViewController:progress force:YES];
9127 [progress invoke:invocation withTitle:title];
9131 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9132 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9135 - (void) repairWithInvocation:(NSInvocation *)invocation {
9137 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9141 - (void) repairWithSelector:(SEL)selector {
9142 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9148 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
9149 _assert(file != NULL);
9151 for (NSString *key in [Sources_ allKeys]) {
9152 NSDictionary *source([Sources_ objectForKey:key]);
9154 fprintf(file, "%s %s %s\n",
9155 [[source objectForKey:@"Type"] UTF8String],
9156 [[source objectForKey:@"URI"] UTF8String],
9157 [[source objectForKey:@"Distribution"] UTF8String]
9163 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9168 - (void) addTrivialSource:(NSString *)href {
9169 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
9172 @"./", @"Distribution",
9173 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
9178 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9179 @synchronized (self) {
9180 [self _reloadDataWithInvocation:invocation];
9184 - (void) reloadData {
9185 [self reloadDataWithInvocation:nil];
9189 pkgProblemResolver *resolver = [database_ resolver];
9191 resolver->InstallProtect();
9192 if (!resolver->Resolve(true))
9197 // XXX: this is a really crappy way of doing this.
9198 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9199 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9200 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9201 if ([tabbar_ updating])
9202 [tabbar_ cancelUpdate];
9204 if (![database_ prepare])
9207 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9208 [page setDelegate:self];
9209 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
9210 [confirm_ setDelegate:self];
9213 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9214 [tabbar_ presentModalViewController:confirm_ animated:YES];
9220 @synchronized (self) {
9225 - (void) clearPackage:(Package *)package {
9226 @synchronized (self) {
9233 - (void) installPackages:(NSArray *)packages {
9234 @synchronized (self) {
9235 for (Package *package in packages)
9242 - (void) installPackage:(Package *)package {
9243 @synchronized (self) {
9250 - (void) removePackage:(Package *)package {
9251 @synchronized (self) {
9258 - (void) distUpgrade {
9259 @synchronized (self) {
9260 if (![database_ upgrade])
9266 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9269 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
9274 - (void) showSettings {
9275 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9276 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9278 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9279 [tabbar_ presentModalViewController:nav animated:YES];
9282 - (void) retainNetworkActivityIndicator {
9283 if (activity_++ == 0)
9284 [self setNetworkActivityIndicatorVisible:YES];
9287 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9291 - (void) releaseNetworkActivityIndicator {
9292 if (--activity_ == 0)
9293 [self setNetworkActivityIndicatorVisible:NO];
9296 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9301 - (void) cancelAndClear:(bool)clear {
9302 @synchronized (self) {
9314 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9315 NSString *context([alert context]);
9317 if ([context isEqualToString:@"conffile"]) {
9318 FILE *input = [database_ input];
9319 if (button == [alert cancelButtonIndex])
9320 fprintf(input, "N\n");
9321 else if (button == [alert firstOtherButtonIndex])
9322 fprintf(input, "Y\n");
9325 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9326 } else if ([context isEqualToString:@"fixhalf"]) {
9327 if (button == [alert cancelButtonIndex]) {
9328 @synchronized (self) {
9329 for (Package *broken in broken_) {
9332 NSString *id = [broken id];
9333 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9334 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9335 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9336 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9342 } else if (button == [alert firstOtherButtonIndex]) {
9343 [broken_ removeAllObjects];
9347 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9348 } else if ([context isEqualToString:@"upgrade"]) {
9349 if (button == [alert firstOtherButtonIndex]) {
9350 @synchronized (self) {
9351 for (Package *essential in essential_)
9352 [essential install];
9357 } else if (button == [alert firstOtherButtonIndex] + 1) {
9359 } else if (button == [alert cancelButtonIndex]) {
9363 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9367 - (void) system:(NSString *)command { _pooled
9369 system([command UTF8String]);
9373 - (void) applicationWillSuspend {
9375 [super applicationWillSuspend];
9378 - (BOOL) isSafeToSuspend {
9381 NSLog(@"isSafeToSuspend: locked_ != 0");
9386 // Use external process status API internally.
9387 // This is probably a really bad idea.
9388 // XXX: what is the point of this? does this solve anything at all?
9389 uint64_t status = 0;
9391 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9392 notify_get_state(notify_token, &status);
9393 notify_cancel(notify_token);
9398 NSLog(@"isSafeToSuspend: status != 0");
9404 NSLog(@"isSafeToSuspend: -> true");
9409 - (void) applicationSuspend:(__GSEvent *)event {
9410 if ([self isSafeToSuspend])
9411 [super applicationSuspend:event];
9414 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9415 if ([self isSafeToSuspend])
9416 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9419 - (void) _setSuspended:(BOOL)value {
9420 if ([self isSafeToSuspend])
9421 [super _setSuspended:value];
9424 - (UIProgressHUD *) addProgressHUD {
9425 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9426 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9428 [window_ setUserInteractionEnabled:NO];
9431 UIViewController *target = tabbar_;
9432 while ([target modalViewController] != nil) target = [target modalViewController];
9433 [[target view] addSubview:hud];
9439 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9441 [hud removeFromSuperview];
9442 [window_ setUserInteractionEnabled:YES];
9446 - (CYViewController *) pageForPackage:(NSString *)name {
9447 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9450 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9451 NSString *scheme([[url scheme] lowercaseString]);
9452 if ([[url absoluteString] length] <= [scheme length] + 3)
9454 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9455 NSArray *components([path pathComponents]);
9457 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9458 return [self pageForPackage:[components objectAtIndex:1]];
9460 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9463 NSString *base([components objectAtIndex:0]);
9465 CYViewController *controller = nil;
9467 if ([base isEqualToString:@"url"]) {
9468 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9469 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9470 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9471 } else if (!external && [components count] == 1) {
9472 if ([base isEqualToString:@"manage"]) {
9473 controller = [[[ManageController alloc] init] autorelease];
9476 if ([base isEqualToString:@"sources"]) {
9477 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9480 if ([base isEqualToString:@"home"]) {
9481 controller = [[[HomeController alloc] init] autorelease];
9484 if ([base isEqualToString:@"sections"]) {
9485 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9488 if ([base isEqualToString:@"search"]) {
9489 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9492 if ([base isEqualToString:@"changes"]) {
9493 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9496 if ([base isEqualToString:@"installed"]) {
9497 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9499 } else if ([components count] == 2) {
9500 NSString *argument = [components objectAtIndex:1];
9502 if ([base isEqualToString:@"package"]) {
9503 controller = [self pageForPackage:argument];
9506 if (!external && [base isEqualToString:@"search"]) {
9507 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9508 [(SearchController *)controller setSearchTerm:argument];
9511 if (!external && [base isEqualToString:@"sections"]) {
9512 if ([argument isEqualToString:@"all"])
9514 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9517 if (!external && [base isEqualToString:@"sources"]) {
9518 if ([argument isEqualToString:@"add"]) {
9519 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9520 [(SourcesController *)controller showAddSourcePrompt];
9522 Source *source = [database_ sourceWithKey:argument];
9523 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9527 if (!external && [base isEqualToString:@"launch"]) {
9528 [self launchApplicationWithIdentifier:argument suspended:NO];
9531 } else if (!external && [components count] == 3) {
9532 NSString *arg1 = [components objectAtIndex:1];
9533 NSString *arg2 = [components objectAtIndex:2];
9535 if ([base isEqualToString:@"package"]) {
9536 if ([arg2 isEqualToString:@"settings"]) {
9537 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9538 } else if ([arg2 isEqualToString:@"files"]) {
9539 if (Package *package = [database_ packageWithName:arg1]) {
9540 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9541 [(FileTable *)controller setPackage:package];
9547 [controller setDelegate:self];
9551 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9552 CYViewController *page([self pageForURL:url forExternal:external]);
9555 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9556 [nav setViewControllers:[NSArray arrayWithObject:page]];
9557 [tabbar_ setUnselectedViewController:nav];
9563 - (void) applicationOpenURL:(NSURL *)url {
9564 [super applicationOpenURL:url];
9566 if (!loaded_) starturl_ = [url retain];
9567 else [self openCydiaURL:url forExternal:YES];
9570 - (void) applicationWillResignActive:(UIApplication *)application {
9571 // Stop refreshing if you get a phone call or lock the device.
9572 if ([tabbar_ updating])
9573 [tabbar_ cancelUpdate];
9575 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9576 [super applicationWillResignActive:application];
9579 - (void) applicationWillTerminate:(UIApplication *)application {
9581 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9582 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9583 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9588 - (void) setConfigurationData:(NSString *)data {
9589 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9591 if (!conffile_r(data)) {
9592 lprintf("E:invalid conffile\n");
9596 NSString *ofile = conffile_r[1];
9597 //NSString *nfile = conffile_r[2];
9599 UIAlertView *alert = [[[UIAlertView alloc]
9600 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9601 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9603 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9605 UCLocalize("ACCEPT_NEW_COPY"),
9606 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9610 [alert setContext:@"conffile"];
9611 [alert setNumberOfRows:2];
9615 - (void) addStashController {
9617 stash_ = [[StashController alloc] init];
9618 [window_ addSubview:[stash_ view]];
9621 - (void) removeStashController {
9622 [[stash_ view] removeFromSuperview];
9628 [self setIdleTimerDisabled:YES];
9630 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9631 UpdateExternalStatus(1);
9632 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9633 UpdateExternalStatus(0);
9635 [self removeStashController];
9637 if (ExecFork() == 0) {
9638 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9639 perror("launchctl stop");
9643 - (void) setupViewControllers {
9644 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9646 NSMutableArray *items([NSMutableArray arrayWithObjects:
9647 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9648 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9649 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9650 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9654 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9655 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9657 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9660 NSMutableArray *controllers([NSMutableArray array]);
9661 for (UITabBarItem *item in items) {
9662 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9663 [controller setTabBarItem:item];
9664 [controllers addObject:controller];
9666 [tabbar_ setViewControllers:controllers];
9668 [tabbar_ setUpdateDelegate:self];
9671 - (void) addCydiaHost:(NSString *)host {
9672 [CydiaHosts_ addObject:host];
9675 - (void) applicationDidFinishLaunching:(id)unused {
9677 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9678 [self setApplicationSupportsShakeToEdit:NO];
9680 [self addCydiaHost:[[NSURL URLWithString:CydiaURL(@"")] host]];
9682 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9683 initWithMemoryCapacity:524288
9684 diskCapacity:10485760
9685 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9688 [CYBrowserController _initialize];
9690 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9692 Font12_ = [[UIFont systemFontOfSize:12] retain];
9693 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9694 Font14_ = [[UIFont systemFontOfSize:14] retain];
9695 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9696 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9698 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9699 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9701 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9702 [window_ orderFront:self];
9703 [window_ makeKey:self];
9704 [window_ setHidden:NO];
9707 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9708 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9709 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9710 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9711 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9712 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9713 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9714 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9715 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9718 [self addStashController];
9719 // XXX: this would be much cleaner as a yieldToSelector:
9720 // that way the removeStashController could happen right here inline
9721 // we also could no longer require the useless stash_ field anymore
9722 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9726 database_ = [Database sharedInstance];
9727 [database_ setDelegate:self];
9729 [window_ setUserInteractionEnabled:NO];
9730 [self setupViewControllers];
9732 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9733 [window_ addSubview:[emulated_ view]];
9735 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9742 [window_ setUserInteractionEnabled:YES];
9743 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9746 if ([emulated_ modalViewController] != nil)
9747 [emulated_ dismissModalViewControllerAnimated:YES];
9748 [window_ setUserInteractionEnabled:NO];
9756 int selectedIndex = 0;
9757 NSMutableArray *items = nil;
9759 bool recently = false;
9760 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9761 if (closed != nil) {
9762 NSTimeInterval interval([closed timeIntervalSinceNow]);
9763 // XXX: Is 15 minutes the optimal time here?
9764 if (interval <= 0 && interval > -(15*60))
9768 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9769 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9772 for (NSArray *entry in items)
9773 if ([entry count] <= 0)
9776 if (!recently || !items || !enough) {
9778 items = [NSMutableArray array];
9779 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9780 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9781 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9783 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9785 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9786 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9788 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9791 [tabbar_ setSelectedIndex:selectedIndex];
9792 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9793 NSArray *stack = [items objectAtIndex:tab];
9794 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9795 NSMutableArray *current = [NSMutableArray array];
9797 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9798 NSString *addr = [stack objectAtIndex:nav];
9799 NSURL *url = [NSURL URLWithString:addr];
9800 CYViewController *page = [self pageForURL:url forExternal:NO];
9802 [current addObject:page];
9805 [navigation setViewControllers:current];
9808 // (Try to) show the startup URL.
9809 if (starturl_ != nil) {
9810 [self openCydiaURL:starturl_ forExternal:NO];
9811 [starturl_ release];
9816 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9817 if (item != nil && IsWildcat_) {
9818 [sheet showFromBarButtonItem:item animated:YES];
9820 [sheet showInView:window_];
9824 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9825 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9826 [progress setTitle:task];
9827 [progress addProgressEvent:event];
9830 - (void) addProgressEventForTask:(NSArray *)data {
9831 CydiaProgressEvent *event([data objectAtIndex:0]);
9832 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9833 [self addProgressEvent:event forTask:task];
9836 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9837 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9843 id Alloc_(id self, SEL selector) {
9844 id object = alloc_(self, selector);
9845 lprintf("[%s]A-%p\n", self->isa->name, object);
9850 id Dealloc_(id self, SEL selector) {
9851 id object = dealloc_(self, selector);
9852 lprintf("[%s]D-%p\n", self->isa->name, object);
9856 Class $WebDefaultUIKitDelegate;
9858 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9859 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9860 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9861 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9864 static NSNumber *shouldPlayKeyboardSounds;
9868 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9870 case 1104: // Keyboard Button Clicked
9871 case 1105: // Keyboard Delete Repeated
9872 if (shouldPlayKeyboardSounds == nil) {
9873 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9874 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9877 if (![shouldPlayKeyboardSounds boolValue])
9881 _UIHardware$_playSystemSound$(self, _cmd, sound);
9885 Class $UIApplication;
9887 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9888 static BOOL initialized = NO;
9889 static BOOL started = NO;
9891 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9892 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9894 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9895 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9896 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9897 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9899 if (initialized && !enabled) {
9901 [bundle performSelector:@selector(_accessibilityStopServer)];
9902 } else if (enabled) {
9906 [bundle performSelector:@selector(_accessibilityStartServer)];
9912 int main(int argc, char *argv[]) { _pooled
9915 UpdateExternalStatus(0);
9917 if (Class $UIDevice = objc_getClass("UIDevice")) {
9918 UIDevice *device([$UIDevice currentDevice]);
9919 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9923 UIScreen *screen([UIScreen mainScreen]);
9924 if ([screen respondsToSelector:@selector(scale)])
9925 ScreenScale_ = [screen scale];
9929 UIDevice *device([UIDevice currentDevice]);
9930 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9933 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9934 if (idiom == UIUserInterfaceIdiomPhone)
9936 else if (idiom == UIUserInterfaceIdiomPad)
9939 NSLog(@"unknown UIUserInterfaceIdiom!");
9942 CydiaHosts_ = [NSMutableSet setWithCapacity:2];
9944 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9946 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9948 /* Library Hacks {{{ */
9949 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9951 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9952 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9953 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9954 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9955 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9958 $UIHardware = objc_getClass("UIHardware");
9959 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9960 if (UIHardware$_playSystemSound$ != NULL) {
9961 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9962 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9965 $UIApplication = objc_getClass("UIApplication");
9966 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9967 if (UIApplication$_updateApplicationAccessibility != NULL) {
9968 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9969 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9972 /* Set Locale {{{ */
9973 Locale_ = CFLocaleCopyCurrent();
9974 Languages_ = [NSLocale preferredLanguages];
9975 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9976 //NSLog(@"%@", [Languages_ description]);
9979 if (Languages_ == nil || [Languages_ count] == 0)
9980 // XXX: consider just setting to C and then falling through?
9983 lang = [[Languages_ objectAtIndex:0] UTF8String];
9984 setenv("LANG", lang, true);
9985 std::setlocale(LC_ALL, lang);
9988 NSLog(@"Setting Language: %s", lang);
9991 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9993 /* Parse Arguments {{{ */
9994 bool substrate(false);
10000 for (int argi(1); argi != argc; ++argi)
10001 if (strcmp(argv[argi], "--") == 0) {
10003 argv[argi] = argv[0];
10009 for (int argi(1); argi != arge; ++argi)
10010 if (strcmp(args[argi], "--substrate") == 0)
10013 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10017 App_ = [[NSBundle mainBundle] bundlePath];
10023 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10024 alloc_ = alloc->method_imp;
10025 alloc->method_imp = (IMP) &Alloc_;*/
10027 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10028 dealloc_ = dealloc->method_imp;
10029 dealloc->method_imp = (IMP) &Dealloc_;*/
10031 /* System Information {{{ */
10035 size = sizeof(maxproc);
10036 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10037 perror("sysctlbyname(\"kern.maxproc\", ?)");
10038 else if (maxproc < 64) {
10040 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10041 perror("sysctlbyname(\"kern.maxproc\", #)");
10044 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10045 char *osversion = new char[size];
10046 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10047 perror("sysctlbyname(\"kern.osversion\", ?)");
10049 System_ = [NSString stringWithUTF8String:osversion];
10051 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10052 char *machine = new char[size];
10053 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10054 perror("sysctlbyname(\"hw.machine\", ?)");
10056 Machine_ = machine;
10058 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
10059 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
10060 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
10061 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
10065 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
10066 NSData *data((NSData *) ecid);
10067 size_t length([data length]);
10068 uint8_t bytes[length];
10069 [data getBytes:bytes];
10070 char string[length * 2 + 1];
10071 for (size_t i(0); i != length; ++i)
10072 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
10073 ChipID_ = [NSString stringWithUTF8String:string];
10077 IOObjectRelease(service);
10081 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
10083 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10084 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10085 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10087 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10088 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10089 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10091 if (mcc != NULL && mnc != NULL)
10092 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10099 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10100 Build_ = [system objectForKey:@"ProductBuildVersion"];
10101 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10102 Product_ = [info objectForKey:@"SafariProductVersion"];
10103 Safari_ = [info objectForKey:@"CFBundleVersion"];
10106 /* Load Database {{{ */
10108 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10110 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10112 if (Metadata_ == NULL)
10113 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10115 Settings_ = [Metadata_ objectForKey:@"Settings"];
10117 Packages_ = [Metadata_ objectForKey:@"Packages"];
10118 Sections_ = [Metadata_ objectForKey:@"Sections"];
10119 Sources_ = [Metadata_ objectForKey:@"Sources"];
10121 Token_ = [Metadata_ objectForKey:@"Token"];
10124 if (Settings_ != nil)
10125 Role_ = [Settings_ objectForKey:@"Role"];
10127 if (Sections_ == nil) {
10128 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10129 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10132 if (Sources_ == nil) {
10133 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10134 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10139 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10142 if (Packages_ != nil) {
10144 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10148 [Metadata_ removeObjectForKey:@"Packages"];
10154 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10156 #define MobileSubstrate_(name) \
10157 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10158 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10159 if (handle == NULL) \
10160 NSLog(@"%s", dlerror()); \
10163 MobileSubstrate_(Activator)
10164 MobileSubstrate_(libstatusbar)
10165 MobileSubstrate_(SimulatedKeyEvents)
10166 MobileSubstrate_(WinterBoard)
10168 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10169 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10171 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10173 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10174 unlink("/tmp/.cydia.fw");
10176 } else if (access("/User", F_OK) != 0 || version < 4) {
10179 system("/usr/libexec/cydia/firmware.sh");
10183 _assert([[NSFileManager defaultManager]
10184 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10185 withIntermediateDirectories:YES
10190 if (access("/tmp/cydia.chk", F_OK) == 0) {
10191 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10192 _assert(errno == ENOENT);
10193 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10194 _assert(errno == ENOENT);
10197 /* APT Initialization {{{ */
10198 _assert(pkgInitConfig(*_config));
10199 _assert(pkgInitSystem(*_config, _system));
10202 _config->Set("APT::Acquire::Translation", lang);
10204 // XXX: this timeout might be important :(
10205 //_config->Set("Acquire::http::Timeout", 15);
10207 _config->Set("Acquire::http::MaxParallel", 3);
10209 /* Color Choices {{{ */
10210 space_ = CGColorSpaceCreateDeviceRGB();
10212 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10213 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10214 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10215 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10216 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10217 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10218 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10219 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10220 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10222 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10223 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10225 /* UIKit Configuration {{{ */
10226 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10227 if ($GSFontSetUseLegacyFontMetrics != NULL)
10228 $GSFontSetUseLegacyFontMetrics(YES);
10230 // XXX: I have a feeling this was important
10231 //UIKeyboardDisableAutomaticAppearance();
10234 Colon_ = UCLocalize("COLON_DELIMITED");
10235 Elision_ = UCLocalize("ELISION");
10236 Error_ = UCLocalize("ERROR");
10237 Warning_ = UCLocalize("WARNING");
10240 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10242 CGColorSpaceRelease(space_);
10243 CFRelease(Locale_);