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]);
4576 NSString *scheme([[url scheme] lowercaseString]);
4577 NSString *host([url host]);
4579 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4580 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4581 NSDictionary *headers([http allHeaderFields]);
4582 [self setHeaders:headers forHost:host];
4585 if ([scheme isEqualToString:@"https"])
4586 if ([CydiaHosts_ containsObject:host])
4587 [window setValue:cydia_ forKey:@"cydia"];
4590 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4591 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4593 if (System_ != NULL)
4594 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4595 if (Machine_ != NULL)
4596 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4598 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4600 [copy setValue:Role_ forHTTPHeaderField:@"X-Role"];
4605 - (void) setDelegate:(id)delegate {
4606 [super setDelegate:delegate];
4607 [cydia_ setDelegate:delegate];
4611 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4612 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4614 WebView *webview([[webview_ _documentView] webView]);
4616 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4619 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4621 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4622 if (Product_ != nil)
4623 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4625 [webview setApplicationNameForUserAgent:application];
4633 @interface NSObject (CydiaScript)
4634 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4637 @implementation NSObject (CydiaScript)
4639 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4645 @implementation NSArray (CydiaScript)
4647 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4648 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4649 for (size_t i(0), e([self count]); i != e; ++i)
4650 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4656 @implementation NSDictionary (CydiaScript)
4658 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4659 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4661 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4668 /* Confirmation Controller {{{ */
4669 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4670 if (!iterator.end())
4671 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4672 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4674 pkgCache::PkgIterator package(dep.TargetPkg());
4677 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4684 @protocol ConfirmationControllerDelegate
4685 - (void) cancelAndClear:(bool)clear;
4686 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4690 @interface ConfirmationController : CYBrowserController {
4691 _transient Database *database_;
4693 UIAlertView *essential_;
4695 NSDictionary *changes_;
4696 NSMutableArray *issues_;
4697 NSDictionary *sizes_;
4702 - (id) initWithDatabase:(Database *)database;
4706 @implementation ConfirmationController
4713 if (essential_ != nil)
4714 [essential_ release];
4721 RestartSubstrate_ = true;
4722 [delegate_ confirmWithNavigationController:[self navigationController]];
4725 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4726 NSString *context([alert context]);
4728 if ([context isEqualToString:@"remove"]) {
4729 if (button == [alert cancelButtonIndex])
4730 [self dismissModalViewControllerAnimated:YES];
4731 else if (button == [alert firstOtherButtonIndex]) {
4735 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4736 } else if ([context isEqualToString:@"unable"]) {
4737 [self dismissModalViewControllerAnimated:YES];
4738 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4740 [super alertView:alert clickedButtonAtIndex:button];
4744 - (void) _doContinue {
4745 [self dismissModalViewControllerAnimated:YES];
4746 [delegate_ cancelAndClear:NO];
4749 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4750 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4754 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4755 [super webView:view didClearWindowObject:window forFrame:frame];
4757 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4758 changes_, @"changes",
4762 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4765 - (id) initWithDatabase:(Database *)database {
4766 if ((self = [super init]) != nil) {
4767 database_ = database;
4769 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4770 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4771 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4772 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4773 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4777 pkgCacheFile &cache([database_ cache]);
4778 NSArray *packages([database_ packages]);
4779 pkgDepCache::Policy *policy([database_ policy]);
4781 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4783 for (Package *package in packages) {
4784 pkgCache::PkgIterator iterator([package iterator]);
4785 NSString *name([package id]);
4787 if ([package broken]) {
4788 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4790 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4792 reasons, @"reasons",
4795 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4799 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4800 pkgCache::DepIterator start;
4801 pkgCache::DepIterator end;
4802 dep.GlobOr(start, end); // ++dep
4804 if (!cache->IsImportantDep(end))
4806 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4809 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4811 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4812 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4813 clauses, @"clauses",
4817 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4819 pkgCache::PkgIterator target(start.TargetPkg());
4820 if (target->ProvidesList != 0)
4821 reason = @"missing";
4823 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4825 reason = @"installed";
4826 installed = [NSString stringWithUTF8String:ver.VerStr()];
4827 } else if (!cache[target].CandidateVerIter(cache).end())
4828 reason = @"uninstalled";
4829 else if (target->ProvidesList == 0)
4830 reason = @"uninstallable";
4832 reason = @"virtual";
4835 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4836 [NSString stringWithUTF8String:start.CompType()], @"operator",
4837 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4840 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4841 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4842 version, @"version",
4844 installed, @"installed",
4847 // yes, seriously. (wtf?)
4855 pkgDepCache::StateCache &state(cache[iterator]);
4857 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4859 if (state.NewInstall())
4860 [installs addObject:name];
4861 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4862 [reinstalls addObject:name];
4863 else if (state.Upgrade())
4864 [upgrades addObject:name];
4865 else if (state.Downgrade())
4866 [downgrades addObject:name];
4867 else if (!state.Delete())
4869 else if (special_r(name))
4870 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4871 [NSNull null], @"package",
4872 [NSArray arrayWithObjects:
4873 [NSDictionary dictionaryWithObjectsAndKeys:
4874 @"Conflicts", @"relationship",
4875 [NSArray arrayWithObjects:
4876 [NSDictionary dictionaryWithObjectsAndKeys:
4878 [NSNull null], @"version",
4879 @"installed", @"reason",
4886 if ([package essential])
4888 [removes addObject:name];
4891 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4892 substrate_ |= DepSubstrate(iterator.CurrentVer());
4897 else if (Advanced_) {
4898 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4900 essential_ = [[UIAlertView alloc]
4901 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4902 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4904 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4906 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4910 [essential_ setContext:@"remove"];
4912 essential_ = [[UIAlertView alloc]
4913 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4914 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4916 cancelButtonTitle:UCLocalize("OKAY")
4917 otherButtonTitles:nil
4920 [essential_ setContext:@"unable"];
4923 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4924 installs, @"installs",
4925 reinstalls, @"reinstalls",
4926 upgrades, @"upgrades",
4927 downgrades, @"downgrades",
4928 removes, @"removes",
4931 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4932 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4933 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4936 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4938 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4939 initWithTitle:UCLocalize("CANCEL")
4940 style:UIBarButtonItemStylePlain
4942 action:@selector(cancelButtonClicked)
4948 - (void) applyRightButton {
4949 if ([issues_ count] == 0 && ![self isLoading])
4950 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4951 initWithTitle:UCLocalize("CONFIRM")
4952 style:UIBarButtonItemStyleDone
4954 action:@selector(confirmButtonClicked)
4957 [[self navigationItem] setRightBarButtonItem:nil];
4961 - (void) cancelButtonClicked {
4962 [self dismissModalViewControllerAnimated:YES];
4963 [delegate_ cancelAndClear:YES];
4967 - (void) confirmButtonClicked {
4968 if (essential_ != nil)
4978 /* Progress Data {{{ */
4979 @interface CydiaProgressData : NSObject {
4980 _transient id delegate_;
4989 _H<NSMutableArray> events_;
4990 _H<NSString> title_;
4992 _H<NSString> status_;
4993 _H<NSString> finish_;
4998 @implementation CydiaProgressData
5000 + (NSArray *) _attributeKeys {
5001 return [NSArray arrayWithObjects:
5013 - (NSArray *) attributeKeys {
5014 return [[self class] _attributeKeys];
5017 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5018 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5022 if ((self = [super init]) != nil) {
5023 events_ = [NSMutableArray arrayWithCapacity:32];
5027 - (void) setDelegate:(id)delegate {
5028 delegate_ = delegate;
5031 - (void) setPercent:(float)value {
5035 - (NSNumber *) percent {
5036 return [NSNumber numberWithFloat:percent_];
5039 - (void) setCurrent:(float)value {
5043 - (NSNumber *) current {
5044 return [NSNumber numberWithFloat:current_];
5047 - (void) setTotal:(float)value {
5051 - (NSNumber *) total {
5052 return [NSNumber numberWithFloat:total_];
5055 - (void) setSpeed:(float)value {
5059 - (NSNumber *) speed {
5060 return [NSNumber numberWithFloat:speed_];
5063 - (NSArray *) events {
5067 - (void) removeAllEvents {
5068 [events_ removeAllObjects];
5071 - (void) addEvent:(CydiaProgressEvent *)event {
5072 [events_ addObject:event];
5075 - (void) setTitle:(NSString *)text {
5079 - (NSString *) title {
5083 - (void) setFinish:(NSString *)text {
5087 - (NSString *) finish {
5088 return (id) finish_ ?: [NSNull null];
5091 - (void) setRunning:(bool)running {
5095 - (NSNumber *) running {
5096 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5101 /* Progress Controller {{{ */
5102 @interface ProgressController : CYBrowserController <
5105 _transient Database *database_;
5106 _H<CydiaProgressData> progress_;
5110 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5112 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5114 - (void) setTitle:(NSString *)title;
5115 - (void) setCancellable:(bool)cancellable;
5119 @implementation ProgressController
5122 [database_ setProgressDelegate:nil];
5123 [progress_ setDelegate:nil];
5127 - (void) updateCancel {
5128 [[self navigationItem] setLeftBarButtonItem:(cancel_ == 1 ? [[[UIBarButtonItem alloc]
5129 initWithTitle:UCLocalize("CANCEL")
5130 style:UIBarButtonItemStylePlain
5132 action:@selector(cancel)
5133 ] autorelease] : nil)];
5136 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5137 if ((self = [super init]) != nil) {
5138 database_ = database;
5139 delegate_ = delegate;
5141 [database_ setProgressDelegate:self];
5143 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5144 [progress_ setDelegate:self];
5146 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5148 [scroller_ setBackgroundColor:[UIColor blackColor]];
5150 [[self navigationItem] setHidesBackButton:YES];
5152 [self updateCancel];
5156 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5157 [super webView:view didClearWindowObject:window forFrame:frame];
5158 [window setValue:progress_ forKey:@"cydiaProgress"];
5161 - (void) updateProgress {
5162 [self dispatchEvent:@"CydiaProgressUpdate"];
5165 - (void) viewWillAppear:(BOOL)animated {
5166 if (![self hasLoaded])
5167 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5169 [super viewWillAppear:animated];
5173 UpdateExternalStatus(0);
5180 [delegate_ terminateWithSuccess];
5181 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5182 [delegate_ suspendWithAnimation:YES];
5184 [delegate_ suspend];*/
5196 system("/usr/bin/sbreload");
5202 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5203 SBReboot(SBSSpringBoardServerPort());
5205 reboot2(RB_AUTOBOOT);
5212 - (void) setTitle:(NSString *)title {
5213 [progress_ setTitle:title];
5214 [self updateProgress];
5217 - (UIBarButtonItem *) rightButton {
5218 return [[progress_ running] boolValue] ? nil : [[[UIBarButtonItem alloc]
5219 initWithTitle:UCLocalize("CLOSE")
5220 style:UIBarButtonItemStylePlain
5222 action:@selector(close)
5226 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5227 UpdateExternalStatus(1);
5229 [progress_ setRunning:true];
5230 [self setTitle:title];
5231 // implicit updateProgress
5233 SHA1SumValue notifyconf; {
5235 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5238 MMap mmap(file, MMap::ReadOnly);
5240 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5241 notifyconf = sha1.Result();
5245 SHA1SumValue springlist; {
5247 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5250 MMap mmap(file, MMap::ReadOnly);
5252 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5253 springlist = sha1.Result();
5257 if (invocation != nil) {
5258 [invocation yieldToSelector:@selector(invoke)];
5259 [self setTitle:@"COMPLETE"];
5264 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5267 MMap mmap(file, MMap::ReadOnly);
5269 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5270 if (!(notifyconf == sha1.Result()))
5277 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5280 MMap mmap(file, MMap::ReadOnly);
5282 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5283 if (!(springlist == sha1.Result()))
5289 if (RestartSubstrate_)
5293 RestartSubstrate_ = false;
5296 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5297 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5298 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5299 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5300 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5304 system("su -c /usr/bin/uicache mobile");
5307 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5309 [progress_ setRunning:false];
5310 [self updateProgress];
5312 [self applyRightButton];
5315 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5316 [progress_ addEvent:event];
5317 [self updateProgress];
5320 - (bool) isProgressCancelled {
5321 return cancel_ == 2;
5326 [self updateCancel];
5329 - (void) setCancellable:(bool)cancellable {
5330 unsigned cancel(cancel_);
5334 else if (cancel_ == 0)
5337 if (cancel != cancel_)
5338 [self updateCancel];
5341 - (void) setProgressCancellable:(NSNumber *)cancellable {
5342 [self setCancellable:[cancellable boolValue]];
5345 - (void) setProgressPercent:(NSNumber *)percent {
5346 [progress_ setPercent:[percent floatValue]];
5347 [self updateProgress];
5350 - (void) setProgressStatus:(NSDictionary *)status {
5351 if (status == nil) {
5352 [progress_ setCurrent:0];
5353 [progress_ setTotal:0];
5354 [progress_ setSpeed:0];
5356 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5358 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5359 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5360 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5363 [self updateProgress];
5369 /* Cell Content View {{{ */
5370 @protocol ContentDelegate
5371 - (void) drawContentRect:(CGRect)rect;
5374 @interface ContentView : UIView {
5375 _transient id<ContentDelegate> delegate_;
5380 @implementation ContentView
5382 - (id) initWithFrame:(CGRect)frame {
5383 if ((self = [super initWithFrame:frame]) != nil) {
5384 [self setNeedsDisplayOnBoundsChange:YES];
5388 - (void) setDelegate:(id<ContentDelegate>)delegate {
5389 delegate_ = delegate;
5392 - (void) drawRect:(CGRect)rect {
5393 [super drawRect:rect];
5394 [delegate_ drawContentRect:rect];
5399 /* Cydia TableView Cell {{{ */
5400 @interface CYTableViewCell : UITableViewCell {
5401 ContentView *content_;
5407 @implementation CYTableViewCell
5414 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5415 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5417 if (view == content_) {
5418 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5419 highlighted_ = highlighted;
5422 [super _updateHighlightColorsForView:view highlighted:highlighted];
5425 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5426 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5427 highlighted_ = selected;
5429 [super setSelected:selected animated:animated];
5430 [content_ setNeedsDisplay];
5436 /* Package Cell {{{ */
5437 @interface PackageCell : CYTableViewCell <
5442 NSString *description_;
5450 - (PackageCell *) init;
5451 - (void) setPackage:(Package *)package;
5453 - (void) drawContentRect:(CGRect)rect;
5457 @implementation PackageCell
5459 - (void) clearPackage {
5470 if (description_ != nil) {
5471 [description_ release];
5475 if (source_ != nil) {
5480 if (badge_ != nil) {
5485 if (placard_ != nil) {
5495 [self clearPackage];
5499 - (PackageCell *) init {
5500 CGRect frame(CGRectMake(0, 0, 320, 74));
5501 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5502 UIView *content([self contentView]);
5503 CGRect bounds([content bounds]);
5505 content_ = [[ContentView alloc] initWithFrame:bounds];
5506 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5507 [content addSubview:content_];
5509 [content_ setDelegate:self];
5510 [content_ setOpaque:YES];
5514 - (NSString *) accessibilityLabel {
5515 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5518 - (void) setPackage:(Package *)package {
5519 [self clearPackage];
5522 Source *source = [package source];
5524 icon_ = [[package icon] retain];
5525 name_ = [[package name] retain];
5528 description_ = [package longDescription];
5529 if (description_ == nil)
5530 description_ = [package shortDescription];
5531 if (description_ != nil)
5532 description_ = [description_ retain];
5534 commercial_ = [package isCommercial];
5536 package_ = [package retain];
5538 NSString *label = nil;
5539 bool trusted = false;
5541 if (source != nil) {
5542 label = [source label];
5543 trusted = [source trusted];
5544 } else if ([[package id] isEqualToString:@"firmware"])
5545 label = UCLocalize("APPLE");
5547 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5549 NSString *from(label);
5551 NSString *section = [package simpleSection];
5552 if (section != nil && ![section isEqualToString:label]) {
5553 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5554 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5557 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5558 source_ = [from retain];
5560 if (NSString *purpose = [package primaryPurpose])
5561 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5562 badge_ = [badge_ retain];
5567 if (NSString *mode = [package_ mode]) {
5568 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5569 color = RemovingColor_;
5570 //placard = @"removing";
5572 color = InstallingColor_;
5573 //placard = @"installing";
5576 // XXX: the removing/installing placards are not @2x
5579 color = [UIColor whiteColor];
5581 if ([package installed] != nil)
5582 placard = @"installed";
5587 [content_ setBackgroundColor:color];
5590 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5591 placard_ = [placard_ retain];
5593 [self setNeedsDisplay];
5594 [content_ setNeedsDisplay];
5597 - (void) drawContentRect:(CGRect)rect {
5598 bool highlighted(highlighted_);
5599 float width([self bounds].size.width);
5602 CGContextRef context(UIGraphicsGetCurrentContext());
5603 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5604 CGContextFillRect(context, rect);
5609 rect.size = [icon_ size];
5611 rect.size.width /= 2;
5612 rect.size.height /= 2;
5614 rect.origin.x = 25 - rect.size.width / 2;
5615 rect.origin.y = 25 - rect.size.height / 2;
5617 [icon_ drawInRect:rect];
5620 if (badge_ != nil) {
5622 rect.size = [badge_ size];
5624 rect.size.width /= 2;
5625 rect.size.height /= 2;
5627 rect.origin.x = 36 - rect.size.width / 2;
5628 rect.origin.y = 36 - rect.size.height / 2;
5630 [badge_ drawInRect:rect];
5637 UISetColor(commercial_ ? Purple_ : Black_);
5638 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5639 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5642 UISetColor(commercial_ ? Purplish_ : Gray_);
5643 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5645 if (placard_ != nil)
5646 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5651 /* Section Cell {{{ */
5652 @interface SectionCell : CYTableViewCell <
5664 - (void) setSection:(Section *)section editing:(BOOL)editing;
5668 @implementation SectionCell
5670 - (void) clearSection {
5671 if (basic_ != nil) {
5676 if (section_ != nil) {
5686 if (count_ != nil) {
5693 [self clearSection];
5699 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5700 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5701 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5702 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5703 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5705 UIView *content([self contentView]);
5706 CGRect bounds([content bounds]);
5708 content_ = [[ContentView alloc] initWithFrame:bounds];
5709 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5710 [content addSubview:content_];
5711 [content_ setBackgroundColor:[UIColor whiteColor]];
5713 [content_ setDelegate:self];
5717 - (void) onSwitch:(id)sender {
5718 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5719 if (metadata == nil) {
5720 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5721 [Sections_ setObject:metadata forKey:basic_];
5724 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5728 - (void) setSection:(Section *)section editing:(BOOL)editing {
5729 if (editing != editing_) {
5731 [switch_ removeFromSuperview];
5733 [self addSubview:switch_];
5737 [self clearSection];
5739 if (section == nil) {
5740 name_ = [UCLocalize("ALL_PACKAGES") retain];
5743 basic_ = [section name];
5745 basic_ = [basic_ retain];
5747 section_ = [section localized];
5748 if (section_ != nil)
5749 section_ = [section_ retain];
5751 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5752 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5755 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5758 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5759 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5761 [content_ setNeedsDisplay];
5764 - (void) setFrame:(CGRect)frame {
5765 [super setFrame:frame];
5767 CGRect rect([switch_ frame]);
5768 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5771 - (NSString *) accessibilityLabel {
5775 - (void) drawContentRect:(CGRect)rect {
5776 bool highlighted(highlighted_ && !editing_);
5778 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5783 float width(rect.size.width);
5789 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5791 CGSize size = [count_ sizeWithFont:Font14_];
5795 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5801 /* File Table {{{ */
5802 @interface FileTable : CYViewController <
5803 UITableViewDataSource,
5806 _transient Database *database_;
5809 NSMutableArray *files_;
5813 - (id) initWithDatabase:(Database *)database;
5814 - (void) setPackage:(Package *)package;
5818 @implementation FileTable
5821 [self releaseSubviews];
5830 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5831 return files_ == nil ? 0 : [files_ count];
5834 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5838 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5839 static NSString *reuseIdentifier = @"Cell";
5841 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5843 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5844 [cell setFont:[UIFont systemFontOfSize:16]];
5846 [cell setText:[files_ objectAtIndex:indexPath.row]];
5847 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5852 - (NSURL *) navigationURL {
5853 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5857 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5859 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5860 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5861 [list_ setRowHeight:24.0f];
5862 [list_ setDataSource:self];
5863 [list_ setDelegate:self];
5864 [[self view] addSubview:list_];
5867 - (void) viewDidLoad {
5868 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5871 - (void) releaseSubviews {
5876 - (id) initWithDatabase:(Database *)database {
5877 if ((self = [super init]) != nil) {
5878 database_ = database;
5880 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5884 - (void) setPackage:(Package *)package {
5885 if (package_ != nil) {
5886 [package_ autorelease];
5895 [files_ removeAllObjects];
5897 if (package != nil) {
5898 package_ = [package retain];
5899 name_ = [[package id] retain];
5901 if (NSArray *files = [package files])
5902 [files_ addObjectsFromArray:files];
5904 if ([files_ count] != 0) {
5905 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5906 [files_ removeObjectAtIndex:0];
5907 [files_ sortUsingSelector:@selector(compareByPath:)];
5909 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5910 [stack addObject:@"/"];
5912 for (int i(0), e([files_ count]); i != e; ++i) {
5913 NSString *file = [files_ objectAtIndex:i];
5914 while (![file hasPrefix:[stack lastObject]])
5915 [stack removeLastObject];
5916 NSString *directory = [stack lastObject];
5917 [stack addObject:[file stringByAppendingString:@"/"]];
5918 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5919 ([stack count] - 2) * 3, "",
5920 [file substringFromIndex:[directory length]]
5929 - (void) reloadData {
5932 [self setPackage:[database_ packageWithName:name_]];
5937 /* Package Controller {{{ */
5938 @interface CYPackageController : CYBrowserController <
5939 UIActionSheetDelegate
5941 _transient Database *database_;
5942 _H<Package> package_;
5945 _H<NSMutableArray> buttons_;
5946 _H<UIBarButtonItem> button_;
5949 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5953 @implementation CYPackageController
5955 - (NSURL *) navigationURL {
5956 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5959 /* XXX: this is not safe at all... localization of /fail/ */
5960 - (void) _clickButtonWithName:(NSString *)name {
5961 if ([name isEqualToString:UCLocalize("CLEAR")])
5962 [delegate_ clearPackage:package_];
5963 else if ([name isEqualToString:UCLocalize("INSTALL")])
5964 [delegate_ installPackage:package_];
5965 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5966 [delegate_ installPackage:package_];
5967 else if ([name isEqualToString:UCLocalize("REMOVE")])
5968 [delegate_ removePackage:package_];
5969 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5970 [delegate_ installPackage:package_];
5971 else _assert(false);
5974 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5975 NSString *context([sheet context]);
5977 if ([context isEqualToString:@"modify"]) {
5978 if (button != [sheet cancelButtonIndex]) {
5979 NSString *buttonName = [buttons_ objectAtIndex:button];
5980 [self _clickButtonWithName:buttonName];
5983 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5987 - (bool) _allowJavaScriptPanel {
5992 - (void) _customButtonClicked {
5993 int count([buttons_ count]);
5998 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6000 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6001 [buttons addObjectsFromArray:buttons_];
6003 UIActionSheet *sheet = [[[UIActionSheet alloc]
6006 cancelButtonTitle:nil
6007 destructiveButtonTitle:nil
6008 otherButtonTitles:nil
6011 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6013 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6014 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6016 [sheet setContext:@"modify"];
6018 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6022 // We don't want to allow non-commercial packages to do custom things to the install button,
6023 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6024 - (void) customButtonClicked {
6026 [super customButtonClicked];
6028 [self _customButtonClicked];
6031 - (void) reloadButtonClicked {
6032 // Don't reload a commerical package by tapping the loading button,
6033 // but if it's not an Install button, we should forward it on.
6034 if (![package_ uninstalled])
6035 [self _customButtonClicked];
6038 - (void) applyLoadingTitle {
6039 // Don't show "Loading" as the title. Ever.
6042 - (UIBarButtonItem *) rightButton {
6047 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
6048 if ((self = [super init]) != nil) {
6049 database_ = database;
6050 buttons_ = [NSMutableArray arrayWithCapacity:4];
6051 name_ = [NSString stringWithString:name];
6052 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
6056 - (void) reloadData {
6057 package_ = [database_ packageWithName:name_];
6059 [buttons_ removeAllObjects];
6061 if (package_ != nil) {
6062 [(Package *) package_ parse];
6064 commercial_ = [package_ isCommercial];
6066 if ([package_ mode] != nil)
6067 [buttons_ addObject:UCLocalize("CLEAR")];
6068 if ([package_ source] == nil);
6069 else if ([package_ upgradableAndEssential:NO])
6070 [buttons_ addObject:UCLocalize("UPGRADE")];
6071 else if ([package_ uninstalled])
6072 [buttons_ addObject:UCLocalize("INSTALL")];
6074 [buttons_ addObject:UCLocalize("REINSTALL")];
6075 if (![package_ uninstalled])
6076 [buttons_ addObject:UCLocalize("REMOVE")];
6080 switch ([buttons_ count]) {
6081 case 0: title = nil; break;
6082 case 1: title = [buttons_ objectAtIndex:0]; break;
6083 default: title = UCLocalize("MODIFY"); break;
6086 button_ = [[[UIBarButtonItem alloc]
6088 style:UIBarButtonItemStylePlain
6090 action:@selector(customButtonClicked)
6096 - (bool) isLoading {
6097 return commercial_ ? [super isLoading] : false;
6103 /* Package List Controller {{{ */
6104 @interface PackageListController : CYViewController <
6105 UITableViewDataSource,
6108 _transient Database *database_;
6110 NSMutableArray *packages_;
6111 NSMutableArray *sections_;
6113 NSMutableArray *index_;
6114 NSMutableDictionary *indices_;
6118 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6119 - (void) setDelegate:(id)delegate;
6120 - (void) resetCursor;
6124 @implementation PackageListController
6127 [packages_ release];
6128 [sections_ release];
6137 - (void) deselectWithAnimation:(BOOL)animated {
6138 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6141 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6142 CGRect base = [[self view] bounds];
6143 base.size.height -= bounds.size.height;
6144 base.origin = [list_ frame].origin;
6146 [UIView beginAnimations:nil context:NULL];
6147 [UIView setAnimationBeginsFromCurrentState:YES];
6148 [UIView setAnimationCurve:curve];
6149 [UIView setAnimationDuration:duration];
6150 [list_ setFrame:base];
6151 [UIView commitAnimations];
6154 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6155 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6158 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6159 [self resizeForKeyboardBounds:bounds duration:0];
6162 - (void) keyboardWillShow:(NSNotification *)notification {
6165 NSTimeInterval duration;
6166 UIViewAnimationCurve curve;
6167 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6168 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6169 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6170 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6172 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);
6173 UIViewController *base = self;
6174 while ([base parentViewController] != nil)
6175 base = [base parentViewController];
6176 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6177 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6179 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6182 - (void) keyboardWillHide:(NSNotification *)notification {
6183 NSTimeInterval duration;
6184 UIViewAnimationCurve curve;
6185 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6186 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6188 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6191 - (void) viewWillAppear:(BOOL)animated {
6192 [super viewWillAppear:animated];
6194 [self resizeForKeyboardBounds:CGRectZero];
6195 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6196 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6199 - (void) viewWillDisappear:(BOOL)animated {
6200 [super viewWillDisappear:animated];
6202 [self resizeForKeyboardBounds:CGRectZero];
6203 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6204 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6207 - (void) viewDidAppear:(BOOL)animated {
6208 [super viewDidAppear:animated];
6209 [self deselectWithAnimation:animated];
6212 - (void) didSelectPackage:(Package *)package {
6213 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6214 [view setDelegate:delegate_];
6215 [[self navigationController] pushViewController:view animated:YES];
6218 #if TryIndexedCollation
6219 + (BOOL) hasIndexedCollation {
6220 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6224 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6225 NSInteger count([sections_ count]);
6226 return count == 0 ? 1 : count;
6229 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6230 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6232 return [[sections_ objectAtIndex:section] name];
6235 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6236 if ([sections_ count] == 0)
6238 return [[sections_ objectAtIndex:section] count];
6241 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6242 @synchronized (database_) {
6243 if ([database_ era] != era_)
6246 Section *section([sections_ objectAtIndex:[path section]]);
6247 NSInteger row([path row]);
6248 Package *package([packages_ objectAtIndex:([section row] + row)]);
6249 return [[package retain] autorelease];
6252 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6253 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6255 cell = [[[PackageCell alloc] init] autorelease];
6256 [cell setPackage:[self packageAtIndexPath:path]];
6260 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6261 Package *package([self packageAtIndexPath:path]);
6262 package = [database_ packageWithName:[package id]];
6263 [self didSelectPackage:package];
6266 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6267 // XXX: is 20 the most optimal number here?
6268 return [packages_ count] > 20 ? index_ : nil;
6271 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6272 #if TryIndexedCollation
6273 if ([[self class] hasIndexedCollation]) {
6274 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6281 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6282 if ((self = [super init]) != nil) {
6283 database_ = database;
6284 title_ = [title copy];
6285 [[self navigationItem] setTitle:title_];
6287 #if TryIndexedCollation
6288 if ([[self class] hasIndexedCollation])
6289 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6292 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6294 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6296 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6297 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6299 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6300 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6301 [list_ setRowHeight:73];
6302 [[self view] addSubview:list_];
6304 [list_ setDataSource:self];
6305 [list_ setDelegate:self];
6309 - (void) setDelegate:(id)delegate {
6310 delegate_ = delegate;
6313 - (bool) hasPackage:(Package *)package {
6317 - (void) reloadData {
6320 era_ = [database_ era];
6321 NSArray *packages = [database_ packages];
6323 [packages_ removeAllObjects];
6324 [sections_ removeAllObjects];
6326 _profile(PackageTable$reloadData$Filter)
6327 for (Package *package in packages)
6328 if ([self hasPackage:package])
6329 [packages_ addObject:package];
6332 [indices_ removeAllObjects];
6334 Section *section = nil;
6336 #if TryIndexedCollation
6337 if ([[self class] hasIndexedCollation]) {
6338 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6339 NSArray *titles = [collation sectionIndexTitles];
6342 _profile(PackageTable$reloadData$Section)
6343 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6347 _profile(PackageTable$reloadData$Section$Package)
6348 package = [packages_ objectAtIndex:offset];
6349 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6352 while (secidx < index) {
6355 _profile(PackageTable$reloadData$Section$Allocate)
6356 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6359 _profile(PackageTable$reloadData$Section$Add)
6360 [sections_ addObject:section];
6364 [section addToCount];
6370 [index_ removeAllObjects];
6372 _profile(PackageTable$reloadData$Section)
6373 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6377 _profile(PackageTable$reloadData$Section$Package)
6378 package = [packages_ objectAtIndex:offset];
6379 index = [package index];
6382 if (section == nil || [section index] != index) {
6383 _profile(PackageTable$reloadData$Section$Allocate)
6384 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6387 [index_ addObject:[section name]];
6388 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6390 _profile(PackageTable$reloadData$Section$Add)
6391 [sections_ addObject:section];
6395 [section addToCount];
6400 _profile(PackageTable$reloadData$List)
6405 - (void) resetCursor {
6406 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6411 /* Filtered Package List Controller {{{ */
6412 @interface FilteredPackageListController : PackageListController {
6418 - (void) setObject:(id)object;
6419 - (void) setObject:(id)object forFilter:(SEL)filter;
6421 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6425 @implementation FilteredPackageListController
6433 - (void) setFilter:(SEL)filter {
6436 /* XXX: this is an unsafe optimization of doomy hell */
6437 Method method(class_getInstanceMethod([Package class], filter));
6438 _assert(method != NULL);
6439 imp_ = method_getImplementation(method);
6440 _assert(imp_ != NULL);
6443 - (void) setObject:(id)object {
6449 object_ = [object retain];
6452 - (void) setObject:(id)object forFilter:(SEL)filter {
6453 [self setFilter:filter];
6454 [self setObject:object];
6457 - (bool) hasPackage:(Package *)package {
6458 _profile(FilteredPackageTable$hasPackage)
6459 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6463 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6464 if ((self = [super initWithDatabase:database title:title]) != nil) {
6465 [self setFilter:filter];
6466 [self setObject:object];
6473 /* Home Controller {{{ */
6474 @interface HomeController : CYBrowserController {
6479 @implementation HomeController
6482 if ((self = [super init]) != nil) {
6483 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6487 - (NSURL *) navigationURL {
6488 return [NSURL URLWithString:@"cydia://home"];
6491 - (void) aboutButtonClicked {
6492 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6494 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6495 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6496 [alert setCancelButtonIndex:0];
6499 @"Copyright (C) 2008-2011\n"
6500 "Jay Freeman (saurik)\n"
6501 "saurik@saurik.com\n"
6502 "http://www.saurik.com/"
6508 - (void) viewDidLoad {
6509 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6510 initWithTitle:UCLocalize("ABOUT")
6511 style:UIBarButtonItemStylePlain
6513 action:@selector(aboutButtonClicked)
6519 /* Manage Controller {{{ */
6520 @interface ManageController : CYBrowserController {
6523 - (void) queueStatusDidChange;
6527 @implementation ManageController
6530 if ((self = [super init]) != nil) {
6531 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6535 - (NSURL *) navigationURL {
6536 return [NSURL URLWithString:@"cydia://manage"];
6539 - (void) viewDidLoad {
6540 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6541 initWithTitle:UCLocalize("SETTINGS")
6542 style:UIBarButtonItemStylePlain
6544 action:@selector(settingsButtonClicked)
6547 [self queueStatusDidChange];
6550 - (void) settingsButtonClicked {
6551 [delegate_ showSettings];
6555 - (void) queueButtonClicked {
6559 - (void) applyLoadingTitle {
6560 // Disable "Loading" title.
6563 - (void) applyRightButton {
6564 // Disable right button.
6568 - (void) queueStatusDidChange {
6570 if (!IsWildcat_ && Queuing_) {
6571 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6572 initWithTitle:UCLocalize("QUEUE")
6573 style:UIBarButtonItemStyleDone
6575 action:@selector(queueButtonClicked)
6578 [[self navigationItem] setRightBarButtonItem:nil];
6583 - (bool) isLoading {
6584 // Never show as loading.
6591 /* Refresh Bar {{{ */
6592 @interface RefreshBar : UINavigationBar {
6593 UIProgressIndicator *indicator_;
6594 UITextLabel *prompt_;
6595 UIProgressBar *progress_;
6596 UINavigationButton *cancel_;
6601 @implementation RefreshBar
6604 [indicator_ release];
6606 [progress_ release];
6611 - (void) positionViews {
6612 CGRect frame = [cancel_ frame];
6613 frame.size = [cancel_ sizeThatFits:frame.size];
6614 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6615 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6616 [cancel_ setFrame:frame];
6618 CGSize prgsize = {75, 100};
6620 [self frame].size.width - prgsize.width - 10,
6621 ([self frame].size.height - prgsize.height) / 2
6623 [progress_ setFrame:prgrect];
6625 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6626 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6627 CGRect indrect = {{indoffset, indoffset}, indsize};
6628 [indicator_ setFrame:indrect];
6630 CGSize prmsize = {215, indsize.height + 4};
6632 indoffset * 2 + indsize.width,
6633 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6635 [prompt_ setFrame:prmrect];
6638 - (void) setFrame:(CGRect)frame {
6639 [super setFrame:frame];
6640 [self positionViews];
6643 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6644 if ((self = [super initWithFrame:frame]) != nil) {
6645 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6647 [self setBarStyle:UIBarStyleBlack];
6649 UIBarStyle barstyle([self _barStyle:NO]);
6650 bool ugly(barstyle == UIBarStyleDefault);
6652 UIProgressIndicatorStyle style = ugly ?
6653 UIProgressIndicatorStyleMediumBrown :
6654 UIProgressIndicatorStyleMediumWhite;
6656 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6657 [indicator_ setStyle:style];
6658 [indicator_ startAnimation];
6659 [self addSubview:indicator_];
6661 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6662 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6663 [prompt_ setBackgroundColor:[UIColor clearColor]];
6664 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6665 [self addSubview:prompt_];
6667 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6668 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6669 [progress_ setStyle:0];
6670 [self addSubview:progress_];
6672 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6673 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6674 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6675 [cancel_ setBarStyle:barstyle];
6677 [self positionViews];
6681 - (void) setCancellable:(bool)cancellable {
6683 [self addSubview:cancel_];
6685 [cancel_ removeFromSuperview];
6689 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6690 [progress_ setProgress:0];
6694 [self setCancellable:NO];
6697 - (void) setPrompt:(NSString *)prompt {
6698 [prompt_ setText:prompt];
6701 - (void) setProgress:(float)progress {
6702 [progress_ setProgress:progress];
6708 @class CYNavigationController;
6710 /* Cydia Tab Bar Controller {{{ */
6711 @interface CYTabBarController : UITabBarController <
6712 UITabBarControllerDelegate,
6715 _transient Database *database_;
6716 RefreshBar *refreshbar_;
6720 // XXX: ok, "updatedelegate_"?...
6721 _transient NSObject<CydiaDelegate> *updatedelegate_;
6724 UIViewController *remembered_;
6725 _transient UIViewController *transient_;
6728 - (NSArray *) navigationURLCollection;
6729 - (void) dropBar:(BOOL)animated;
6730 - (void) beginUpdate;
6731 - (void) raiseBar:(BOOL)animated;
6736 @implementation CYTabBarController
6738 - (void) setUnselectedViewController:(UIViewController *)transient {
6739 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6740 if (transient != nil) {
6741 if (transient_ == nil)
6742 remembered_ = [[controllers objectAtIndex:0] retain];
6743 transient_ = transient;
6744 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6745 [controllers replaceObjectAtIndex:0 withObject:transient_];
6746 [self setSelectedIndex:0];
6747 [self setViewControllers:controllers];
6748 [self concealTabBarSelection];
6749 } else if (remembered_ != nil) {
6750 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6751 transient_ = transient;
6752 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6753 [remembered_ release];
6755 [self setViewControllers:controllers];
6756 [self revealTabBarSelection];
6760 - (UIViewController *) unselectedViewController {
6764 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6765 if ([self unselectedViewController])
6766 [self setUnselectedViewController:nil];
6769 - (NSArray *) navigationURLCollection {
6770 NSMutableArray *items([NSMutableArray array]);
6772 // XXX: Should this deal with transient view controllers?
6773 for (id navigation in [self viewControllers]) {
6774 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6776 [items addObject:stack];
6782 - (void) reloadData {
6783 for (CYViewController *controller in [self viewControllers])
6784 [controller reloadData];
6786 [(CYNavigationController *)[self unselectedViewController] reloadData];
6790 [refreshbar_ release];
6791 [[NSNotificationCenter defaultCenter] removeObserver:self];
6796 - (id) initWithDatabase:(Database *)database {
6797 if ((self = [super init]) != nil) {
6798 database_ = database;
6799 [self setDelegate:self];
6801 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6802 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6804 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6808 - (void) setUpdate:(NSDate *)date {
6812 - (void) beginUpdate {
6813 [refreshbar_ start];
6816 [updatedelegate_ retainNetworkActivityIndicator];
6820 detachNewThreadSelector:@selector(performUpdate)
6826 - (void) performUpdate { _pooled
6828 status.setDelegate(self);
6829 [database_ updateWithStatus:status];
6832 performSelectorOnMainThread:@selector(completeUpdate)
6838 - (void) stopUpdateWithSelector:(SEL)selector {
6840 [updatedelegate_ releaseNetworkActivityIndicator];
6842 [self raiseBar:YES];
6845 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6848 - (void) completeUpdate {
6851 [self stopUpdateWithSelector:@selector(reloadData)];
6854 - (void) cancelUpdate {
6855 [self stopUpdateWithSelector:@selector(updateData)];
6858 - (void) cancelPressed {
6859 [self cancelUpdate];
6866 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6867 [refreshbar_ setPrompt:[event compoundMessage]];
6870 - (bool) isProgressCancelled {
6874 - (void) setProgressCancellable:(NSNumber *)cancellable {
6875 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6878 - (void) setProgressPercent:(NSNumber *)percent {
6879 [refreshbar_ setProgress:[percent floatValue]];
6882 - (void) setProgressStatus:(NSDictionary *)status {
6884 [self setProgressPercent:[status objectForKey:@"Percent"]];
6887 - (void) setUpdateDelegate:(id)delegate {
6888 updatedelegate_ = delegate;
6891 - (CGFloat) statusBarHeight {
6892 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6893 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6895 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6899 - (UIView *) transitionView {
6900 if ([self respondsToSelector:@selector(_transitionView)])
6901 return [self _transitionView];
6903 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6906 - (void) dropBar:(BOOL)animated {
6911 UIView *transition([self transitionView]);
6912 [[self view] addSubview:refreshbar_];
6914 CGRect barframe([refreshbar_ frame]);
6916 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6917 barframe.origin.y = [self statusBarHeight];
6919 barframe.origin.y = 0;
6921 [refreshbar_ setFrame:barframe];
6924 [UIView beginAnimations:nil context:NULL];
6926 CGRect viewframe = [transition frame];
6927 viewframe.origin.y += barframe.size.height;
6928 viewframe.size.height -= barframe.size.height;
6929 [transition setFrame:viewframe];
6932 [UIView commitAnimations];
6934 // Ensure bar has the proper width for our view, it might have changed
6935 barframe.size.width = viewframe.size.width;
6936 [refreshbar_ setFrame:barframe];
6938 // XXX: fix Apple's layout bug
6939 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6942 - (void) raiseBar:(BOOL)animated {
6947 UIView *transition([self transitionView]);
6948 [refreshbar_ removeFromSuperview];
6950 CGRect barframe([refreshbar_ frame]);
6953 [UIView beginAnimations:nil context:NULL];
6955 CGRect viewframe = [transition frame];
6956 viewframe.origin.y -= barframe.size.height;
6957 viewframe.size.height += barframe.size.height;
6958 [transition setFrame:viewframe];
6961 [UIView commitAnimations];
6963 // XXX: fix Apple's layout bug
6964 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6968 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6969 // XXX: fix Apple's layout bug
6970 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6974 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6975 bool dropped(dropped_);
6980 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6985 // XXX: fix Apple's layout bug
6986 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6989 - (void) statusBarFrameChanged:(NSNotification *)notification {
6998 /* Cydia Navigation Controller {{{ */
6999 @interface CYNavigationController : UINavigationController {
7000 _transient Database *database_;
7001 _transient id<UINavigationControllerDelegate> delegate_;
7004 - (NSArray *) navigationURLCollection;
7005 - (id) initWithDatabase:(Database *)database;
7006 - (void) reloadData;
7011 @implementation CYNavigationController
7013 - (NSArray *) navigationURLCollection {
7014 NSMutableArray *stack([NSMutableArray array]);
7016 for (CYViewController *controller in [self viewControllers]) {
7017 NSString *url = [[controller navigationURL] absoluteString];
7019 [stack addObject:url];
7025 - (void) reloadData {
7026 for (CYViewController *page in [self viewControllers]) {
7027 // Only reload controllers that have already loaded.
7028 // This prevents a page from accidentally loading too
7029 // early if it hasn't been shown on the screen yet.
7030 if ([page hasLoaded])
7035 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
7036 delegate_ = delegate;
7039 - (id) initWithDatabase:(Database *)database {
7040 if ((self = [super init]) != nil) {
7041 database_ = database;
7048 /* Cydia:// Protocol {{{ */
7049 @interface CydiaURLProtocol : NSURLProtocol {
7054 @implementation CydiaURLProtocol
7056 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7057 NSURL *url([request URL]);
7061 NSString *scheme([[url scheme] lowercaseString]);
7062 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7064 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7070 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7074 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7075 id<NSURLProtocolClient> client([self client]);
7077 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7079 NSData *data(UIImagePNGRepresentation(icon));
7081 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7082 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7083 [client URLProtocol:self didLoadData:data];
7084 [client URLProtocolDidFinishLoading:self];
7088 - (void) startLoading {
7089 id<NSURLProtocolClient> client([self client]);
7090 NSURLRequest *request([self request]);
7092 NSURL *url([request URL]);
7093 NSString *href([url absoluteString]);
7094 NSString *scheme([[url scheme] lowercaseString]);
7098 if ([scheme isEqualToString:@"cydia"])
7099 path = [href substringFromIndex:8];
7100 else if ([scheme isEqualToString:@"about"])
7101 path = [href substringFromIndex:12];
7102 else _assert(false);
7104 NSRange slash([path rangeOfString:@"/"]);
7107 if (slash.location == NSNotFound) {
7111 command = [path substringToIndex:slash.location];
7112 path = [path substringFromIndex:(slash.location + 1)];
7115 Database *database([Database sharedInstance]);
7117 if ([command isEqualToString:@"package-icon"]) {
7120 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7121 Package *package([database packageWithName:path]);
7124 UIImage *icon([package icon]);
7125 [self _returnPNGWithImage:icon forRequest:request];
7126 } else if ([command isEqualToString:@"source-icon"]) {
7129 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7130 NSString *source(Simplify(path));
7131 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7133 icon = [UIImage applicationImageNamed:@"unknown.png"];
7134 [self _returnPNGWithImage:icon forRequest:request];
7135 } else if ([command isEqualToString:@"uikit-image"]) {
7138 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7139 UIImage *icon(_UIImageWithName(path));
7140 [self _returnPNGWithImage:icon forRequest:request];
7141 } else if ([command isEqualToString:@"section-icon"]) {
7144 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7145 NSString *section(Simplify(path));
7146 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7148 icon = [UIImage applicationImageNamed:@"unknown.png"];
7149 [self _returnPNGWithImage:icon forRequest:request];
7151 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7155 - (void) stopLoading {
7161 /* Section Controller {{{ */
7162 @interface SectionController : FilteredPackageListController {
7163 _H<NSString> section_;
7166 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7170 @implementation SectionController
7172 - (NSURL *) navigationURL {
7173 NSString *name = section_;
7177 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7180 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7183 title = UCLocalize("ALL_PACKAGES");
7184 else if (![name isEqual:@""])
7185 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7187 title = UCLocalize("NO_SECTION");
7189 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7196 /* Sections Controller {{{ */
7197 @interface SectionsController : CYViewController <
7198 UITableViewDataSource,
7201 _transient Database *database_;
7202 NSMutableArray *sections_;
7203 NSMutableArray *filtered_;
7208 - (id) initWithDatabase:(Database *)database;
7209 - (void) editButtonClicked;
7213 @implementation SectionsController
7216 [self releaseSubviews];
7217 [sections_ release];
7218 [filtered_ release];
7223 - (NSURL *) navigationURL {
7224 return [NSURL URLWithString:@"cydia://sections"];
7227 - (void) updateNavigationItem {
7228 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7229 if ([sections_ count] == 0) {
7230 [[self navigationItem] setRightBarButtonItem:nil];
7232 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7233 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7235 action:@selector(editButtonClicked)
7236 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7240 - (BOOL) isEditing {
7244 - (void) setEditing:(BOOL)editing {
7245 if ((editing_ = editing))
7248 [delegate_ updateData];
7250 [self updateNavigationItem];
7253 - (void) viewDidAppear:(BOOL)animated {
7254 [super viewDidAppear:animated];
7255 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7258 - (void) viewWillDisappear:(BOOL)animated {
7259 [super viewWillDisappear:animated];
7260 if (editing_) [self setEditing:NO];
7263 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7264 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7268 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7269 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7272 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7276 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7277 static NSString *reuseIdentifier = @"SectionCell";
7279 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7281 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7283 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7288 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7292 Section *section = [self sectionAtIndexPath:indexPath];
7294 SectionController *controller = [[[SectionController alloc]
7295 initWithDatabase:database_
7296 section:[section name]
7298 [controller setDelegate:delegate_];
7300 [[self navigationController] pushViewController:controller animated:YES];
7304 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7306 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7307 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7308 [list_ setRowHeight:45.0f];
7309 [list_ setDataSource:self];
7310 [list_ setDelegate:self];
7311 [[self view] addSubview:list_];
7314 - (void) viewDidLoad {
7315 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7318 - (void) releaseSubviews {
7323 - (id) initWithDatabase:(Database *)database {
7324 if ((self = [super init]) != nil) {
7325 database_ = database;
7327 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7328 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7332 - (void) reloadData {
7335 NSArray *packages = [database_ packages];
7337 [sections_ removeAllObjects];
7338 [filtered_ removeAllObjects];
7340 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7343 for (Package *package in packages) {
7344 NSString *name([package section]);
7345 NSString *key(name == nil ? @"" : name);
7349 _profile(SectionsView$reloadData$Section)
7350 section = [sections objectForKey:key];
7351 if (section == nil) {
7352 _profile(SectionsView$reloadData$Section$Allocate)
7353 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7354 [sections setObject:section forKey:key];
7359 [section addToCount];
7361 _profile(SectionsView$reloadData$Filter)
7362 if (![package valid] || ![package visible])
7370 [sections_ addObjectsFromArray:[sections allValues]];
7372 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7374 for (Section *section in sections_) {
7375 size_t count([section row]);
7379 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7380 [section setCount:count];
7381 [filtered_ addObject:section];
7384 [self updateNavigationItem];
7389 - (void) editButtonClicked {
7390 [self setEditing:(!editing_)];
7396 /* Changes Controller {{{ */
7397 @interface ChangesController : CYViewController <
7398 UITableViewDataSource,
7401 _transient Database *database_;
7403 CFMutableArrayRef packages_;
7404 NSMutableArray *sections_;
7407 BOOL hasSentFirstLoad_;
7410 - (id) initWithDatabase:(Database *)database;
7414 @implementation ChangesController
7417 [self releaseSubviews];
7418 CFRelease(packages_);
7419 [sections_ release];
7424 - (NSURL *) navigationURL {
7425 return [NSURL URLWithString:@"cydia://changes"];
7428 - (void) viewWillAppear:(BOOL)animated {
7429 // Loads after it appears, so don't load beforehand.
7431 [super viewWillAppear:animated];
7434 - (void) viewDidAppear:(BOOL)animated {
7435 [super viewDidAppear:animated];
7437 if (!hasSentFirstLoad_) {
7438 hasSentFirstLoad_ = YES;
7439 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7441 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7445 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7446 NSInteger count([sections_ count]);
7447 return count == 0 ? 1 : count;
7450 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7451 if ([sections_ count] == 0)
7453 return [[sections_ objectAtIndex:section] name];
7456 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7457 if ([sections_ count] == 0)
7459 return [[sections_ objectAtIndex:section] count];
7462 - (Package *) packageAtIndex:(NSUInteger)index {
7463 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7466 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7467 @synchronized (database_) {
7468 if ([database_ era] != era_)
7471 NSUInteger sectionIndex([path section]);
7472 if (sectionIndex >= [sections_ count])
7474 Section *section([sections_ objectAtIndex:sectionIndex]);
7475 NSInteger row([path row]);
7476 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7479 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7480 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7482 cell = [[[PackageCell alloc] init] autorelease];
7483 [cell setPackage:[self packageAtIndexPath:path]];
7487 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7488 Package *package([self packageAtIndexPath:path]);
7489 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7490 [view setDelegate:delegate_];
7491 [[self navigationController] pushViewController:view animated:YES];
7495 - (void) refreshButtonClicked {
7496 [delegate_ beginUpdate];
7497 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7500 - (void) upgradeButtonClicked {
7501 [delegate_ distUpgrade];
7505 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7507 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7508 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7509 [list_ setRowHeight:73];
7510 [list_ setDataSource:self];
7511 [list_ setDelegate:self];
7512 [[self view] addSubview:list_];
7515 - (void) viewDidLoad {
7516 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7519 - (void) releaseSubviews {
7524 - (id) initWithDatabase:(Database *)database {
7525 if ((self = [super init]) != nil) {
7526 database_ = database;
7528 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7529 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7533 // this mostly works because reloadData (below) is @synchronized (database_)
7534 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7535 - (void) _reloadPackages:(NSArray *)packages {
7536 CFRelease(packages_);
7537 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7540 _profile(ChangesController$_reloadPackages$Filter)
7541 for (Package *package in packages)
7542 if ([package upgradableAndEssential:YES] || [package visible])
7543 CFArrayAppendValue(packages_, package);
7546 _profile(ChangesController$_reloadPackages$radixSort)
7547 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7552 - (void) reloadData {
7553 @synchronized (database_) {
7554 era_ = [database_ era];
7555 NSArray *packages = [database_ packages];
7557 [sections_ removeAllObjects];
7560 UIProgressHUD *hud([delegate_ addProgressHUD]);
7561 [hud setText:UCLocalize("LOADING")];
7562 //NSLog(@"HUD:%@::%@", delegate_, hud);
7563 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7564 [delegate_ removeProgressHUD:hud];
7566 [self _reloadPackages:packages];
7569 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7570 Section *ignored = nil;
7571 Section *section = nil;
7575 bool unseens = false;
7577 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7579 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7580 Package *package = [self packageAtIndex:offset];
7582 BOOL uae = [package upgradableAndEssential:YES];
7586 time_t seen([package seen]);
7588 if (section == nil || last != seen) {
7592 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7595 _profile(ChangesController$reloadData$Allocate)
7596 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7597 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7598 [sections_ addObject:section];
7602 [section addToCount];
7603 } else if ([package ignored]) {
7604 if (ignored == nil) {
7605 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7607 [ignored addToCount];
7610 [upgradable addToCount];
7615 CFRelease(formatter);
7618 Section *last = [sections_ lastObject];
7619 size_t count = [last count];
7620 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7621 [sections_ removeLastObject];
7624 if ([ignored count] != 0)
7625 [sections_ insertObject:ignored atIndex:0];
7627 [sections_ insertObject:upgradable atIndex:0];
7632 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7633 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7634 style:UIBarButtonItemStylePlain
7636 action:@selector(upgradeButtonClicked)
7639 if (![delegate_ updating])
7640 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7641 initWithTitle:UCLocalize("REFRESH")
7642 style:UIBarButtonItemStylePlain
7644 action:@selector(refreshButtonClicked)
7652 /* Search Controller {{{ */
7653 @interface SearchController : FilteredPackageListController <
7656 _H<UISearchBar> search_;
7660 - (id) initWithDatabase:(Database *)database;
7661 - (void) setSearchTerm:(NSString *)term;
7662 - (void) reloadData;
7666 @implementation SearchController
7669 [search_ setDelegate:nil];
7673 - (NSURL *) navigationURL {
7674 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7675 return [NSURL URLWithString:@"cydia://search"];
7677 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7680 - (void) setSearchTerm:(NSString *)searchTerm {
7681 [search_ setText:searchTerm];
7685 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7686 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7687 [search_ resignFirstResponder];
7691 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7692 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7696 - (id) initWithDatabase:(Database *)database {
7697 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7698 search_ = [[[UISearchBar alloc] init] autorelease];
7699 [search_ setDelegate:self];
7703 - (void) viewDidAppear:(BOOL)animated {
7704 [super viewDidAppear:animated];
7706 if (!searchloaded_) {
7707 searchloaded_ = YES;
7708 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7709 [search_ layoutSubviews];
7710 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7712 UITextField *textField;
7713 if ([search_ respondsToSelector:@selector(searchField)])
7714 textField = [search_ searchField];
7716 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7718 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7719 [textField setEnablesReturnKeyAutomatically:NO];
7720 [[self navigationItem] setTitleView:textField];
7724 - (void) reloadData {
7725 [self setObject:[search_ text]];
7730 - (void) didSelectPackage:(Package *)package {
7731 [search_ resignFirstResponder];
7732 [super didSelectPackage:package];
7737 /* Package Settings Controller {{{ */
7738 @interface PackageSettingsController : CYViewController <
7739 UITableViewDataSource,
7742 _transient Database *database_;
7745 UITableView *table_;
7746 UISwitch *subscribedSwitch_;
7747 UISwitch *ignoredSwitch_;
7748 UITableViewCell *subscribedCell_;
7749 UITableViewCell *ignoredCell_;
7752 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7756 @implementation PackageSettingsController
7759 [self releaseSubviews];
7766 - (NSURL *) navigationURL {
7767 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7770 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7771 if (package_ == nil)
7774 if ([package_ installed] == nil)
7780 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7781 if (package_ == nil)
7784 // both sections contain just one item right now.
7788 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7792 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7794 return UCLocalize("SHOW_ALL_CHANGES_EX");
7796 return UCLocalize("IGNORE_UPGRADES_EX");
7799 - (void) onSubscribed:(id)control {
7800 bool value([control isOn]);
7801 if (package_ == nil)
7803 if ([package_ setSubscribed:value])
7804 [delegate_ updateData];
7807 - (void) _updateIgnored {
7808 const char *package([name_ UTF8String]);
7809 bool on([ignoredSwitch_ isOn]);
7811 pid_t pid(ExecFork());
7813 FILE *dpkg(popen("dpkg --set-selections", "w"));
7814 fwrite(package, strlen(package), 1, dpkg);
7817 fwrite(" hold\n", 6, 1, dpkg);
7819 fwrite(" install\n", 9, 1, dpkg);
7829 int result(waitpid(pid, &status, 0));
7832 _assert(result == pid);
7838 - (void) onIgnored:(id)control {
7839 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7840 [invocation setTarget:self];
7841 [invocation setSelector:@selector(_updateIgnored)];
7843 [delegate_ reloadDataWithInvocation:invocation];
7846 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7847 if (package_ == nil)
7850 switch ([indexPath section]) {
7851 case 0: return subscribedCell_;
7852 case 1: return ignoredCell_;
7861 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7863 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7864 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7865 [table_ setDataSource:self];
7866 [table_ setDelegate:self];
7867 [[self view] addSubview:table_];
7869 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7870 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7871 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7873 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7874 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7875 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7877 subscribedCell_ = [[UITableViewCell alloc] init];
7878 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7879 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7880 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7882 ignoredCell_ = [[UITableViewCell alloc] init];
7883 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7884 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7885 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7888 - (void) viewDidLoad {
7889 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7892 - (void) releaseSubviews {
7893 [ignoredCell_ release];
7896 [subscribedCell_ release];
7897 subscribedCell_ = nil;
7902 [ignoredSwitch_ release];
7903 ignoredSwitch_ = nil;
7905 [subscribedSwitch_ release];
7906 subscribedSwitch_ = nil;
7909 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7910 if ((self = [super init]) != nil) {
7911 database_ = database;
7912 name_ = [package retain];
7916 - (void) reloadData {
7919 if (package_ != nil)
7920 [package_ autorelease];
7921 package_ = [database_ packageWithName:name_];
7923 if (package_ != nil) {
7924 package_ = [package_ retain];
7925 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7926 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7927 } // XXX: what now, G?
7929 [table_ reloadData];
7935 /* Installed Controller {{{ */
7936 @interface InstalledController : FilteredPackageListController {
7940 - (id) initWithDatabase:(Database *)database;
7942 - (void) updateRoleButton;
7943 - (void) queueStatusDidChange;
7947 @implementation InstalledController
7953 - (NSURL *) navigationURL {
7954 return [NSURL URLWithString:@"cydia://installed"];
7957 - (id) initWithDatabase:(Database *)database {
7958 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7959 [self updateRoleButton];
7960 [self queueStatusDidChange];
7965 - (void) queueButtonClicked {
7970 - (void) queueStatusDidChange {
7974 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7975 initWithTitle:UCLocalize("QUEUE")
7976 style:UIBarButtonItemStyleDone
7978 action:@selector(queueButtonClicked)
7981 [[self navigationItem] setLeftBarButtonItem:nil];
7987 - (void) updateRoleButton {
7988 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7989 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7990 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7991 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7993 action:@selector(roleButtonClicked)
7997 - (void) roleButtonClicked {
7998 [self setObject:[NSNumber numberWithBool:expert_]];
8002 [self updateRoleButton];
8008 /* Source Cell {{{ */
8009 @interface SourceCell : CYTableViewCell <
8017 - (void) setSource:(Source *)source;
8021 @implementation SourceCell
8023 - (void) clearSource {
8033 - (void) setSource:(Source *)source {
8037 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
8039 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8040 icon_ = [icon_ retain];
8042 origin_ = [[source name] retain];
8043 label_ = [[source uri] retain];
8045 [content_ setNeedsDisplay];
8053 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8054 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8055 UIView *content([self contentView]);
8056 CGRect bounds([content bounds]);
8058 content_ = [[ContentView alloc] initWithFrame:bounds];
8059 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8060 [content_ setBackgroundColor:[UIColor whiteColor]];
8061 [content addSubview:content_];
8063 [content_ setDelegate:self];
8064 [content_ setOpaque:YES];
8068 - (NSString *) accessibilityLabel {
8072 - (void) drawContentRect:(CGRect)rect {
8073 bool highlighted(highlighted_);
8074 float width(rect.size.width);
8077 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8084 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8088 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8093 /* Source Controller {{{ */
8094 @interface SourceController : FilteredPackageListController {
8095 _transient Source *source_;
8099 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8103 @implementation SourceController
8105 - (NSURL *) navigationURL {
8106 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8109 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8110 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8112 key_ = [[source key] retain];
8116 - (void) reloadData {
8117 source_ = [database_ sourceWithKey:key_];
8119 key_ = [[source_ key] retain];
8120 [self setObject:source_];
8121 [[self navigationItem] setTitle:[source_ label]];
8128 /* Sources Controller {{{ */
8129 @interface SourcesController : CYViewController <
8130 UITableViewDataSource,
8133 _transient Database *database_;
8135 NSMutableArray *sources_;
8139 UIProgressHUD *hud_;
8142 //NSURLConnection *installer_;
8143 NSURLConnection *trivial_;
8144 NSURLConnection *trivial_bz2_;
8145 NSURLConnection *trivial_gz_;
8146 //NSURLConnection *automatic_;
8151 - (id) initWithDatabase:(Database *)database;
8152 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8156 @implementation SourcesController
8158 - (void) _releaseConnection:(NSURLConnection *)connection {
8159 if (connection != nil) {
8160 [connection cancel];
8161 //[connection setDelegate:nil];
8162 [connection release];
8167 [self releaseSubviews];
8173 //[self _releaseConnection:installer_];
8174 [self _releaseConnection:trivial_];
8175 [self _releaseConnection:trivial_gz_];
8176 [self _releaseConnection:trivial_bz2_];
8177 //[self _releaseConnection:automatic_];
8183 - (NSURL *) navigationURL {
8184 return [NSURL URLWithString:@"cydia://sources"];
8187 - (void) viewDidAppear:(BOOL)animated {
8188 [super viewDidAppear:animated];
8189 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8192 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8193 return offset_ == 0 ? 1 : 2;
8196 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8197 switch (section + (offset_ == 0 ? 1 : 0)) {
8198 case 0: return UCLocalize("ENTERED_BY_USER");
8199 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8205 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8206 int count = [sources_ count];
8208 case 0: return (offset_ == 0 ? count : offset_);
8209 case 1: return count - offset_;
8215 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8217 switch (indexPath.section) {
8218 case 0: idx = indexPath.row; break;
8219 case 1: idx = indexPath.row + offset_; break;
8223 return [sources_ objectAtIndex:idx];
8226 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8227 static NSString *cellIdentifier = @"SourceCell";
8229 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8230 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8231 [cell setSource:[self sourceAtIndexPath:indexPath]];
8232 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8237 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8238 Source *source = [self sourceAtIndexPath:indexPath];
8240 SourceController *controller = [[[SourceController alloc]
8241 initWithDatabase:database_
8245 [controller setDelegate:delegate_];
8247 [[self navigationController] pushViewController:controller animated:YES];
8250 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8251 Source *source = [self sourceAtIndexPath:indexPath];
8252 return [source record] != nil;
8255 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8256 Source *source = [self sourceAtIndexPath:indexPath];
8257 [Sources_ removeObjectForKey:[source key]];
8258 [delegate_ syncData];
8262 [delegate_ addTrivialSource:href_];
8263 [delegate_ syncData];
8266 - (NSString *) getWarning {
8267 NSString *href(href_);
8268 NSRange colon([href rangeOfString:@"://"]);
8269 if (colon.location != NSNotFound)
8270 href = [href substringFromIndex:(colon.location + 3)];
8271 href = [href stringByAddingPercentEscapes];
8272 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8273 href = [href stringByCachingURLWithCurrentCDN];
8275 NSURL *url([NSURL URLWithString:href]);
8277 NSStringEncoding encoding;
8278 NSError *error(nil);
8280 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8281 return [warning length] == 0 ? nil : warning;
8285 - (void) _endConnection:(NSURLConnection *)connection {
8286 // XXX: the memory management in this method is horribly awkward
8288 NSURLConnection **field = NULL;
8289 if (connection == trivial_)
8291 else if (connection == trivial_bz2_)
8292 field = &trivial_bz2_;
8293 else if (connection == trivial_gz_)
8294 field = &trivial_gz_;
8295 _assert(field != NULL);
8296 [connection release];
8301 trivial_bz2_ == nil &&
8307 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8310 UIAlertView *alert = [[[UIAlertView alloc]
8311 initWithTitle:UCLocalize("SOURCE_WARNING")
8314 cancelButtonTitle:UCLocalize("CANCEL")
8316 UCLocalize("ADD_ANYWAY"),
8320 [alert setContext:@"warning"];
8321 [alert setNumberOfRows:1];
8325 } else if (error_ != nil) {
8326 UIAlertView *alert = [[[UIAlertView alloc]
8327 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8328 message:[error_ localizedDescription]
8330 cancelButtonTitle:UCLocalize("OK")
8331 otherButtonTitles:nil
8334 [alert setContext:@"urlerror"];
8337 UIAlertView *alert = [[[UIAlertView alloc]
8338 initWithTitle:UCLocalize("NOT_REPOSITORY")
8339 message:UCLocalize("NOT_REPOSITORY_EX")
8341 cancelButtonTitle:UCLocalize("OK")
8342 otherButtonTitles:nil
8345 [alert setContext:@"trivial"];
8349 [delegate_ releaseNetworkActivityIndicator];
8351 [delegate_ removeProgressHUD:hud_];
8360 if (error_ != nil) {
8367 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8368 switch ([response statusCode]) {
8374 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8375 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8377 error_ = [error retain];
8378 [self _endConnection:connection];
8381 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8382 [self _endConnection:connection];
8385 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8386 NSMutableURLRequest *request = [NSMutableURLRequest
8387 requestWithURL:[NSURL URLWithString:href]
8388 cachePolicy:NSURLRequestUseProtocolCachePolicy
8389 timeoutInterval:120.0
8392 [request setHTTPMethod:method];
8394 if (Machine_ != NULL)
8395 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8396 if (UniqueID_ != nil)
8397 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8399 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
8401 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8404 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8405 NSString *context([alert context]);
8407 if ([context isEqualToString:@"source"]) {
8410 NSString *href = [[alert textField] text];
8412 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8414 if (![href hasSuffix:@"/"])
8415 href_ = [href stringByAppendingString:@"/"];
8418 href_ = [href_ retain];
8420 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8421 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8422 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8423 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8427 // XXX: this is stupid
8428 hud_ = [[delegate_ addProgressHUD] retain];
8429 [hud_ setText:UCLocalize("VERIFYING_URL")];
8430 [delegate_ retainNetworkActivityIndicator];
8439 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8440 } else if ([context isEqualToString:@"trivial"])
8441 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8442 else if ([context isEqualToString:@"urlerror"])
8443 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8444 else if ([context isEqualToString:@"warning"]) {
8459 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8464 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8466 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8467 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8468 [list_ setRowHeight:56];
8469 [list_ setDataSource:self];
8470 [list_ setDelegate:self];
8471 [[self view] addSubview:list_];
8474 - (void) viewDidLoad {
8475 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8476 [self updateButtonsForEditingStatus:NO animated:NO];
8479 - (void) releaseSubviews {
8484 - (id) initWithDatabase:(Database *)database {
8485 if ((self = [super init]) != nil) {
8486 database_ = database;
8487 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8491 - (void) reloadData {
8495 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8498 [sources_ removeAllObjects];
8499 [sources_ addObjectsFromArray:[database_ sources]];
8501 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8504 int count([sources_ count]);
8506 for (int i = 0; i != count; i++) {
8507 if ([[sources_ objectAtIndex:i] record] == nil)
8512 [list_ setEditing:NO];
8513 [self updateButtonsForEditingStatus:NO animated:NO];
8517 - (void) showAddSourcePrompt {
8518 UIAlertView *alert = [[[UIAlertView alloc]
8519 initWithTitle:UCLocalize("ENTER_APT_URL")
8522 cancelButtonTitle:UCLocalize("CANCEL")
8524 UCLocalize("ADD_SOURCE"),
8528 [alert setContext:@"source"];
8529 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8531 [alert setNumberOfRows:1];
8532 [alert addTextFieldWithValue:@"http://" label:@""];
8534 UITextInputTraits *traits = [[alert textField] textInputTraits];
8535 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8536 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8537 [traits setKeyboardType:UIKeyboardTypeURL];
8538 // XXX: UIReturnKeyDone
8539 [traits setReturnKeyType:UIReturnKeyNext];
8544 - (void) addButtonClicked {
8545 [self showAddSourcePrompt];
8548 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8549 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8550 initWithTitle:UCLocalize("ADD")
8551 style:UIBarButtonItemStylePlain
8553 action:@selector(addButtonClicked)
8554 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8556 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8557 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8558 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8560 action:@selector(editButtonClicked)
8561 ] autorelease] animated:animated];
8563 if (IsWildcat_ && !editing)
8564 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8565 initWithTitle:UCLocalize("SETTINGS")
8566 style:UIBarButtonItemStylePlain
8568 action:@selector(settingsButtonClicked)
8572 - (void) settingsButtonClicked {
8573 [delegate_ showSettings];
8576 - (void) editButtonClicked {
8577 [list_ setEditing:![list_ isEditing] animated:YES];
8579 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8585 /* Settings Controller {{{ */
8586 @interface SettingsController : CYViewController <
8587 UITableViewDataSource,
8590 _transient Database *database_;
8591 // XXX: ok, "roledelegate_"?...
8592 _transient id roledelegate_;
8593 UITableView *table_;
8594 UISegmentedControl *segment_;
8598 - (void) showDoneButton;
8599 - (void) resizeSegmentedControl;
8603 @implementation SettingsController
8606 [self releaseSubviews];
8612 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8614 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8615 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8616 [table_ setDelegate:self];
8617 [table_ setDataSource:self];
8618 [[self view] addSubview:table_];
8620 NSArray *items = [NSArray arrayWithObjects:
8622 UCLocalize("HACKER"),
8623 UCLocalize("DEVELOPER"),
8625 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8626 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8627 [container_ addSubview:segment_];
8630 - (void) viewDidLoad {
8631 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8634 if ([Role_ isEqualToString:@"User"]) index = 0;
8635 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8636 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8638 [segment_ setSelectedSegmentIndex:index];
8639 [self showDoneButton];
8642 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8643 [self resizeSegmentedControl];
8646 - (void) releaseSubviews {
8653 [container_ release];
8657 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8658 if ((self = [super init]) != nil) {
8659 database_ = database;
8660 roledelegate_ = delegate;
8664 - (void) resizeSegmentedControl {
8665 CGFloat width = [[self view] frame].size.width;
8666 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8669 - (void) viewWillAppear:(BOOL)animated {
8670 [super viewWillAppear:animated];
8672 [self resizeSegmentedControl];
8675 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8676 [self resizeSegmentedControl];
8679 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8680 [self resizeSegmentedControl];
8684 NSString *role(nil);
8686 switch ([segment_ selectedSegmentIndex]) {
8687 case 0: role = @"User"; break;
8688 case 1: role = @"Hacker"; break;
8689 case 2: role = @"Developer"; break;
8694 if (![role isEqualToString:Role_]) {
8695 bool rolling(Role_ == nil);
8698 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8702 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8706 [roledelegate_ loadData];
8708 [roledelegate_ updateData];
8712 - (void) segmentChanged:(UISegmentedControl *)control {
8713 [self showDoneButton];
8716 - (void) saveAndClose {
8719 [[self navigationItem] setRightBarButtonItem:nil];
8720 [[self navigationController] dismissModalViewControllerAnimated:YES];
8723 - (void) doneButtonClicked {
8724 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8725 [spinner startAnimating];
8726 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8727 [[self navigationItem] setRightBarButtonItem:spinItem];
8729 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8732 - (void) showDoneButton {
8733 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8734 initWithTitle:UCLocalize("DONE")
8735 style:UIBarButtonItemStyleDone
8737 action:@selector(doneButtonClicked)
8738 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8741 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8742 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8746 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8750 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8751 return nil; // This method is required by the protocol.
8754 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8756 return UCLocalize("ROLE_EX");
8758 return [NSString stringWithFormat:
8759 @"%@: %@\n%@: %@\n%@: %@",
8760 UCLocalize("USER"), UCLocalize("USER_EX"),
8761 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8762 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8767 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8768 return section == 3 ? 44.0f : 0;
8771 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8772 return section == 3 ? container_ : nil;
8775 - (void) reloadData {
8777 [table_ reloadData];
8782 /* Stash Controller {{{ */
8783 @interface StashController : CYViewController {
8784 UIActivityIndicatorView *spinner_;
8791 @implementation StashController
8794 [self releaseSubviews];
8800 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8801 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8803 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8804 CGRect spinrect = [spinner_ frame];
8805 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8806 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8807 [spinner_ setFrame:spinrect];
8808 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8809 [[self view] addSubview:spinner_];
8810 [spinner_ startAnimating];
8813 captrect.size.width = [[self view] frame].size.width;
8814 captrect.size.height = 40.0f;
8815 captrect.origin.x = 0;
8816 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8817 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8818 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8819 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8820 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8821 [caption_ setTextColor:[UIColor whiteColor]];
8822 [caption_ setBackgroundColor:[UIColor clearColor]];
8823 [caption_ setShadowColor:[UIColor blackColor]];
8824 [caption_ setTextAlignment:UITextAlignmentCenter];
8825 [[self view] addSubview:caption_];
8828 statusrect.size.width = [[self view] frame].size.width;
8829 statusrect.size.height = 30.0f;
8830 statusrect.origin.x = 0;
8831 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8832 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8833 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8834 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8835 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8836 [status_ setTextColor:[UIColor whiteColor]];
8837 [status_ setBackgroundColor:[UIColor clearColor]];
8838 [status_ setShadowColor:[UIColor blackColor]];
8839 [status_ setTextAlignment:UITextAlignmentCenter];
8840 [[self view] addSubview:status_];
8843 - (void) releaseSubviews {
8857 @interface Cydia : UIApplication <
8858 ConfirmationControllerDelegate,
8861 UINavigationControllerDelegate,
8862 UITabBarControllerDelegate
8864 // XXX: evaluate all fields for _transient
8867 CYTabBarController *tabbar_;
8868 CYEmulatedLoadingController *emulated_;
8870 NSMutableArray *essential_;
8871 NSMutableArray *broken_;
8873 Database *database_;
8880 StashController *stash_;
8889 @implementation Cydia
8891 - (void) beginUpdate {
8892 [tabbar_ beginUpdate];
8896 return [tabbar_ updating];
8900 if ([broken_ count] != 0) {
8901 int count = [broken_ count];
8903 UIAlertView *alert = [[[UIAlertView alloc]
8904 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8905 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8907 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8909 UCLocalize("TEMPORARY_IGNORE"),
8913 [alert setContext:@"fixhalf"];
8914 [alert setNumberOfRows:2];
8916 } else if (!Ignored_ && [essential_ count] != 0) {
8917 int count = [essential_ count];
8919 UIAlertView *alert = [[[UIAlertView alloc]
8920 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8921 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8923 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8925 UCLocalize("UPGRADE_ESSENTIAL"),
8926 UCLocalize("COMPLETE_UPGRADE"),
8930 [alert setContext:@"upgrade"];
8935 - (void) _saveConfig {
8941 NSString *error(nil);
8943 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8945 NSError *error(nil);
8946 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8947 NSLog(@"failure to save metadata data: %@", error);
8952 NSLog(@"failure to serialize metadata: %@", error);
8957 // Navigation controller for the queuing badge.
8958 - (CYNavigationController *) queueNavigationController {
8959 NSArray *controllers = [tabbar_ viewControllers];
8960 return [controllers objectAtIndex:3];
8963 - (void) _updateData {
8966 [tabbar_ reloadData];
8968 CYNavigationController *navigation = [self queueNavigationController];
8970 id queuedelegate = nil;
8971 if ([[navigation viewControllers] count] > 0)
8972 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8974 [queuedelegate queueStatusDidChange];
8975 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8978 - (void) _refreshIfPossible:(NSDate *)update {
8979 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8981 bool recently = false;
8982 if (update != nil) {
8983 NSTimeInterval interval([update timeIntervalSinceNow]);
8984 if (interval <= 0 && interval > -(15*60))
8988 // Don't automatic refresh if:
8989 // - We already refreshed recently.
8990 // - We already auto-refreshed this launch.
8991 // - Auto-refresh is disabled.
8992 if (recently || loaded_ || ManualRefresh) {
8993 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8995 // If we are cancelling, we need to make sure it knows it's already loaded.
8999 // We are going to load, so remember that.
9003 SCNetworkReachabilityFlags flags; {
9004 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9005 SCNetworkReachabilityGetFlags(reachability, &flags);
9006 CFRelease(reachability);
9009 // XXX: this elaborate mess is what Apple is using to determine this? :(
9010 // XXX: do we care if the user has to intervene? maybe that's ok?
9012 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9013 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9014 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9015 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9016 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9017 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9021 // If we can reach the server, auto-refresh!
9023 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9028 - (void) refreshIfPossible {
9029 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9032 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
9033 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9034 [hud setText:UCLocalize("RELOADING_DATA")];
9036 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9039 [self removeProgressHUD:hud];
9043 [essential_ removeAllObjects];
9044 [broken_ removeAllObjects];
9046 NSArray *packages([database_ packages]);
9047 for (Package *package in packages) {
9049 [broken_ addObject:package];
9050 if ([package upgradableAndEssential:NO]) {
9051 if ([package essential])
9052 [essential_ addObject:package];
9057 NSLog(@"changes:#%u", changes);
9059 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9062 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9063 [changesItem setBadgeValue:badge];
9064 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9065 [self setApplicationIconBadgeNumber:changes];
9068 [changesItem setBadgeValue:nil];
9069 [changesItem setAnimatedBadge:NO];
9070 [self setApplicationIconBadgeNumber:0];
9075 [self refreshIfPossible];
9078 - (void) updateData {
9087 @synchronized (self) {
9088 [self _reloadDataWithInvocation:nil];
9092 - (void) disemulate {
9093 if (emulated_ == nil)
9096 [window_ addSubview:[tabbar_ view]];
9097 [[emulated_ view] removeFromSuperview];
9098 [emulated_ release];
9100 [window_ setUserInteractionEnabled:YES];
9103 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9104 UINavigationController *navigation([[[CYNavigationController alloc] initWithRootViewController:controller] autorelease]);
9106 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9108 UIViewController *parent;
9109 if (emulated_ == nil)
9118 [parent presentModalViewController:navigation animated:YES];
9121 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9122 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9124 if (navigation != nil)
9125 [navigation pushViewController:progress animated:YES];
9127 [self presentModalViewController:progress force:YES];
9129 [progress invoke:invocation withTitle:title];
9133 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9134 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9137 - (void) repairWithInvocation:(NSInvocation *)invocation {
9139 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9143 - (void) repairWithSelector:(SEL)selector {
9144 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9150 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
9151 _assert(file != NULL);
9153 for (NSString *key in [Sources_ allKeys]) {
9154 NSDictionary *source([Sources_ objectForKey:key]);
9156 fprintf(file, "%s %s %s\n",
9157 [[source objectForKey:@"Type"] UTF8String],
9158 [[source objectForKey:@"URI"] UTF8String],
9159 [[source objectForKey:@"Distribution"] UTF8String]
9165 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9170 - (void) addTrivialSource:(NSString *)href {
9171 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
9174 @"./", @"Distribution",
9175 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
9180 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9181 @synchronized (self) {
9182 [self _reloadDataWithInvocation:invocation];
9186 - (void) reloadData {
9187 [self reloadDataWithInvocation:nil];
9191 pkgProblemResolver *resolver = [database_ resolver];
9193 resolver->InstallProtect();
9194 if (!resolver->Resolve(true))
9199 // XXX: this is a really crappy way of doing this.
9200 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9201 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9202 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9203 if ([tabbar_ updating])
9204 [tabbar_ cancelUpdate];
9206 if (![database_ prepare])
9209 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9210 [page setDelegate:self];
9211 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
9212 [confirm_ setDelegate:self];
9215 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9216 [tabbar_ presentModalViewController:confirm_ animated:YES];
9222 @synchronized (self) {
9227 - (void) clearPackage:(Package *)package {
9228 @synchronized (self) {
9235 - (void) installPackages:(NSArray *)packages {
9236 @synchronized (self) {
9237 for (Package *package in packages)
9244 - (void) installPackage:(Package *)package {
9245 @synchronized (self) {
9252 - (void) removePackage:(Package *)package {
9253 @synchronized (self) {
9260 - (void) distUpgrade {
9261 @synchronized (self) {
9262 if (![database_ upgrade])
9268 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9271 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
9276 - (void) showSettings {
9277 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9278 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9280 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9281 [tabbar_ presentModalViewController:nav animated:YES];
9284 - (void) retainNetworkActivityIndicator {
9285 if (activity_++ == 0)
9286 [self setNetworkActivityIndicatorVisible:YES];
9289 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9293 - (void) releaseNetworkActivityIndicator {
9294 if (--activity_ == 0)
9295 [self setNetworkActivityIndicatorVisible:NO];
9298 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9303 - (void) cancelAndClear:(bool)clear {
9304 @synchronized (self) {
9316 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9317 NSString *context([alert context]);
9319 if ([context isEqualToString:@"conffile"]) {
9320 FILE *input = [database_ input];
9321 if (button == [alert cancelButtonIndex])
9322 fprintf(input, "N\n");
9323 else if (button == [alert firstOtherButtonIndex])
9324 fprintf(input, "Y\n");
9327 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9328 } else if ([context isEqualToString:@"fixhalf"]) {
9329 if (button == [alert cancelButtonIndex]) {
9330 @synchronized (self) {
9331 for (Package *broken in broken_) {
9334 NSString *id = [broken id];
9335 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9336 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9337 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9338 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9344 } else if (button == [alert firstOtherButtonIndex]) {
9345 [broken_ removeAllObjects];
9349 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9350 } else if ([context isEqualToString:@"upgrade"]) {
9351 if (button == [alert firstOtherButtonIndex]) {
9352 @synchronized (self) {
9353 for (Package *essential in essential_)
9354 [essential install];
9359 } else if (button == [alert firstOtherButtonIndex] + 1) {
9361 } else if (button == [alert cancelButtonIndex]) {
9365 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9369 - (void) system:(NSString *)command { _pooled
9371 system([command UTF8String]);
9375 - (void) applicationWillSuspend {
9377 [super applicationWillSuspend];
9380 - (BOOL) isSafeToSuspend {
9383 NSLog(@"isSafeToSuspend: locked_ != 0");
9388 // Use external process status API internally.
9389 // This is probably a really bad idea.
9390 // XXX: what is the point of this? does this solve anything at all?
9391 uint64_t status = 0;
9393 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9394 notify_get_state(notify_token, &status);
9395 notify_cancel(notify_token);
9400 NSLog(@"isSafeToSuspend: status != 0");
9406 NSLog(@"isSafeToSuspend: -> true");
9411 - (void) applicationSuspend:(__GSEvent *)event {
9412 if ([self isSafeToSuspend])
9413 [super applicationSuspend:event];
9416 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9417 if ([self isSafeToSuspend])
9418 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9421 - (void) _setSuspended:(BOOL)value {
9422 if ([self isSafeToSuspend])
9423 [super _setSuspended:value];
9426 - (UIProgressHUD *) addProgressHUD {
9427 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9428 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9430 [window_ setUserInteractionEnabled:NO];
9433 UIViewController *target = tabbar_;
9434 while ([target modalViewController] != nil) target = [target modalViewController];
9435 [[target view] addSubview:hud];
9441 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9443 [hud removeFromSuperview];
9444 [window_ setUserInteractionEnabled:YES];
9448 - (CYViewController *) pageForPackage:(NSString *)name {
9449 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9452 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9453 NSString *scheme([[url scheme] lowercaseString]);
9454 if ([[url absoluteString] length] <= [scheme length] + 3)
9456 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9457 NSArray *components([path pathComponents]);
9459 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9460 return [self pageForPackage:[components objectAtIndex:1]];
9462 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9465 NSString *base([components objectAtIndex:0]);
9467 CYViewController *controller = nil;
9469 if ([base isEqualToString:@"url"]) {
9470 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9471 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9472 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9473 } else if (!external && [components count] == 1) {
9474 if ([base isEqualToString:@"manage"]) {
9475 controller = [[[ManageController alloc] init] autorelease];
9478 if ([base isEqualToString:@"sources"]) {
9479 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9482 if ([base isEqualToString:@"home"]) {
9483 controller = [[[HomeController alloc] init] autorelease];
9486 if ([base isEqualToString:@"sections"]) {
9487 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9490 if ([base isEqualToString:@"search"]) {
9491 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9494 if ([base isEqualToString:@"changes"]) {
9495 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9498 if ([base isEqualToString:@"installed"]) {
9499 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9501 } else if ([components count] == 2) {
9502 NSString *argument = [components objectAtIndex:1];
9504 if ([base isEqualToString:@"package"]) {
9505 controller = [self pageForPackage:argument];
9508 if (!external && [base isEqualToString:@"search"]) {
9509 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9510 [(SearchController *)controller setSearchTerm:argument];
9513 if (!external && [base isEqualToString:@"sections"]) {
9514 if ([argument isEqualToString:@"all"])
9516 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9519 if (!external && [base isEqualToString:@"sources"]) {
9520 if ([argument isEqualToString:@"add"]) {
9521 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9522 [(SourcesController *)controller showAddSourcePrompt];
9524 Source *source = [database_ sourceWithKey:argument];
9525 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9529 if (!external && [base isEqualToString:@"launch"]) {
9530 [self launchApplicationWithIdentifier:argument suspended:NO];
9533 } else if (!external && [components count] == 3) {
9534 NSString *arg1 = [components objectAtIndex:1];
9535 NSString *arg2 = [components objectAtIndex:2];
9537 if ([base isEqualToString:@"package"]) {
9538 if ([arg2 isEqualToString:@"settings"]) {
9539 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9540 } else if ([arg2 isEqualToString:@"files"]) {
9541 if (Package *package = [database_ packageWithName:arg1]) {
9542 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9543 [(FileTable *)controller setPackage:package];
9549 [controller setDelegate:self];
9553 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9554 CYViewController *page([self pageForURL:url forExternal:external]);
9557 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9558 [nav setViewControllers:[NSArray arrayWithObject:page]];
9559 [tabbar_ setUnselectedViewController:nav];
9565 - (void) applicationOpenURL:(NSURL *)url {
9566 [super applicationOpenURL:url];
9568 if (!loaded_) starturl_ = [url retain];
9569 else [self openCydiaURL:url forExternal:YES];
9572 - (void) applicationWillResignActive:(UIApplication *)application {
9573 // Stop refreshing if you get a phone call or lock the device.
9574 if ([tabbar_ updating])
9575 [tabbar_ cancelUpdate];
9577 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9578 [super applicationWillResignActive:application];
9581 - (void) applicationWillTerminate:(UIApplication *)application {
9583 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9584 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9585 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9590 - (void) setConfigurationData:(NSString *)data {
9591 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9593 if (!conffile_r(data)) {
9594 lprintf("E:invalid conffile\n");
9598 NSString *ofile = conffile_r[1];
9599 //NSString *nfile = conffile_r[2];
9601 UIAlertView *alert = [[[UIAlertView alloc]
9602 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9603 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9605 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9607 UCLocalize("ACCEPT_NEW_COPY"),
9608 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9612 [alert setContext:@"conffile"];
9613 [alert setNumberOfRows:2];
9617 - (void) addStashController {
9619 stash_ = [[StashController alloc] init];
9620 [window_ addSubview:[stash_ view]];
9623 - (void) removeStashController {
9624 [[stash_ view] removeFromSuperview];
9630 [self setIdleTimerDisabled:YES];
9632 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9633 UpdateExternalStatus(1);
9634 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9635 UpdateExternalStatus(0);
9637 [self removeStashController];
9639 if (ExecFork() == 0) {
9640 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9641 perror("launchctl stop");
9645 - (void) setupViewControllers {
9646 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9648 NSMutableArray *items([NSMutableArray arrayWithObjects:
9649 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9650 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9651 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9652 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9656 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9657 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9659 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9662 NSMutableArray *controllers([NSMutableArray array]);
9663 for (UITabBarItem *item in items) {
9664 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9665 [controller setTabBarItem:item];
9666 [controllers addObject:controller];
9668 [tabbar_ setViewControllers:controllers];
9670 [tabbar_ setUpdateDelegate:self];
9673 - (void) addCydiaHost:(NSString *)host {
9674 [CydiaHosts_ addObject:host];
9677 - (void) applicationDidFinishLaunching:(id)unused {
9679 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9680 [self setApplicationSupportsShakeToEdit:NO];
9682 [self addCydiaHost:[[NSURL URLWithString:CydiaURL(@"")] host]];
9684 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9685 initWithMemoryCapacity:524288
9686 diskCapacity:10485760
9687 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9690 [CYBrowserController _initialize];
9692 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9694 Font12_ = [[UIFont systemFontOfSize:12] retain];
9695 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9696 Font14_ = [[UIFont systemFontOfSize:14] retain];
9697 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9698 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9700 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9701 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9703 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9704 [window_ orderFront:self];
9705 [window_ makeKey:self];
9706 [window_ setHidden:NO];
9709 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9710 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9711 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9712 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9713 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9714 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9715 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9716 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9717 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9720 [self addStashController];
9721 // XXX: this would be much cleaner as a yieldToSelector:
9722 // that way the removeStashController could happen right here inline
9723 // we also could no longer require the useless stash_ field anymore
9724 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9728 database_ = [Database sharedInstance];
9729 [database_ setDelegate:self];
9731 [window_ setUserInteractionEnabled:NO];
9732 [self setupViewControllers];
9734 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9735 [window_ addSubview:[emulated_ view]];
9737 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9744 [window_ setUserInteractionEnabled:YES];
9745 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9748 if ([emulated_ modalViewController] != nil)
9749 [emulated_ dismissModalViewControllerAnimated:YES];
9750 [window_ setUserInteractionEnabled:NO];
9758 int selectedIndex = 0;
9759 NSMutableArray *items = nil;
9761 bool recently = false;
9762 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9763 if (closed != nil) {
9764 NSTimeInterval interval([closed timeIntervalSinceNow]);
9765 // XXX: Is 15 minutes the optimal time here?
9766 if (interval <= 0 && interval > -(15*60))
9770 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9771 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9774 for (NSArray *entry in items)
9775 if ([entry count] <= 0)
9778 if (!recently || !items || !enough) {
9780 items = [NSMutableArray array];
9781 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9782 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9783 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9785 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9787 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9788 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9790 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9793 [tabbar_ setSelectedIndex:selectedIndex];
9794 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9795 NSArray *stack = [items objectAtIndex:tab];
9796 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9797 NSMutableArray *current = [NSMutableArray array];
9799 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9800 NSString *addr = [stack objectAtIndex:nav];
9801 NSURL *url = [NSURL URLWithString:addr];
9802 CYViewController *page = [self pageForURL:url forExternal:NO];
9804 [current addObject:page];
9807 [navigation setViewControllers:current];
9810 // (Try to) show the startup URL.
9811 if (starturl_ != nil) {
9812 [self openCydiaURL:starturl_ forExternal:NO];
9813 [starturl_ release];
9818 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9819 if (item != nil && IsWildcat_) {
9820 [sheet showFromBarButtonItem:item animated:YES];
9822 [sheet showInView:window_];
9826 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9827 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9828 [progress setTitle:task];
9829 [progress addProgressEvent:event];
9832 - (void) addProgressEventForTask:(NSArray *)data {
9833 CydiaProgressEvent *event([data objectAtIndex:0]);
9834 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9835 [self addProgressEvent:event forTask:task];
9838 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9839 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9845 id Alloc_(id self, SEL selector) {
9846 id object = alloc_(self, selector);
9847 lprintf("[%s]A-%p\n", self->isa->name, object);
9852 id Dealloc_(id self, SEL selector) {
9853 id object = dealloc_(self, selector);
9854 lprintf("[%s]D-%p\n", self->isa->name, object);
9858 Class $WebDefaultUIKitDelegate;
9860 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9861 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9862 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9863 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9866 static NSNumber *shouldPlayKeyboardSounds;
9870 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9872 case 1104: // Keyboard Button Clicked
9873 case 1105: // Keyboard Delete Repeated
9874 if (shouldPlayKeyboardSounds == nil) {
9875 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9876 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9879 if (![shouldPlayKeyboardSounds boolValue])
9883 _UIHardware$_playSystemSound$(self, _cmd, sound);
9887 Class $UIApplication;
9889 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9890 static BOOL initialized = NO;
9891 static BOOL started = NO;
9893 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9894 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9896 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9897 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9898 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9899 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9901 if (initialized && !enabled) {
9903 [bundle performSelector:@selector(_accessibilityStopServer)];
9904 } else if (enabled) {
9908 [bundle performSelector:@selector(_accessibilityStartServer)];
9914 int main(int argc, char *argv[]) { _pooled
9917 UpdateExternalStatus(0);
9919 if (Class $UIDevice = objc_getClass("UIDevice")) {
9920 UIDevice *device([$UIDevice currentDevice]);
9921 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9925 UIScreen *screen([UIScreen mainScreen]);
9926 if ([screen respondsToSelector:@selector(scale)])
9927 ScreenScale_ = [screen scale];
9931 UIDevice *device([UIDevice currentDevice]);
9932 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9935 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9936 if (idiom == UIUserInterfaceIdiomPhone)
9938 else if (idiom == UIUserInterfaceIdiomPad)
9941 NSLog(@"unknown UIUserInterfaceIdiom!");
9944 CydiaHosts_ = [NSMutableSet setWithCapacity:2];
9946 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9948 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9950 /* Library Hacks {{{ */
9951 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9953 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9954 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9955 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9956 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9957 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9960 $UIHardware = objc_getClass("UIHardware");
9961 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9962 if (UIHardware$_playSystemSound$ != NULL) {
9963 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9964 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9967 $UIApplication = objc_getClass("UIApplication");
9968 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9969 if (UIApplication$_updateApplicationAccessibility != NULL) {
9970 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9971 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9974 /* Set Locale {{{ */
9975 Locale_ = CFLocaleCopyCurrent();
9976 Languages_ = [NSLocale preferredLanguages];
9977 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9978 //NSLog(@"%@", [Languages_ description]);
9981 if (Languages_ == nil || [Languages_ count] == 0)
9982 // XXX: consider just setting to C and then falling through?
9985 lang = [[Languages_ objectAtIndex:0] UTF8String];
9986 setenv("LANG", lang, true);
9987 std::setlocale(LC_ALL, lang);
9990 NSLog(@"Setting Language: %s", lang);
9993 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9995 /* Parse Arguments {{{ */
9996 bool substrate(false);
10002 for (int argi(1); argi != argc; ++argi)
10003 if (strcmp(argv[argi], "--") == 0) {
10005 argv[argi] = argv[0];
10011 for (int argi(1); argi != arge; ++argi)
10012 if (strcmp(args[argi], "--substrate") == 0)
10015 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10019 App_ = [[NSBundle mainBundle] bundlePath];
10025 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10026 alloc_ = alloc->method_imp;
10027 alloc->method_imp = (IMP) &Alloc_;*/
10029 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10030 dealloc_ = dealloc->method_imp;
10031 dealloc->method_imp = (IMP) &Dealloc_;*/
10033 /* System Information {{{ */
10037 size = sizeof(maxproc);
10038 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10039 perror("sysctlbyname(\"kern.maxproc\", ?)");
10040 else if (maxproc < 64) {
10042 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10043 perror("sysctlbyname(\"kern.maxproc\", #)");
10046 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10047 char *osversion = new char[size];
10048 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10049 perror("sysctlbyname(\"kern.osversion\", ?)");
10051 System_ = [NSString stringWithUTF8String:osversion];
10053 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10054 char *machine = new char[size];
10055 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10056 perror("sysctlbyname(\"hw.machine\", ?)");
10058 Machine_ = machine;
10060 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
10061 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
10062 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
10063 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
10067 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
10068 NSData *data((NSData *) ecid);
10069 size_t length([data length]);
10070 uint8_t bytes[length];
10071 [data getBytes:bytes];
10072 char string[length * 2 + 1];
10073 for (size_t i(0); i != length; ++i)
10074 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
10075 ChipID_ = [NSString stringWithUTF8String:string];
10079 IOObjectRelease(service);
10083 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
10085 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10086 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10087 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10089 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10090 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10091 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10093 if (mcc != NULL && mnc != NULL)
10094 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10101 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10102 Build_ = [system objectForKey:@"ProductBuildVersion"];
10103 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10104 Product_ = [info objectForKey:@"SafariProductVersion"];
10105 Safari_ = [info objectForKey:@"CFBundleVersion"];
10108 /* Load Database {{{ */
10110 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10112 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10114 if (Metadata_ == NULL)
10115 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10117 Settings_ = [Metadata_ objectForKey:@"Settings"];
10119 Packages_ = [Metadata_ objectForKey:@"Packages"];
10120 Sections_ = [Metadata_ objectForKey:@"Sections"];
10121 Sources_ = [Metadata_ objectForKey:@"Sources"];
10123 Token_ = [Metadata_ objectForKey:@"Token"];
10126 if (Settings_ != nil)
10127 Role_ = [Settings_ objectForKey:@"Role"];
10129 if (Sections_ == nil) {
10130 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10131 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10134 if (Sources_ == nil) {
10135 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10136 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10141 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10144 if (Packages_ != nil) {
10146 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10150 [Metadata_ removeObjectForKey:@"Packages"];
10156 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10158 #define MobileSubstrate_(name) \
10159 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10160 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10161 if (handle == NULL) \
10162 NSLog(@"%s", dlerror()); \
10165 MobileSubstrate_(Activator)
10166 MobileSubstrate_(libstatusbar)
10167 MobileSubstrate_(SimulatedKeyEvents)
10168 MobileSubstrate_(WinterBoard)
10170 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10171 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10173 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10175 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10176 unlink("/tmp/.cydia.fw");
10178 } else if (access("/User", F_OK) != 0 || version < 4) {
10181 system("/usr/libexec/cydia/firmware.sh");
10185 _assert([[NSFileManager defaultManager]
10186 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10187 withIntermediateDirectories:YES
10192 if (access("/tmp/cydia.chk", F_OK) == 0) {
10193 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10194 _assert(errno == ENOENT);
10195 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10196 _assert(errno == ENOENT);
10199 /* APT Initialization {{{ */
10200 _assert(pkgInitConfig(*_config));
10201 _assert(pkgInitSystem(*_config, _system));
10204 _config->Set("APT::Acquire::Translation", lang);
10206 // XXX: this timeout might be important :(
10207 //_config->Set("Acquire::http::Timeout", 15);
10209 _config->Set("Acquire::http::MaxParallel", 3);
10211 /* Color Choices {{{ */
10212 space_ = CGColorSpaceCreateDeviceRGB();
10214 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10215 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10216 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10217 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10218 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10219 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10220 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10221 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10222 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10224 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10225 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10227 /* UIKit Configuration {{{ */
10228 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10229 if ($GSFontSetUseLegacyFontMetrics != NULL)
10230 $GSFontSetUseLegacyFontMetrics(YES);
10232 // XXX: I have a feeling this was important
10233 //UIKeyboardDisableAutomaticAppearance();
10236 Colon_ = UCLocalize("COLON_DELIMITED");
10237 Elision_ = UCLocalize("ELISION");
10238 Error_ = UCLocalize("ERROR");
10239 Warning_ = UCLocalize("WARNING");
10242 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10244 CGColorSpaceRelease(space_);
10245 CFRelease(Locale_);