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"
134 #define _timestamp ({ \
136 gettimeofday(&tv, NULL); \
137 tv.tv_sec * 1000000 + tv.tv_usec; \
140 typedef std::vector<class ProfileTime *> TimeList;
150 ProfileTime(const char *name) :
154 times_.push_back(this);
157 void AddTime(uint64_t time) {
164 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
176 ProfileTimer(ProfileTime &time) :
183 time_.AddTime(_timestamp - start_);
188 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
190 std::cerr << "========" << std::endl;
193 #define _profile(name) { \
194 static ProfileTime name(#name); \
195 ProfileTimer _ ## name(name);
200 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
202 #define CYPoolStart() \
203 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
205 #define CYPoolEnd() \
209 #define Cydia_ CYDIA_VERSION
211 #define lprintf(args...) fprintf(stderr, args)
214 #define TraceLogging (1 && !ForRelease)
215 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
216 #define ProfileTimes (0 && !ForRelease)
217 #define ForSaurik (0 && !ForRelease)
218 #define LogBrowser (0 && !ForRelease)
219 #define TrackResize (0 && !ForRelease)
220 #define ManualRefresh (1 && !ForRelease)
221 #define ShowInternals (0 && !ForRelease)
222 #define AlwaysReload (0 && !ForRelease)
223 #define TryIndexedCollation (0 && !ForRelease)
227 #define _trace(args...)
232 #define _profile(name) {
235 #define PrintTimes() do {} while (false)
238 // Hash Functions/Structures {{{
239 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
247 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
249 static _finline NSString *CydiaURL(NSString *path) {
251 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
252 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
253 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
254 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
255 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
257 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
260 static _finline void UpdateExternalStatus(uint64_t newStatus) {
262 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
263 notify_set_state(notify_token, newStatus);
264 notify_cancel(notify_token);
266 notify_post("com.saurik.Cydia.status");
269 /* [NSObject yieldToSelector:(withObject:)] {{{*/
270 @interface NSObject (Cydia)
271 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
272 - (id) yieldToSelector:(SEL)selector;
275 @implementation NSObject (Cydia)
280 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
281 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
282 id object([[context objectAtIndex:1] nonretainedObjectValue]);
283 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
285 /* XXX: deal with exceptions */
286 id value([self performSelector:selector withObject:object]);
288 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
289 [context removeAllObjects];
290 if ([signature methodReturnLength] != 0 && value != nil)
291 [context addObject:value];
296 performSelectorOnMainThread:@selector(doNothing)
302 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
303 volatile bool stopped(false);
305 NSMutableArray *context([NSMutableArray arrayWithObjects:
306 [NSValue valueWithPointer:selector],
307 [NSValue valueWithNonretainedObject:object],
308 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
311 NSThread *thread([[[NSThread alloc]
313 selector:@selector(_yieldToContext:)
319 NSRunLoop *loop([NSRunLoop currentRunLoop]);
320 NSDate *future([NSDate distantFuture]);
321 NSString *mode([loop currentMode] ?: NSDefaultRunLoopMode);
324 while (!stopped && [loop runMode:mode beforeDate:future]);
327 return [context count] == 0 ? nil : [context objectAtIndex:0];
330 - (id) yieldToSelector:(SEL)selector {
331 return [self yieldToSelector:selector withObject:nil];
337 /* Cydia Alert View {{{ */
338 @interface CYAlertView : UIAlertView {
342 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
346 @implementation CYAlertView
348 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
349 if ((self = [super init]) != nil) {
350 [self setTitle:title];
351 [self setDelegate:self];
352 for (NSString *button in buttons) [self addButtonWithTitle:button];
353 [self setCancelButtonIndex:index];
357 - (void) _updateFrameForDisplay {
358 [super _updateFrameForDisplay];
359 if ([self cancelButtonIndex] == -1) {
360 NSArray *buttons = [self buttons];
361 if ([buttons count]) {
362 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
363 for (UIThreePartButton *button in buttons)
364 [button setBackground:background forState:0];
369 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
370 button_ = buttonIndex + 1;
374 [self dismissWithClickedButtonIndex:-1 animated:YES];
377 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
378 [self setRunsModal:YES];
387 /* NSForcedOrderingSearch doesn't work on the iPhone */
388 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
389 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
390 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
393 typedef uint32_t (*SKRadixFunction)(id, void *);
395 @interface NSMutableArray (Radix)
396 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
404 @implementation NSMutableArray (Radix)
406 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
407 size_t count([self count]);
408 struct RadixItem_ *swap(new RadixItem_[count * 2]);
410 for (size_t i(0); i != count; ++i) {
411 RadixItem_ &item(swap[i]);
414 id object([self objectAtIndex:i]);
415 item.key = function(object, argument);
418 struct RadixItem_ *lhs(swap), *rhs(swap + count);
420 static const size_t width = 32;
421 static const size_t bits = 11;
422 static const size_t slots = 1 << bits;
423 static const size_t passes = (width + (bits - 1)) / bits;
425 size_t *hist(new size_t[slots]);
427 for (size_t pass(0); pass != passes; ++pass) {
428 memset(hist, 0, sizeof(size_t) * slots);
430 for (size_t i(0); i != count; ++i) {
431 uint32_t key(lhs[i].key);
433 key &= _not(uint32_t) >> width - bits;
438 for (size_t i(0); i != slots; ++i) {
439 size_t local(offset);
444 for (size_t i(0); i != count; ++i) {
445 uint32_t key(lhs[i].key);
447 key &= _not(uint32_t) >> width - bits;
448 rhs[hist[key]++] = lhs[i];
451 RadixItem_ *tmp(lhs);
458 const void **values(new const void *[count]);
459 for (size_t i(0); i != count; ++i)
460 values[i] = [self objectAtIndex:lhs[i].index];
461 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
469 /* Insertion Sort {{{ */
471 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
472 const char *ptr = (const char *)list;
474 CFIndex half = count / 2;
475 const char *probe = ptr + elementSize * half;
476 CFComparisonResult cr = comparator(element, probe, context);
477 if (0 == cr) return (probe - (const char *)list) / elementSize;
478 ptr = (cr < 0) ? ptr : probe + elementSize;
479 count = (cr < 0) ? half : (half + (count & 1) - 1);
481 return (ptr - (const char *)list) / elementSize;
484 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
485 const char *ptr = (const char *)list;
487 CFIndex half = count / 2;
488 const char *probe = ptr + elementSize * half;
489 CFComparisonResult cr = comparator(element, probe, context);
490 if (0 == cr) return (probe - (const char *)list) / elementSize;
491 ptr = (cr < 0) ? ptr : probe + elementSize;
492 count = (cr < 0) ? half : (half + (count & 1) - 1);
494 return (ptr - (const char *)list) / elementSize;
497 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
498 if (range.length == 0)
500 const void **values(new const void *[range.length]);
501 CFArrayGetValues(array, range, values);
503 #if HistogramInsertionSort > 0
504 uint32_t total(0), *offsets(new uint32_t[range.length]);
507 for (CFIndex index(1); index != range.length; ++index) {
508 const void *value(values[index]);
509 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
510 CFIndex correct(index);
511 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
512 #if HistogramInsertionSort > 1
513 NSLog(@"%@ < %@", value, values[correct - 1]);
518 if (correct != index) {
519 size_t offset(index - correct);
520 #if HistogramInsertionSort
524 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
526 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
527 values[correct] = value;
531 CFArrayReplaceValues(array, range, values, range.length);
534 #if HistogramInsertionSort > 0
535 for (CFIndex index(0); index != range.length; ++index)
536 if (offsets[index] != 0)
537 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
538 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
545 /* Apple Bug Fixes {{{ */
546 @implementation UIWebDocumentView (Cydia)
548 - (void) _setScrollerOffset:(CGPoint)offset {
549 UIScroller *scroller([self _scroller]);
551 CGSize size([scroller contentSize]);
552 CGSize bounds([scroller bounds].size);
555 max.x = size.width - bounds.width;
556 max.y = size.height - bounds.height;
564 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
565 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
567 [scroller setOffset:offset];
573 @interface NSInvocation (Cydia)
574 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target;
577 @implementation NSInvocation (Cydia)
579 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target {
580 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[target methodSignatureForSelector:selector]]);
581 [invocation setTarget:target];
582 [invocation setSelector:selector];
588 @implementation WebScriptObject (NSFastEnumeration)
590 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
591 size_t length([self count] - state->state);
594 else if (length > count)
596 for (size_t i(0); i != length; ++i)
597 objects[i] = [self objectAtIndex:state->state++];
598 state->itemsPtr = objects;
599 state->mutationsPtr = (unsigned long *) self;
605 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
606 size_t length([self length] - state->state);
609 else if (length > count)
611 for (size_t i(0); i != length; ++i)
612 objects[i] = [self item:state->state++];
613 state->itemsPtr = objects;
614 state->mutationsPtr = (unsigned long *) self;
618 /* Cydia NSString Additions {{{ */
619 @interface NSString (Cydia)
620 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
621 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
622 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
623 - (NSComparisonResult) compareByPath:(NSString *)other;
624 - (NSString *) stringByCachingURLWithCurrentCDN;
625 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
628 @implementation NSString (Cydia)
630 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
631 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
634 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
635 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
636 memcpy(data, bytes, length);
637 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
640 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
641 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
644 - (NSComparisonResult) compareByPath:(NSString *)other {
645 NSString *prefix = [self commonPrefixWithString:other options:0];
646 size_t length = [prefix length];
648 NSRange lrange = NSMakeRange(length, [self length] - length);
649 NSRange rrange = NSMakeRange(length, [other length] - length);
651 lrange = [self rangeOfString:@"/" options:0 range:lrange];
652 rrange = [other rangeOfString:@"/" options:0 range:rrange];
654 NSComparisonResult value;
656 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
657 value = NSOrderedSame;
658 else if (lrange.location == NSNotFound)
659 value = NSOrderedAscending;
660 else if (rrange.location == NSNotFound)
661 value = NSOrderedDescending;
663 value = NSOrderedSame;
665 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
666 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
667 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
668 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
670 NSComparisonResult result = [lpath compare:rpath];
671 return result == NSOrderedSame ? value : result;
674 - (NSString *) stringByCachingURLWithCurrentCDN {
676 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
677 withString:@"://cache.cydia.saurik.com/"
681 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
682 return [(id)CFURLCreateStringByAddingPercentEscapes(
687 kCFStringEncodingUTF8
694 /* C++ NSString Wrapper Cache {{{ */
695 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
696 return size == 0 ? NULL :
697 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
698 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
701 static _finline CFStringRef CYStringCreate(const char *data) {
702 return CYStringCreate(data, strlen(data));
711 _finline void clear_() {
712 if (cache_ != NULL) {
719 _finline bool empty() const {
723 _finline size_t size() const {
727 _finline char *data() const {
731 _finline void clear() {
736 _finline CYString() :
743 _finline ~CYString() {
747 void operator =(const CYString &rhs) {
751 if (rhs.cache_ == nil)
754 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
757 void copy(apr_pool_t *pool) {
758 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
759 memcpy(temp, data_, size_);
764 void set(apr_pool_t *pool, const char *data, size_t size) {
770 data_ = const_cast<char *>(data);
778 _finline void set(apr_pool_t *pool, const char *data) {
779 set(pool, data, data == NULL ? 0 : strlen(data));
782 _finline void set(apr_pool_t *pool, const std::string &rhs) {
783 set(pool, rhs.data(), rhs.size());
786 bool operator ==(const CYString &rhs) const {
787 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
790 _finline operator CFStringRef() {
792 cache_ = CYStringCreate(data_, size_);
796 _finline operator id() {
797 return (NSString *) static_cast<CFStringRef>(*this);
800 _finline operator const char *() {
801 return reinterpret_cast<const char *>(data_);
805 /* C++ NSString Algorithm Adapters {{{ */
807 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
810 struct NSStringMapHash :
811 std::unary_function<NSString *, size_t>
813 _finline size_t operator ()(NSString *value) const {
814 return CFStringHashNSString((CFStringRef) value);
818 struct NSStringMapLess :
819 std::binary_function<NSString *, NSString *, bool>
821 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
822 return [lhs compare:rhs] == NSOrderedAscending;
826 struct NSStringMapEqual :
827 std::binary_function<NSString *, NSString *, bool>
829 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
830 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
831 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
832 //[lhs isEqualToString:rhs];
837 /* Perl-Compatible RegEx {{{ */
853 Pcre(const char *regex) :
857 this->operator =(regex);
860 void operator =(const char *regex) {
861 _assert(code_ == NULL);
865 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
868 lprintf("%d:%s\n", offset, error);
872 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
873 matches_ = new int[(capture_ + 1) * 3];
881 NSString *operator [](size_t match) {
882 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
885 bool operator ()(NSString *data) {
886 // XXX: length is for characters, not for bytes
887 return operator ()([data UTF8String], [data length]);
890 bool operator ()(const char *data, size_t size) {
892 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
895 _finline size_t size() const {
900 /* Mime Addresses {{{ */
901 @interface Address : NSObject {
907 - (NSString *) address;
909 - (void) setAddress:(NSString *)address;
911 + (Address *) addressWithString:(NSString *)string;
912 - (Address *) initWithString:(NSString *)string;
916 @implementation Address
925 - (NSString *) name {
929 - (NSString *) address {
933 - (void) setAddress:(NSString *)address {
935 [address_ autorelease];
939 address_ = [address retain];
942 + (Address *) addressWithString:(NSString *)string {
943 return [[[Address alloc] initWithString:string] autorelease];
946 + (NSArray *) _attributeKeys {
947 return [NSArray arrayWithObjects:
953 - (NSArray *) attributeKeys {
954 return [[self class] _attributeKeys];
957 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
958 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
961 - (Address *) initWithString:(NSString *)string {
962 if ((self = [super init]) != nil) {
963 const char *data = [string UTF8String];
964 size_t size = [string length];
966 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
968 if (address_r(data, size)) {
969 name_ = [address_r[1] retain];
970 address_ = [address_r[2] retain];
972 name_ = [string retain];
980 /* CoreGraphics Primitives {{{ */
985 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
986 CGFloat color[] = {red, green, blue, alpha};
987 return CGColorCreate(space, color);
996 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
997 color_(Create_(space, red, green, blue, alpha))
999 Set(space, red, green, blue, alpha);
1004 CGColorRelease(color_);
1011 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1013 color_ = Create_(space, red, green, blue, alpha);
1016 operator CGColorRef() {
1022 /* Random Global Variables {{{ */
1023 static const int PulseInterval_ = 50000;
1025 static const NSString *UI_;
1028 static bool RestartSubstrate_;
1029 static NSArray *Finishes_;
1031 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1032 #define NotifyConfig_ "/etc/notify.conf"
1034 static bool Queuing_;
1036 static CYColor Blue_;
1037 static CYColor Blueish_;
1038 static CYColor Black_;
1039 static CYColor Off_;
1040 static CYColor White_;
1041 static CYColor Gray_;
1042 static CYColor Green_;
1043 static CYColor Purple_;
1044 static CYColor Purplish_;
1046 static UIColor *InstallingColor_;
1047 static UIColor *RemovingColor_;
1049 static NSString *App_;
1051 static BOOL Advanced_;
1052 static BOOL Ignored_;
1054 static UIFont *Font12_;
1055 static UIFont *Font12Bold_;
1056 static UIFont *Font14_;
1057 static UIFont *Font18Bold_;
1058 static UIFont *Font22Bold_;
1060 static const char *Machine_ = NULL;
1061 static NSString *System_ = nil;
1062 static NSString *SerialNumber_ = nil;
1063 static NSString *ChipID_ = nil;
1064 static _H<NSString> Token_;
1065 static NSString *UniqueID_ = nil;
1066 static NSString *PLMN_ = nil;
1067 static NSString *Build_ = nil;
1068 static NSString *Product_ = nil;
1069 static NSString *Safari_ = nil;
1071 static CFLocaleRef Locale_;
1072 static NSArray *Languages_;
1073 static CGColorSpaceRef space_;
1075 static NSDictionary *SectionMap_;
1076 static NSMutableDictionary *Metadata_;
1077 static _transient NSMutableDictionary *Settings_;
1078 static _transient NSString *Role_;
1079 static _transient NSMutableDictionary *Packages_;
1080 static _transient NSMutableDictionary *Sections_;
1081 static _transient NSMutableDictionary *Sources_;
1082 static bool Changed_;
1086 static CGFloat ScreenScale_;
1087 static NSString *Idiom_;
1089 static NSMutableDictionary *SessionData_;
1090 static NSObject *HostConfig_;
1091 static NSMutableSet *BridgedHosts_;
1092 static NSMutableSet *PipelinedHosts_;
1094 static NSString *kCydiaProgressEventTypeError = @"Error";
1095 static NSString *kCydiaProgressEventTypeInformation = @"Information";
1096 static NSString *kCydiaProgressEventTypeStatus = @"Status";
1097 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
1100 /* Display Helpers {{{ */
1101 inline float Interpolate(float begin, float end, float fraction) {
1102 return (end - begin) * fraction + begin;
1105 static _finline const char *StripVersion_(const char *version) {
1106 const char *colon(strchr(version, ':'));
1107 return colon == NULL ? version : colon + 1;
1110 NSString *LocalizeSection(NSString *section) {
1111 static Pcre title_r("^(.*?) \\((.*)\\)$");
1112 if (title_r(section)) {
1113 NSString *parent(title_r[1]);
1114 NSString *child(title_r[2]);
1116 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1117 LocalizeSection(parent),
1118 LocalizeSection(child)
1122 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1125 NSString *Simplify(NSString *title) {
1126 const char *data = [title UTF8String];
1127 size_t size = [title length];
1129 static Pcre square_r("^\\[(.*)\\]$");
1130 if (square_r(data, size))
1131 return Simplify(square_r[1]);
1133 static Pcre paren_r("^\\((.*)\\)$");
1134 if (paren_r(data, size))
1135 return Simplify(paren_r[1]);
1137 static Pcre title_r("^(.*?) \\((.*)\\)$");
1138 if (title_r(data, size))
1139 return Simplify(title_r[1]);
1145 NSString *GetLastUpdate() {
1146 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1149 return UCLocalize("NEVER_OR_UNKNOWN");
1151 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1152 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1154 CFRelease(formatter);
1156 return [(NSString *) formatted autorelease];
1159 bool isSectionVisible(NSString *section) {
1160 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1161 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1162 return hidden == nil || ![hidden boolValue];
1167 /* Delegate Prototypes {{{ */
1170 @class CydiaProgressEvent;
1172 @protocol DatabaseDelegate
1173 - (void) repairWithSelector:(SEL)selector;
1174 - (void) setConfigurationData:(NSString *)data;
1175 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
1178 @class CYPackageController;
1180 @protocol CydiaDelegate
1181 - (void) retainNetworkActivityIndicator;
1182 - (void) releaseNetworkActivityIndicator;
1183 - (void) clearPackage:(Package *)package;
1184 - (void) installPackage:(Package *)package;
1185 - (void) installPackages:(NSArray *)packages;
1186 - (void) removePackage:(Package *)package;
1187 - (void) beginUpdate;
1189 - (void) distUpgrade;
1191 - (void) updateData;
1193 - (void) addTrivialSource:(NSString *)href;
1194 - (void) showSettings;
1195 - (UIProgressHUD *) addProgressHUD;
1196 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1197 - (CYViewController *) pageForPackage:(NSString *)name;
1198 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1199 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1203 /* ProgressEvent Interface/Delegate {{{ */
1204 @interface CydiaProgressEvent : NSObject {
1205 _H<NSString> message_;
1209 _H<NSString> package_;
1211 _H<NSString> version_;
1214 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type;
1215 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package;
1216 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item;
1218 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type;
1220 - (NSString *) message;
1221 - (NSString *) type;
1224 - (NSString *) package;
1226 - (NSString *) version;
1228 - (void) setItem:(NSArray *)item;
1229 - (void) setPackage:(NSString *)package;
1230 - (void) setURL:(NSString *)url;
1231 - (void) setVersion:(NSString *)version;
1233 - (NSString *) compound:(NSString *)value;
1234 - (NSString *) compoundMessage;
1235 - (NSString *) compoundTitle;
1239 @protocol ProgressDelegate
1240 - (void) addProgressEvent:(CydiaProgressEvent *)event;
1241 - (void) setProgressPercent:(NSNumber *)percent;
1242 - (void) setProgressStatus:(NSDictionary *)status;
1243 - (void) setProgressCancellable:(NSNumber *)cancellable;
1244 - (bool) isProgressCancelled;
1245 - (void) setTitle:(NSString *)title;
1248 /* Status Delegation {{{ */
1250 public pkgAcquireStatus
1253 _transient NSObject<ProgressDelegate> *delegate_;
1263 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1264 delegate_ = delegate;
1267 NSObject<ProgressDelegate> *getDelegate() const {
1271 virtual bool MediaChange(std::string media, std::string drive) {
1275 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1278 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1279 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1280 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
1281 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1284 virtual void Done(pkgAcquire::ItemDesc &item) {
1287 virtual void Fail(pkgAcquire::ItemDesc &item) {
1289 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1290 item.Owner->Status == pkgAcquire::Item::StatDone
1294 std::string &error(item.Owner->ErrorText);
1298 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
1299 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1302 virtual bool Pulse(pkgAcquire *Owner) {
1303 bool value = pkgAcquireStatus::Pulse(Owner);
1306 double(CurrentBytes + CurrentItems) /
1307 double(TotalBytes + TotalItems)
1310 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1311 [NSNumber numberWithDouble:percent], @"Percent",
1313 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1314 [NSNumber numberWithDouble:TotalBytes], @"Total",
1315 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1316 nil] waitUntilDone:YES];
1318 if (value && ![delegate_ isProgressCancelled])
1326 _finline bool WasCancelled() const {
1330 virtual void Start() {
1331 pkgAcquireStatus::Start();
1332 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1335 virtual void Stop() {
1336 pkgAcquireStatus::Stop();
1337 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1338 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1342 /* Database Interface {{{ */
1343 typedef std::map< unsigned long, _H<Source> > SourceMap;
1345 @interface Database : NSObject {
1351 pkgCacheFile cache_;
1352 pkgDepCache::Policy *policy_;
1353 pkgRecords *records_;
1354 pkgProblemResolver *resolver_;
1355 pkgAcquire *fetcher_;
1357 SPtr<pkgPackageManager> manager_;
1358 pkgSourceList *list_;
1360 SourceMap sourceMap_;
1361 NSMutableArray *sourceList_;
1363 CFMutableArrayRef packages_;
1365 _transient NSObject<DatabaseDelegate> *delegate_;
1366 _transient NSObject<ProgressDelegate> *progress_;
1374 std::map<const char *, _H<NSString> > sections_;
1377 + (Database *) sharedInstance;
1380 - (void) _readCydia:(NSNumber *)fd;
1381 - (void) _readStatus:(NSNumber *)fd;
1382 - (void) _readOutput:(NSNumber *)fd;
1386 - (Package *) packageWithName:(NSString *)name;
1388 - (pkgCacheFile &) cache;
1389 - (pkgDepCache::Policy *) policy;
1390 - (pkgRecords *) records;
1391 - (pkgProblemResolver *) resolver;
1392 - (pkgAcquire &) fetcher;
1393 - (pkgSourceList &) list;
1394 - (NSArray *) packages;
1395 - (NSArray *) sources;
1396 - (Source *) sourceWithKey:(NSString *)key;
1397 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1405 - (void) updateWithStatus:(Status &)status;
1407 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1409 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1410 - (NSObject<ProgressDelegate> *) progressDelegate;
1412 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1414 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1418 /* ProgressEvent Implementation {{{ */
1419 @implementation CydiaProgressEvent
1421 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1422 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1425 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1426 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1427 [event setPackage:package];
1431 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1432 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1434 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1435 NSArray *fields([description componentsSeparatedByString:@" "]);
1436 [event setItem:fields];
1438 if ([fields count] > 3) {
1439 [event setPackage:[fields objectAtIndex:2]];
1440 [event setVersion:[fields objectAtIndex:3]];
1443 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1448 + (NSArray *) _attributeKeys {
1449 return [NSArray arrayWithObjects:
1459 - (NSArray *) attributeKeys {
1460 return [[self class] _attributeKeys];
1463 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1464 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1467 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1468 if ((self = [super init]) != nil) {
1474 - (NSString *) message {
1478 - (NSString *) type {
1482 - (NSArray *) item {
1483 return (id) item_ ?: [NSNull null];
1486 - (void) setItem:(NSArray *)item {
1490 - (NSString *) package {
1491 return (id) package_ ?: [NSNull null];
1494 - (void) setPackage:(NSString *)package {
1498 - (NSString *) url {
1499 return (id) url_ ?: [NSNull null];
1502 - (void) setURL:(NSString *)url {
1506 - (void) setVersion:(NSString *)version {
1510 - (NSString *) version {
1511 return (id) version_ ?: [NSNull null];
1514 - (NSString *) compound:(NSString *)value {
1516 NSString *mode(nil); {
1517 NSString *type([self type]);
1518 if ([type isEqualToString:kCydiaProgressEventTypeError])
1519 mode = UCLocalize("ERROR");
1520 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1521 mode = UCLocalize("WARNING");
1525 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1531 - (NSString *) compoundMessage {
1532 return [self compound:[self message]];
1535 - (NSString *) compoundTitle {
1538 if (package_ == nil)
1540 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1541 title = [package name];
1545 return [self compound:title];
1551 // Cytore Definitions {{{
1552 struct PackageValue :
1555 Cytore::Offset<PackageValue> next_;
1557 uint32_t index_ : 23;
1558 uint32_t subscribed_ : 1;
1575 Cytore::Offset<PackageValue> packages_[1 << 16];
1578 static Cytore::File<MetaValue> MetaFile_;
1580 // Cytore Helper Functions {{{
1581 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1582 SplitHash nhash = { hashlittle(name, length) };
1584 PackageValue *metadata;
1586 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1587 offset: if (offset->IsNull()) {
1588 *offset = MetaFile_.New<PackageValue>(length + 1);
1589 metadata = &MetaFile_.Get(*offset);
1591 if (metadata == NULL) {
1595 metadata = new PackageValue();
1596 memset(metadata, 0, sizeof(*metadata));
1599 memcpy(metadata->name_, name, length + 1);
1600 metadata->nhash_ = nhash.u16[1];
1602 metadata = &MetaFile_.Get(*offset);
1604 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1605 offset = &metadata->next_;
1613 static void PackageImport(const void *key, const void *value, void *context) {
1614 bool &fail(*reinterpret_cast<bool *>(context));
1617 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1618 NSLog(@"failed to import package %@", key);
1622 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1623 NSDictionary *package((NSDictionary *) value);
1625 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1626 if ([subscribed boolValue] && !metadata->subscribed_)
1627 metadata->subscribed_ = true;
1629 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1630 time_t time([date timeIntervalSince1970]);
1631 if (metadata->first_ > time || metadata->first_ == 0)
1632 metadata->first_ = time;
1635 NSDate *date([package objectForKey:@"LastSeen"]);
1636 NSString *version([package objectForKey:@"LastVersion"]);
1638 if (date != nil && version != nil) {
1639 time_t time([date timeIntervalSince1970]);
1640 if (metadata->last_ < time || metadata->last_ == 0)
1641 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1642 size_t length(strlen(buffer));
1643 uint16_t vhash(hashlittle(buffer, length));
1645 size_t capped(std::min<size_t>(8, length));
1646 char *latest(buffer + length - capped);
1648 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1649 metadata->vhash_ = vhash;
1651 metadata->last_ = time;
1657 /* Source Class {{{ */
1658 @interface Source : NSObject {
1659 CYString depiction_;
1660 CYString description_;
1666 CYString distribution_;
1671 _H<NSString> authority_;
1673 CYString defaultIcon_;
1675 _H<NSDictionary> record_;
1679 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1681 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1683 - (NSString *) depictionForPackage:(NSString *)package;
1684 - (NSString *) supportForPackage:(NSString *)package;
1686 - (NSDictionary *) record;
1690 - (NSString *) distribution;
1691 - (NSString *) type;
1693 - (NSString *) host;
1695 - (NSString *) name;
1696 - (NSString *) description;
1697 - (NSString *) label;
1698 - (NSString *) origin;
1699 - (NSString *) version;
1701 - (NSString *) defaultIcon;
1705 @implementation Source
1709 distribution_.clear();
1712 description_.clear();
1718 defaultIcon_.clear();
1726 // XXX: this is a very inefficient way to call these deconstructors
1731 + (NSArray *) _attributeKeys {
1732 return [NSArray arrayWithObjects:
1747 - (NSArray *) attributeKeys {
1748 return [[self class] _attributeKeys];
1751 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1752 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1755 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1758 trusted_ = index->IsTrusted();
1760 uri_.set(pool, index->GetURI());
1761 distribution_.set(pool, index->GetDist());
1762 type_.set(pool, index->GetType());
1764 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1765 if (dindex != NULL) {
1767 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1770 pkgTagFile tags(&fd);
1772 pkgTagSection section;
1779 {"default-icon", &defaultIcon_},
1780 {"depiction", &depiction_},
1781 {"description", &description_},
1783 {"origin", &origin_},
1784 {"support", &support_},
1785 {"version", &version_},
1788 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1789 const char *start, *end;
1791 if (section.Find(names[i].name_, start, end)) {
1792 CYString &value(*names[i].value_);
1793 value.set(pool, start, end - start);
1799 record_ = [Sources_ objectForKey:[self key]];
1801 NSURL *url([NSURL URLWithString:uri_]);
1805 host_ = [host_ lowercaseString];
1808 // XXX: this is due to a bug in _H<>
1809 authority_ = (id) host_;
1811 authority_ = [url path];
1814 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1815 if ((self = [super init]) != nil) {
1816 [self setMetaIndex:index inPool:pool];
1820 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1821 NSDictionary *lhr = [self record];
1822 NSDictionary *rhr = [source record];
1825 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1827 NSString *lhs = [self name];
1828 NSString *rhs = [source name];
1830 if ([lhs length] != 0 && [rhs length] != 0) {
1831 unichar lhc = [lhs characterAtIndex:0];
1832 unichar rhc = [rhs characterAtIndex:0];
1834 if (isalpha(lhc) && !isalpha(rhc))
1835 return NSOrderedAscending;
1836 else if (!isalpha(lhc) && isalpha(rhc))
1837 return NSOrderedDescending;
1840 return [lhs compare:rhs options:LaxCompareOptions_];
1843 - (NSString *) depictionForPackage:(NSString *)package {
1844 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1847 - (NSString *) supportForPackage:(NSString *)package {
1848 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1851 - (NSDictionary *) record {
1859 - (NSString *) uri {
1863 - (NSString *) distribution {
1864 return distribution_;
1867 - (NSString *) type {
1871 - (NSString *) key {
1872 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1875 - (NSString *) host {
1879 - (NSString *) name {
1880 return origin_.empty() ? (id) authority_ : origin_;
1883 - (NSString *) description {
1884 return description_;
1887 - (NSString *) label {
1888 return label_.empty() ? (id) authority_ : label_;
1891 - (NSString *) origin {
1895 - (NSString *) version {
1899 - (NSString *) defaultIcon {
1900 return defaultIcon_;
1905 /* CydiaOperation Class {{{ */
1906 @interface CydiaOperation : NSObject {
1907 NSString *operator_;
1911 - (NSString *) operator;
1912 - (NSString *) value;
1916 @implementation CydiaOperation
1919 [operator_ release];
1924 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1925 if ((self = [super init]) != nil) {
1926 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1927 value_ = [[NSString alloc] initWithUTF8String:value];
1931 + (NSArray *) _attributeKeys {
1932 return [NSArray arrayWithObjects:
1938 - (NSArray *) attributeKeys {
1939 return [[self class] _attributeKeys];
1942 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1943 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1946 - (NSString *) operator {
1950 - (NSString *) value {
1956 /* CydiaClause Class {{{ */
1957 @interface CydiaClause : NSObject {
1959 CydiaOperation *version_;
1962 - (NSString *) package;
1963 - (CydiaOperation *) version;
1967 @implementation CydiaClause
1975 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1976 if ((self = [super init]) != nil) {
1977 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1979 if (const char *version = dep.TargetVer())
1980 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1982 version_ = [[NSNull null] retain];
1986 + (NSArray *) _attributeKeys {
1987 return [NSArray arrayWithObjects:
1993 - (NSArray *) attributeKeys {
1994 return [[self class] _attributeKeys];
1997 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1998 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2001 - (NSString *) package {
2005 - (CydiaOperation *) version {
2011 /* CydiaRelation Class {{{ */
2012 @interface CydiaRelation : NSObject {
2013 NSString *relationship_;
2014 NSMutableArray *clauses_;
2017 - (NSString *) relationship;
2018 - (NSArray *) clauses;
2022 @implementation CydiaRelation
2025 [relationship_ release];
2030 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2031 if ((self = [super init]) != nil) {
2032 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
2033 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
2035 pkgCache::DepIterator start;
2036 pkgCache::DepIterator end;
2037 dep.GlobOr(start, end); // ++dep
2040 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2042 // yes, seriously. (wtf?)
2050 + (NSArray *) _attributeKeys {
2051 return [NSArray arrayWithObjects:
2057 - (NSArray *) attributeKeys {
2058 return [[self class] _attributeKeys];
2061 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2062 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2065 - (NSString *) relationship {
2066 return relationship_;
2069 - (NSArray *) clauses {
2073 - (void) addClause:(CydiaClause *)clause {
2074 [clauses_ addObject:clause];
2079 /* Package Class {{{ */
2080 struct ParsedPackage {
2085 CYString depiction_;
2095 @interface Package : NSObject {
2098 uint32_t essential_ : 1;
2099 uint32_t obsolete_ : 1;
2100 uint32_t ignored_ : 1;
2104 _transient Database *database_;
2106 pkgCache::VerIterator version_;
2107 pkgCache::PkgIterator iterator_;
2108 pkgCache::VerFileIterator file_;
2114 CYString installed_;
2116 const char *section_;
2117 _transient NSString *section$_;
2121 PackageValue *metadata_;
2122 ParsedPackage *parsed_;
2124 NSMutableArray *tags_;
2127 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2128 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2130 - (pkgCache::PkgIterator) iterator;
2133 - (NSString *) section;
2134 - (NSString *) simpleSection;
2136 - (NSString *) longSection;
2137 - (NSString *) shortSection;
2141 - (Address *) maintainer;
2143 - (NSString *) longDescription;
2144 - (NSString *) shortDescription;
2147 - (PackageValue *) metadata;
2150 - (bool) subscribed;
2151 - (bool) setSubscribed:(bool)subscribed;
2155 - (NSString *) latest;
2156 - (NSString *) installed;
2157 - (BOOL) uninstalled;
2160 - (BOOL) upgradableAndEssential:(BOOL)essential;
2163 - (BOOL) unfiltered;
2167 - (BOOL) halfConfigured;
2168 - (BOOL) halfInstalled;
2170 - (NSString *) mode;
2173 - (NSString *) name;
2175 - (NSString *) homepage;
2176 - (NSString *) depiction;
2177 - (Address *) author;
2179 - (NSString *) support;
2181 - (NSArray *) files;
2182 - (NSArray *) warnings;
2183 - (NSArray *) applications;
2185 - (Source *) source;
2187 - (BOOL) matches:(NSString *)text;
2189 - (bool) hasSupportingRole;
2190 - (BOOL) hasTag:(NSString *)tag;
2191 - (NSString *) primaryPurpose;
2192 - (NSArray *) purposes;
2193 - (bool) isCommercial;
2195 - (void) setIndex:(size_t)index;
2197 - (CYString &) cyname;
2199 - (uint32_t) compareBySection:(NSArray *)sections;
2204 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2205 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2206 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2207 - (bool) isVisibleInSection:(NSString *)section;
2208 - (bool) isVisibleInSource:(Source *)source;
2212 uint32_t PackageChangesRadix(Package *self, void *) {
2217 uint32_t timestamp : 30;
2218 uint32_t ignored : 1;
2219 uint32_t upgradable : 1;
2223 bool upgradable([self upgradableAndEssential:YES]);
2224 value.bits.upgradable = upgradable ? 1 : 0;
2227 value.bits.timestamp = 0;
2228 value.bits.ignored = [self ignored] ? 0 : 1;
2229 value.bits.upgradable = 1;
2231 value.bits.timestamp = [self seen] >> 2;
2232 value.bits.ignored = 0;
2233 value.bits.upgradable = 0;
2236 return _not(uint32_t) - value.key;
2239 uint32_t PackagePrefixRadix(Package *self, void *context) {
2240 size_t offset(reinterpret_cast<size_t>(context));
2241 CYString &name([self cyname]);
2243 size_t size(name.size());
2246 char *text(name.data());
2249 if (!isdigit(text[0]))
2253 while (size != digits && isdigit(text[digits]))
2261 if (offset == 0 && zeros != 0) {
2262 memset(data, '0', zeros);
2263 memcpy(data + zeros, text, 4 - zeros);
2265 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2266 if (size <= offset - zeros)
2269 text += offset - zeros;
2270 size -= offset - zeros;
2273 memcpy(data, text, 4);
2275 memcpy(data, text, size);
2276 memset(data + size, 0, 4 - size);
2279 for (size_t i(0); i != 4; ++i)
2280 if (isalpha(data[i]))
2288 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2290 /* XXX: ntohl may be more honest */
2291 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2294 CYString &(*PackageName)(Package *self, SEL sel);
2296 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2297 _profile(PackageNameCompare)
2298 CYString &lhi(PackageName(lhs, @selector(cyname)));
2299 CYString &rhi(PackageName(rhs, @selector(cyname)));
2300 CFStringRef lhn(lhi), rhn(rhi);
2303 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2304 else if (rhn == NULL)
2305 return NSOrderedDescending;
2307 _profile(PackageNameCompare$NumbersLast)
2308 if (!lhi.empty() && !rhi.empty()) {
2309 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2310 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2311 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2312 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2313 return lha ? NSOrderedAscending : NSOrderedDescending;
2317 CFIndex length = CFStringGetLength(lhn);
2319 _profile(PackageNameCompare$Compare)
2320 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2325 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2326 return PackageNameCompare(*lhs, *rhs, context);
2329 struct PackageNameOrdering :
2330 std::binary_function<Package *, Package *, bool>
2332 _finline bool operator ()(Package *lhs, Package *rhs) const {
2333 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2337 @implementation Package
2339 - (NSString *) description {
2340 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2344 if (parsed_ != NULL)
2353 + (NSString *) webScriptNameForSelector:(SEL)selector {
2355 else if (selector == @selector(clear))
2357 else if (selector == @selector(getField:))
2359 else if (selector == @selector(hasTag:))
2361 else if (selector == @selector(install))
2363 else if (selector == @selector(remove))
2369 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2370 return [self webScriptNameForSelector:selector] == nil;
2373 + (NSArray *) _attributeKeys {
2374 return [NSArray arrayWithObjects:
2393 @"shortDescription",
2406 - (NSArray *) attributeKeys {
2407 return [[self class] _attributeKeys];
2410 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2411 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2414 - (NSArray *) relations {
2415 @synchronized (database_) {
2416 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2417 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2418 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2422 - (NSString *) getField:(NSString *)name {
2423 @synchronized (database_) {
2424 if ([database_ era] != era_ || file_.end())
2427 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2429 const char *start, *end;
2430 if (!parser.Find([name UTF8String], start, end))
2431 return (NSString *) [NSNull null];
2433 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2437 if (parsed_ != NULL)
2439 @synchronized (database_) {
2440 if ([database_ era] != era_ || file_.end())
2443 ParsedPackage *parsed(new ParsedPackage);
2446 _profile(Package$parse)
2447 pkgRecords::Parser *parser;
2449 _profile(Package$parse$Lookup)
2450 parser = &[database_ records]->Lookup(file_);
2455 _profile(Package$parse$Find)
2460 {"icon", &parsed->icon_},
2461 {"depiction", &parsed->depiction_},
2462 {"homepage", &parsed->homepage_},
2463 {"website", &website},
2464 {"bugs", &parsed->bugs_},
2465 {"support", &parsed->support_},
2466 {"sponsor", &parsed->sponsor_},
2467 {"author", &parsed->author_},
2470 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2471 const char *start, *end;
2473 if (parser->Find(names[i].name_, start, end)) {
2474 CYString &value(*names[i].value_);
2475 _profile(Package$parse$Value)
2476 value.set(pool_, start, end - start);
2482 _profile(Package$parse$Tagline)
2483 const char *start, *end;
2484 if (parser->ShortDesc(start, end)) {
2485 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2488 while (stop != start && stop[-1] == '\r')
2490 parsed->tagline_.set(pool_, start, stop - start);
2494 _profile(Package$parse$Retain)
2495 if (parsed->homepage_.empty())
2496 parsed->homepage_ = website;
2497 if (parsed->homepage_ == parsed->depiction_)
2498 parsed->homepage_.clear();
2503 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2504 if ((self = [super init]) != nil) {
2505 _profile(Package$initWithVersion)
2508 database_ = database;
2509 era_ = [database era];
2513 pkgCache::PkgIterator iterator(version.ParentPkg());
2514 iterator_ = iterator;
2516 _profile(Package$initWithVersion$Version)
2517 if (!version_.end())
2518 file_ = version_.FileList();
2520 pkgCache &cache([database_ cache]);
2521 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2525 _profile(Package$initWithVersion$Cache)
2526 name_.set(NULL, iterator.Display());
2528 latest_.set(NULL, StripVersion_(version_.VerStr()));
2530 pkgCache::VerIterator current(iterator.CurrentVer());
2532 installed_.set(NULL, StripVersion_(current.VerStr()));
2535 _profile(Package$initWithVersion$Tags)
2536 pkgCache::TagIterator tag(iterator.TagList());
2538 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2540 const char *name(tag.Name());
2541 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2543 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2544 if (strcmp(name + 6, "enduser") == 0)
2546 else if (strcmp(name + 6, "hacker") == 0)
2548 else if (strcmp(name + 6, "developer") == 0)
2550 else if (strcmp(name + 6, "cydia") == 0)
2556 if (strncmp(name, "cydia::", 7) == 0) {
2557 if (strcmp(name + 7, "essential") == 0)
2559 else if (strcmp(name + 7, "obsolete") == 0)
2564 } while (!tag.end());
2568 _profile(Package$initWithVersion$Metadata)
2569 const char *mixed(iterator.Name());
2570 size_t size(strlen(mixed));
2571 char lower[size + 1];
2573 for (size_t i(0); i != size; ++i)
2574 lower[i] = mixed[i] | 0x20;
2577 PackageValue *metadata(PackageFind(lower, size));
2578 metadata_ = metadata;
2580 id_.set(NULL, metadata->name_, size);
2582 const char *latest(version_.VerStr());
2583 size_t length(strlen(latest));
2585 uint16_t vhash(hashlittle(latest, length));
2587 size_t capped(std::min<size_t>(8, length));
2588 latest = latest + length - capped;
2590 if (metadata->first_ == 0)
2591 metadata->first_ = now_;
2593 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2594 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2595 metadata->vhash_ = vhash;
2596 metadata->last_ = now_;
2597 } else if (metadata->last_ == 0)
2598 metadata->last_ = metadata->first_;
2601 _profile(Package$initWithVersion$Section)
2602 section_ = iterator.Section();
2605 _profile(Package$initWithVersion$Flags)
2606 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2607 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2612 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2613 pkgCache::VerIterator version;
2615 _profile(Package$packageWithIterator$GetCandidateVer)
2616 version = [database policy]->GetCandidateVer(iterator);
2624 _profile(Package$packageWithIterator$Allocate)
2625 package = [Package allocWithZone:zone];
2628 _profile(Package$packageWithIterator$Initialize)
2630 initWithVersion:version
2637 _profile(Package$packageWithIterator$Autorelease)
2638 package = [package autorelease];
2644 - (pkgCache::PkgIterator) iterator {
2648 - (NSString *) section {
2649 if (section$_ == nil) {
2650 if (section_ == NULL)
2653 _profile(Package$section$mappedSectionForPointer)
2654 section$_ = [database_ mappedSectionForPointer:section_];
2659 - (NSString *) simpleSection {
2660 if (NSString *section = [self section])
2661 return Simplify(section);
2666 - (NSString *) longSection {
2667 return LocalizeSection([self section]);
2670 - (NSString *) shortSection {
2671 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2674 - (NSString *) uri {
2677 pkgIndexFile *index;
2678 pkgCache::PkgFileIterator file(file_.File());
2679 if (![database_ list].FindIndex(file, index))
2681 return [NSString stringWithUTF8String:iterator_->Path];
2682 //return [NSString stringWithUTF8String:file.Site()];
2683 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2687 - (Address *) maintainer {
2688 @synchronized (database_) {
2689 if ([database_ era] != era_ || file_.end())
2692 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2693 const std::string &maintainer(parser->Maintainer());
2694 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2698 @synchronized (database_) {
2699 if ([database_ era] != era_ || version_.end())
2702 return version_->InstalledSize;
2705 - (NSString *) longDescription {
2706 @synchronized (database_) {
2707 if ([database_ era] != era_ || file_.end())
2710 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2711 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2713 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2714 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2715 if ([lines count] < 2)
2718 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2719 for (size_t i(1), e([lines count]); i != e; ++i) {
2720 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2721 [trimmed addObject:trim];
2724 return [trimmed componentsJoinedByString:@"\n"];
2727 - (NSString *) shortDescription {
2728 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2732 _profile(Package$index)
2733 CFStringRef name((CFStringRef) [self name]);
2734 if (CFStringGetLength(name) == 0)
2736 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2737 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2739 return toupper(character);
2743 - (PackageValue *) metadata {
2748 PackageValue *metadata([self metadata]);
2749 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2752 - (bool) subscribed {
2753 return [self metadata]->subscribed_;
2756 - (bool) setSubscribed:(bool)subscribed {
2757 PackageValue *metadata([self metadata]);
2758 if (metadata->subscribed_ == subscribed)
2760 metadata->subscribed_ = subscribed;
2768 - (NSString *) latest {
2772 - (NSString *) installed {
2776 - (BOOL) uninstalled {
2777 return installed_.empty();
2781 return !version_.end();
2784 - (BOOL) upgradableAndEssential:(BOOL)essential {
2785 _profile(Package$upgradableAndEssential)
2786 pkgCache::VerIterator current(iterator_.CurrentVer());
2788 return essential && essential_;
2790 return !version_.end() && version_ != current;
2794 - (BOOL) essential {
2799 return [database_ cache][iterator_].InstBroken();
2802 - (BOOL) unfiltered {
2803 _profile(Package$unfiltered$obsolete)
2804 if (_unlikely(obsolete_))
2808 _profile(Package$unfiltered$hasSupportingRole)
2809 if (_unlikely(![self hasSupportingRole]))
2817 if (![self unfiltered])
2822 _profile(Package$visible$section)
2823 section = [self section];
2826 _profile(Package$visible$isSectionVisible)
2827 if (!isSectionVisible(section))
2835 unsigned char current(iterator_->CurrentState);
2836 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2839 - (BOOL) halfConfigured {
2840 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2843 - (BOOL) halfInstalled {
2844 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2848 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2849 return state.Mode != pkgDepCache::ModeKeep;
2852 - (NSString *) mode {
2853 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2855 switch (state.Mode) {
2856 case pkgDepCache::ModeDelete:
2857 if ((state.iFlags & pkgDepCache::Purge) != 0)
2861 case pkgDepCache::ModeKeep:
2862 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2863 return @"REINSTALL";
2864 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2868 case pkgDepCache::ModeInstall:
2869 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2870 return @"REINSTALL";
2871 else*/ switch (state.Status) {
2873 return @"DOWNGRADE";
2879 return @"NEW_INSTALL";
2890 - (NSString *) name {
2891 return name_.empty() ? id_ : name_;
2894 - (UIImage *) icon {
2895 NSString *section = [self simpleSection];
2898 if (parsed_ != NULL)
2899 if (NSString *href = parsed_->icon_)
2900 if ([href hasPrefix:@"file:///"])
2901 // XXX: correct escaping
2902 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2903 if (icon == nil) if (section != nil)
2904 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2905 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2906 if ([dicon hasPrefix:@"file:///"])
2907 // XXX: correct escaping
2908 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2910 icon = [UIImage applicationImageNamed:@"unknown.png"];
2914 - (NSString *) homepage {
2915 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2918 - (NSString *) depiction {
2919 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2922 - (Address *) sponsor {
2923 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2926 - (Address *) author {
2927 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2930 - (NSString *) support {
2931 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2934 - (NSArray *) files {
2935 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2936 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2939 fin.open([path UTF8String]);
2944 while (std::getline(fin, line))
2945 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2950 - (NSString *) state {
2951 @synchronized (database_) {
2952 if ([database_ era] != era_ || file_.end())
2955 switch (iterator_->CurrentState) {
2956 case pkgCache::State::NotInstalled:
2957 return @"NotInstalled";
2958 case pkgCache::State::UnPacked:
2960 case pkgCache::State::HalfConfigured:
2961 return @"HalfConfigured";
2962 case pkgCache::State::HalfInstalled:
2963 return @"HalfInstalled";
2964 case pkgCache::State::ConfigFiles:
2965 return @"ConfigFiles";
2966 case pkgCache::State::Installed:
2967 return @"Installed";
2968 case pkgCache::State::TriggersAwaited:
2969 return @"TriggersAwaited";
2970 case pkgCache::State::TriggersPending:
2971 return @"TriggersPending";
2974 return (NSString *) [NSNull null];
2977 - (NSString *) selection {
2978 @synchronized (database_) {
2979 if ([database_ era] != era_ || file_.end())
2982 switch (iterator_->SelectedState) {
2983 case pkgCache::State::Unknown:
2985 case pkgCache::State::Install:
2987 case pkgCache::State::Hold:
2989 case pkgCache::State::DeInstall:
2990 return @"DeInstall";
2991 case pkgCache::State::Purge:
2995 return (NSString *) [NSNull null];
2998 - (NSArray *) warnings {
2999 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3000 const char *name(iterator_.Name());
3002 size_t length(strlen(name));
3003 if (length < 2) invalid:
3004 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3005 else for (size_t i(0); i != length; ++i)
3007 /* XXX: technically this is not allowed */
3008 (name[i] < 'A' || name[i] > 'Z') &&
3009 (name[i] < 'a' || name[i] > 'z') &&
3010 (name[i] < '0' || name[i] > '9') &&
3011 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3014 if (strcmp(name, "cydia") != 0) {
3017 bool _private = false;
3020 bool repository = [[self section] isEqualToString:@"Repositories"];
3022 if (NSArray *files = [self files])
3023 for (NSString *file in files)
3024 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3026 else if (!user && [file isEqualToString:@"/User"])
3028 else if (!_private && [file isEqualToString:@"/private"])
3030 else if (!stash && [file isEqualToString:@"/var/stash"])
3033 /* XXX: this is not sensitive enough. only some folders are valid. */
3034 if (cydia && !repository)
3035 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3037 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3039 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3041 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3044 return [warnings count] == 0 ? nil : warnings;
3047 - (NSArray *) applications {
3048 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3050 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3052 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
3053 if (NSArray *files = [self files])
3054 for (NSString *file in files)
3055 if (application_r(file)) {
3056 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3057 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3058 if ([id isEqualToString:me])
3061 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3063 display = application_r[1];
3065 NSString *bundle([file stringByDeletingLastPathComponent]);
3066 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3067 if (icon == nil || [icon length] == 0)
3069 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3071 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3072 [applications addObject:application];
3074 [application addObject:id];
3075 [application addObject:display];
3076 [application addObject:url];
3079 return [applications count] == 0 ? nil : applications;
3082 - (Source *) source {
3083 if (source_ == nil) {
3084 @synchronized (database_) {
3085 if ([database_ era] != era_ || file_.end())
3086 source_ = (Source *) [NSNull null];
3088 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
3092 return source_ == (Source *) [NSNull null] ? nil : source_;
3095 - (BOOL) matches:(NSString *)text {
3101 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
3102 if (range.location != NSNotFound)
3105 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
3106 if (range.location != NSNotFound)
3111 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
3112 if (range.location != NSNotFound)
3118 - (bool) hasSupportingRole {
3123 if ([Role_ isEqualToString:@"User"])
3127 if ([Role_ isEqualToString:@"Hacker"])
3131 if ([Role_ isEqualToString:@"Developer"])
3136 - (NSArray *) tags {
3140 - (BOOL) hasTag:(NSString *)tag {
3141 return tags_ == nil ? NO : [tags_ containsObject:tag];
3144 - (NSString *) primaryPurpose {
3145 for (NSString *tag in tags_)
3146 if ([tag hasPrefix:@"purpose::"])
3147 return [tag substringFromIndex:9];
3151 - (NSArray *) purposes {
3152 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3153 for (NSString *tag in tags_)
3154 if ([tag hasPrefix:@"purpose::"])
3155 [purposes addObject:[tag substringFromIndex:9]];
3156 return [purposes count] == 0 ? nil : purposes;
3159 - (bool) isCommercial {
3160 return [self hasTag:@"cydia::commercial"];
3163 - (void) setIndex:(size_t)index {
3164 if (metadata_->index_ != index)
3165 metadata_->index_ = index;
3168 - (CYString &) cyname {
3169 return name_.empty() ? id_ : name_;
3172 - (uint32_t) compareBySection:(NSArray *)sections {
3173 NSString *section([self section]);
3174 for (size_t i(0), e([sections count]); i != e; ++i) {
3175 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3179 return _not(uint32_t);
3183 @synchronized (database_) {
3184 pkgProblemResolver *resolver = [database_ resolver];
3185 resolver->Clear(iterator_);
3187 pkgCacheFile &cache([database_ cache]);
3188 cache->SetReInstall(iterator_, false);
3189 cache->MarkKeep(iterator_, false);
3193 @synchronized (database_) {
3194 pkgProblemResolver *resolver = [database_ resolver];
3195 resolver->Clear(iterator_);
3196 resolver->Protect(iterator_);
3198 pkgCacheFile &cache([database_ cache]);
3199 cache->SetReInstall(iterator_, false);
3200 cache->MarkInstall(iterator_, false);
3202 pkgDepCache::StateCache &state((*cache)[iterator_]);
3203 if (!state.Install())
3204 cache->SetReInstall(iterator_, true);
3208 @synchronized (database_) {
3209 pkgProblemResolver *resolver = [database_ resolver];
3210 resolver->Clear(iterator_);
3211 resolver->Remove(iterator_);
3212 resolver->Protect(iterator_);
3214 pkgCacheFile &cache([database_ cache]);
3215 cache->SetReInstall(iterator_, false);
3216 cache->MarkDelete(iterator_, true);
3219 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3220 _profile(Package$isUnfilteredAndSearchedForBy)
3223 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3224 value &= [self unfiltered];
3227 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3228 value &= [self matches:search];
3235 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3236 if ([search length] == 0)
3239 _profile(Package$isUnfilteredAndSelectedForBy)
3242 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3243 value &= [self unfiltered];
3246 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3247 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3254 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3255 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3258 - (bool) isVisibleInSection:(NSString *)name {
3259 NSString *section([self section]);
3263 section == nil && [name length] == 0 ||
3264 [name isEqualToString:section]
3265 ) && [self visible];
3268 - (bool) isVisibleInSource:(Source *)source {
3269 return [self source] == source && [self visible];
3274 /* Section Class {{{ */
3275 @interface Section : NSObject {
3280 NSString *localized_;
3283 - (NSComparisonResult) compareByLocalized:(Section *)section;
3284 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3285 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3286 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3287 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3288 - (NSString *) name;
3295 - (void) addToCount;
3297 - (void) setCount:(size_t)count;
3298 - (NSString *) localized;
3302 @implementation Section
3306 if (localized_ != nil)
3307 [localized_ release];
3311 - (NSComparisonResult) compareByLocalized:(Section *)section {
3312 NSString *lhs(localized_);
3313 NSString *rhs([section localized]);
3315 /*if ([lhs length] != 0 && [rhs length] != 0) {
3316 unichar lhc = [lhs characterAtIndex:0];
3317 unichar rhc = [rhs characterAtIndex:0];
3319 if (isalpha(lhc) && !isalpha(rhc))
3320 return NSOrderedAscending;
3321 else if (!isalpha(lhc) && isalpha(rhc))
3322 return NSOrderedDescending;
3325 return [lhs compare:rhs options:LaxCompareOptions_];
3328 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3329 if ((self = [self initWithName:name localize:NO]) != nil) {
3330 if (localized != nil)
3331 localized_ = [localized retain];
3335 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3336 return [self initWithName:name row:0 localize:localize];
3339 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3340 if ((self = [super init]) != nil) {
3341 name_ = [name retain];
3345 localized_ = [LocalizeSection(name_) retain];
3349 /* XXX: localize the index thingees */
3350 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3351 if ((self = [super init]) != nil) {
3352 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3358 - (NSString *) name {
3378 - (void) addToCount {
3382 - (void) setCount:(size_t)count {
3386 - (NSString *) localized {
3393 static NSString *Colon_;
3394 static NSString *Elision_;
3395 static NSString *Error_;
3396 static NSString *Warning_;
3398 /* Database Implementation {{{ */
3399 @implementation Database
3401 + (Database *) sharedInstance {
3402 static Database *instance;
3403 if (instance == nil)
3404 instance = [[Database alloc] init];
3412 - (void) releasePackages {
3413 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3414 CFArrayRemoveAllValues(packages_);
3418 // XXX: actually implement this thing
3420 [sourceList_ release];
3421 [self releasePackages];
3422 apr_pool_destroy(pool_);
3423 NSRecycleZone(zone_);
3427 - (void) _readCydia:(NSNumber *)fd { _pooled
3428 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3429 std::istream is(&ib);
3432 static Pcre finish_r("^finish:([^:]*)$");
3434 while (std::getline(is, line)) {
3435 const char *data(line.c_str());
3436 size_t size = line.size();
3437 lprintf("C:%s\n", data);
3439 if (finish_r(data, size)) {
3440 NSString *finish = finish_r[1];
3441 int index = [Finishes_ indexOfObject:finish];
3442 if (index != INT_MAX && index > Finish_)
3450 - (void) _readStatus:(NSNumber *)fd { _pooled
3451 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3452 std::istream is(&ib);
3455 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3456 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3458 while (std::getline(is, line)) {
3459 const char *data(line.c_str());
3460 size_t size(line.size());
3461 lprintf("S:%s\n", data);
3463 if (conffile_r(data, size)) {
3464 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3465 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3466 } else if (strncmp(data, "status: ", 8) == 0) {
3467 // status: <package>: {unpacked,half-configured,installed}
3468 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3469 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3470 } else if (strncmp(data, "processing: ", 12) == 0) {
3471 // processing: configure: config-test
3472 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3473 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3474 } else if (pmstatus_r(data, size)) {
3475 std::string type([pmstatus_r[1] UTF8String]);
3477 NSString *package = pmstatus_r[2];
3478 if ([package isEqualToString:@"dpkg-exec"])
3481 float percent([pmstatus_r[3] floatValue]);
3482 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3484 NSString *string = pmstatus_r[4];
3486 if (type == "pmerror") {
3487 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3488 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3489 } else if (type == "pmstatus") {
3490 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3491 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3492 } else if (type == "pmconffile")
3493 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3495 lprintf("E:unknown pmstatus\n");
3497 lprintf("E:unknown status\n");
3503 - (void) _readOutput:(NSNumber *)fd { _pooled
3504 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3505 std::istream is(&ib);
3508 while (std::getline(is, line)) {
3509 lprintf("O:%s\n", line.c_str());
3511 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3512 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3522 - (Package *) packageWithName:(NSString *)name {
3523 @synchronized (self) {
3524 if (static_cast<pkgDepCache *>(cache_) == NULL)
3526 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3527 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3531 if ((self = [super init]) != nil) {
3538 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3539 apr_pool_create(&pool_, NULL);
3541 size_t capacity(MetaFile_->active_);
3547 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3548 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3552 _assert(pipe(fds) != -1);
3555 _config->Set("APT::Keep-Fds::", cydiafd_);
3556 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3559 detachNewThreadSelector:@selector(_readCydia:)
3561 withObject:[NSNumber numberWithInt:fds[0]]
3564 _assert(pipe(fds) != -1);
3568 detachNewThreadSelector:@selector(_readStatus:)
3570 withObject:[NSNumber numberWithInt:fds[0]]
3573 _assert(pipe(fds) != -1);
3574 _assert(dup2(fds[0], 0) != -1);
3575 _assert(close(fds[0]) != -1);
3577 input_ = fdopen(fds[1], "a");
3579 _assert(pipe(fds) != -1);
3580 _assert(dup2(fds[1], 1) != -1);
3581 _assert(close(fds[1]) != -1);
3584 detachNewThreadSelector:@selector(_readOutput:)
3586 withObject:[NSNumber numberWithInt:fds[0]]
3591 - (pkgCacheFile &) cache {
3595 - (pkgDepCache::Policy *) policy {
3599 - (pkgRecords *) records {
3603 - (pkgProblemResolver *) resolver {
3607 - (pkgAcquire &) fetcher {
3611 - (pkgSourceList &) list {
3615 - (NSArray *) packages {
3616 return (NSArray *) packages_;
3619 - (NSArray *) sources {
3623 - (Source *) sourceWithKey:(NSString *)key {
3624 for (Source *source in [self sources]) {
3625 if ([[source key] isEqualToString:key])
3630 - (bool) popErrorWithTitle:(NSString *)title {
3633 while (!_error->empty()) {
3635 bool warning(!_error->PopMessage(error));
3640 size_t size(error.size());
3641 if (size == 0 || error[size - 1] != '\n')
3643 error.resize(size - 1);
3646 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3648 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3654 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3655 return [self popErrorWithTitle:title] || !success;
3658 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3659 @synchronized (self) {
3662 [self releasePackages];
3665 [sourceList_ removeAllObjects];
3685 apr_pool_clear(pool_);
3687 NSRecycleZone(zone_);
3688 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3690 int chk(creat("/tmp/cydia.chk", 0644));
3694 if (invocation != nil)
3695 [invocation invoke];
3697 NSString *title(UCLocalize("DATABASE"));
3700 OpProgress progress;
3701 while (!cache_.Open(progress, true)) { pop:
3703 bool warning(!_error->PopMessage(error));
3704 lprintf("cache_.Open():[%s]\n", error.c_str());
3706 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3707 [delegate_ repairWithSelector:@selector(configure)];
3708 else if (error == "The package lists or status file could not be parsed or opened.")
3709 [delegate_ repairWithSelector:@selector(update)];
3710 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3711 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3712 // else if (error == "Malformed Status line")
3713 // else if (error == "The list of sources could not be read.")
3715 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3725 unlink("/tmp/cydia.chk");
3727 now_ = [[NSDate date] timeIntervalSince1970];
3729 policy_ = new pkgDepCache::Policy();
3730 records_ = new pkgRecords(cache_);
3731 resolver_ = new pkgProblemResolver(cache_);
3732 fetcher_ = new pkgAcquire(&status_);
3735 list_ = new pkgSourceList();
3736 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3739 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3740 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3744 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3747 if (cache_->BrokenCount() != 0) {
3748 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3751 if (cache_->BrokenCount() != 0) {
3752 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3756 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3760 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3761 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3762 [sourceList_ addObject:object];
3764 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3765 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3766 // XXX: this could be more intelligent
3767 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3768 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3770 sourceMap_[cached->ID] = object;
3775 /*std::vector<Package *> packages;
3776 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3777 [packages_ release];
3782 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3783 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3784 //packages.push_back(package);
3785 CFArrayAppendValue(packages_, [package retain]);
3789 /*if (packages.empty())
3790 packages_ = [[NSArray alloc] init];
3792 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3795 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3796 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3797 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3805 /*if (!packages.empty())
3806 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3807 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3809 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3811 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3813 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3817 size_t count(CFArrayGetCount(packages_));
3818 MetaFile_->active_ = count;
3820 for (size_t index(0); index != count; ++index)
3821 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3825 } } CYPoolEnd() _trace(); }
3828 @synchronized (self) {
3830 resolver_ = new pkgProblemResolver(cache_);
3832 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3833 if (!cache_[iterator].Keep())
3834 cache_->MarkKeep(iterator, false);
3835 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3836 cache_->SetReInstall(iterator, false);
3839 - (void) configure {
3840 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3842 system([dpkg UTF8String]);
3847 // XXX: I don't remember this condition
3852 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3854 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3856 if ([self popErrorWithTitle:title])
3860 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3863 public pkgArchiveCleaner
3866 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3871 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3878 fetcher_->Shutdown();
3880 pkgRecords records(cache_);
3882 lock_ = new FileFd();
3883 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3885 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3887 if ([self popErrorWithTitle:title])
3891 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3894 manager_ = (_system->CreatePM(cache_));
3895 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3902 bool substrate(RestartSubstrate_);
3903 RestartSubstrate_ = false;
3905 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3907 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3909 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3911 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3912 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3915 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3917 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3919 [self popErrorWithTitle:title];
3923 bool failed = false;
3924 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3925 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3927 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3933 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3941 RestartSubstrate_ = true;
3944 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3946 if (_error->PendingError()) {
3951 if (result == pkgPackageManager::Failed) {
3956 if (result != pkgPackageManager::Completed) {
3961 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3963 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3965 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3966 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3969 if (![before isEqualToArray:after])
3974 NSString *title(UCLocalize("UPGRADE"));
3975 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3981 [self updateWithStatus:status_];
3984 - (void) updateWithStatus:(Status &)status {
3985 NSString *title(UCLocalize("REFRESHING_DATA"));
3988 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3992 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3993 if ([self popErrorWithTitle:title])
3996 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3998 bool success(ListUpdate(status, list, PulseInterval_));
3999 if (status.WasCancelled())
4002 [self popErrorWithTitle:title forOperation:success];
4004 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4006 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
4010 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4011 delegate_ = delegate;
4014 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4015 progress_ = delegate;
4016 status_.setDelegate(delegate);
4019 - (NSObject<ProgressDelegate> *) progressDelegate {
4023 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4024 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4025 return i == sourceMap_.end() ? nil : i->second;
4028 - (NSString *) mappedSectionForPointer:(const char *)section {
4029 _H<NSString> *mapped;
4031 _profile(Database$mappedSectionForPointer$Cache)
4032 mapped = §ions_[section];
4035 if (*mapped == NULL) {
4036 size_t length(strlen(section));
4037 char spaced[length + 1];
4039 _profile(Database$mappedSectionForPointer$Replace)
4040 for (size_t index(0); index != length; ++index)
4041 spaced[index] = section[index] == '_' ? ' ' : section[index];
4042 spaced[length] = '\0';
4047 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4048 string = [NSString stringWithUTF8String:spaced];
4051 _profile(Database$mappedSectionForPointer$Map)
4052 string = [SectionMap_ objectForKey:string] ?: string;
4062 @interface Diversion : NSObject {
4065 _H<NSString> format_;
4070 @implementation Diversion
4072 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4073 if ((self = [super init]) != nil) {
4074 pattern_ = [from UTF8String];
4080 - (NSString *) divert:(NSString *)url {
4084 size_t count(pattern_.size());
4086 for (size_t i(0); i != count; ++i)
4087 values[i] = pattern_[i + 1];
4089 return [[[NSString alloc] initWithFormat:format_ arguments:reinterpret_cast<va_list>(values)] autorelease];
4092 - (NSString *) key {
4096 - (NSUInteger) hash {
4100 - (BOOL) isEqual:(Diversion *)object {
4101 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4106 @interface CydiaObject : NSObject {
4108 _transient id delegate_;
4111 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4115 @interface CYBrowserController : BrowserController {
4116 CydiaObject *cydia_;
4119 + (void) addDiversion:(Diversion *)diversion;
4123 static NSMutableSet *Diversions_;
4125 /* Web Scripting {{{ */
4126 @implementation CydiaObject
4129 [indirect_ release];
4133 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4134 if ((self = [super init]) != nil) {
4135 indirect_ = [indirect retain];
4139 - (void) setDelegate:(id)delegate {
4140 delegate_ = delegate;
4143 + (NSArray *) _attributeKeys {
4144 return [NSArray arrayWithObjects:
4159 - (NSArray *) attributeKeys {
4160 return [[self class] _attributeKeys];
4163 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4164 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4167 - (NSString *) version {
4171 - (NSString *) device {
4172 return [[UIDevice currentDevice] uniqueIdentifier];
4175 - (NSString *) firmware {
4176 return [[UIDevice currentDevice] systemVersion];
4179 - (NSString *) hostname {
4180 return [[UIDevice currentDevice] name];
4183 - (NSString *) idiom {
4184 return (id) Idiom_ ?: [NSNull null];
4187 - (NSString *) plmn {
4188 return (id) PLMN_ ?: [NSNull null];
4191 - (NSString *) ecid {
4192 return (id) ChipID_ ?: [NSNull null];
4195 - (NSString *) serial {
4196 return SerialNumber_;
4199 - (NSString *) role {
4200 return (id) Role_ ?: [NSNull null];
4203 - (NSString *) model {
4204 return [NSString stringWithUTF8String:Machine_];
4207 - (NSString *) token {
4208 return (id) Token_ ?: [NSNull null];
4211 + (NSString *) webScriptNameForSelector:(SEL)selector {
4213 else if (selector == @selector(addBridgedHost:))
4214 return @"addBridgedHost";
4215 else if (selector == @selector(addPipelinedHost:scheme:))
4216 return @"addPipelinedHost";
4217 else if (selector == @selector(addTrivialSource:))
4218 return @"addTrivialSource";
4219 else if (selector == @selector(close))
4221 else if (selector == @selector(divert::))
4223 else if (selector == @selector(du:))
4225 else if (selector == @selector(stringWithFormat:arguments:))
4227 else if (selector == @selector(getAllSources))
4228 return @"getAllSourcs";
4229 else if (selector == @selector(getKernelNumber:))
4230 return @"getKernelNumber";
4231 else if (selector == @selector(getKernelString:))
4232 return @"getKernelString";
4233 else if (selector == @selector(getInstalledPackages))
4234 return @"getInstalledPackages";
4235 else if (selector == @selector(getPackageById:))
4236 return @"getPackageById";
4237 else if (selector == @selector(getSessionValue:))
4238 return @"getSessionValue";
4239 else if (selector == @selector(installPackages:))
4240 return @"installPackages";
4241 else if (selector == @selector(localizedStringForKey:value:table:))
4243 else if (selector == @selector(popViewController:))
4244 return @"popViewController";
4245 else if (selector == @selector(refreshSources))
4246 return @"refreshSources";
4247 else if (selector == @selector(removeButton))
4248 return @"removeButton";
4249 else if (selector == @selector(setSessionValue::))
4250 return @"setSessionValue";
4251 else if (selector == @selector(substitutePackageNames:))
4252 return @"substitutePackageNames";
4253 else if (selector == @selector(scrollToBottom:))
4254 return @"scrollToBottom";
4255 else if (selector == @selector(setAllowsNavigationAction:))
4256 return @"setAllowsNavigationAction";
4257 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4258 return @"setButtonImage";
4259 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4260 return @"setButtonTitle";
4261 else if (selector == @selector(setHidesBackButton:))
4262 return @"setHidesBackButton";
4263 else if (selector == @selector(setHidesNavigationBar:))
4264 return @"setHidesNavigationBar";
4265 else if (selector == @selector(setNavigationBarStyle:))
4266 return @"setNavigationBarStyle";
4267 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4268 return @"setNavigationBarTintColor";
4269 else if (selector == @selector(setPopupHook:))
4270 return @"setPopupHook";
4271 else if (selector == @selector(setToken:))
4273 else if (selector == @selector(setViewportWidth:))
4274 return @"setViewportWidth";
4275 else if (selector == @selector(statfs:))
4277 else if (selector == @selector(supports:))
4283 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4284 return [self webScriptNameForSelector:selector] == nil;
4287 - (BOOL) supports:(NSString *)feature {
4288 return [feature isEqualToString:@"window.open"];
4291 - (void) divert:(NSString *)from :(NSString *)to {
4292 [CYBrowserController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4295 - (NSNumber *) getKernelNumber:(NSString *)name {
4296 const char *string([name UTF8String]);
4299 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4300 return (id) [NSNull null];
4302 if (size != sizeof(int))
4303 return (id) [NSNull null];
4306 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4307 return (id) [NSNull null];
4309 return [NSNumber numberWithInt:value];
4312 - (NSString *) getKernelString:(NSString *)name {
4313 const char *string([name UTF8String]);
4316 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4317 return (id) [NSNull null];
4319 char value[size + 1];
4320 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4321 return (id) [NSNull null];
4323 // XXX: just in case you request something ludicrous
4326 return [NSString stringWithCString:value];
4329 - (id) getSessionValue:(NSString *)key {
4330 @synchronized (SessionData_) {
4331 return [SessionData_ objectForKey:key];
4334 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4335 @synchronized (SessionData_) {
4336 if (value == (id) [WebUndefined undefined])
4337 [SessionData_ removeObjectForKey:key];
4339 [SessionData_ setObject:value forKey:key];
4342 - (void) addBridgedHost:(NSString *)host {
4343 @synchronized (HostConfig_) {
4344 [BridgedHosts_ addObject:host];
4347 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4348 @synchronized (HostConfig_) {
4349 if (scheme != (id) [WebUndefined undefined])
4350 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4352 [PipelinedHosts_ addObject:host];
4355 - (void) popViewController:(NSNumber *)value {
4356 if (value == (id) [WebUndefined undefined])
4357 value = [NSNumber numberWithBool:YES];
4358 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4361 - (void) addTrivialSource:(NSString *)href {
4362 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4365 - (void) refreshSources {
4366 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4369 - (NSArray *) getAllSources {
4370 return [[Database sharedInstance] sources];
4373 - (NSArray *) getInstalledPackages {
4374 Database *database([Database sharedInstance]);
4375 @synchronized (database) {
4376 NSArray *packages([database packages]);
4377 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4378 for (Package *package in packages)
4379 if (![package uninstalled])
4380 [installed addObject:package];
4384 - (Package *) getPackageById:(NSString *)id {
4385 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4389 return (Package *) [NSNull null];
4392 - (NSArray *) statfs:(NSString *)path {
4395 if (path == nil || statfs([path UTF8String], &stat) == -1)
4398 return [NSArray arrayWithObjects:
4399 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4400 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4401 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4405 - (NSNumber *) du:(NSString *)path {
4406 NSNumber *value(nil);
4409 _assert(pipe(fds) != -1);
4411 pid_t pid(ExecFork());
4413 _assert(dup2(fds[1], 1) != -1);
4414 _assert(close(fds[0]) != -1);
4415 _assert(close(fds[1]) != -1);
4416 /* XXX: this should probably not use du */
4417 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4422 _assert(close(fds[1]) != -1);
4424 if (FILE *du = fdopen(fds[0], "r")) {
4426 while (fgets(line, sizeof(line), du) != NULL) {
4427 size_t length(strlen(line));
4428 while (length != 0 && line[length - 1] == '\n')
4429 line[--length] = '\0';
4430 if (char *tab = strchr(line, '\t')) {
4432 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4437 } else _assert(close(fds[0]));
4441 if (waitpid(pid, &status, 0) == -1)
4444 else _assert(false);
4450 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4453 - (void) installPackages:(NSArray *)packages {
4454 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4457 - (NSString *) substitutePackageNames:(NSString *)message {
4458 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4459 for (size_t i(0), e([words count]); i != e; ++i) {
4460 NSString *word([words objectAtIndex:i]);
4461 if (Package *package = [[Database sharedInstance] packageWithName:word])
4462 [words replaceObjectAtIndex:i withObject:[package name]];
4465 return [words componentsJoinedByString:@" "];
4468 - (void) removeButton {
4469 [indirect_ removeButton];
4472 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4473 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4476 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4477 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4480 - (void) setAllowsNavigationAction:(NSString *)value {
4481 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4484 - (void) setHidesBackButton:(NSString *)value {
4485 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4488 - (void) setHidesNavigationBar:(NSString *)value {
4489 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4492 - (void) setNavigationBarStyle:(NSString *)value {
4493 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4496 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4497 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4498 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4499 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4502 - (void) _setToken:(NSString *)token {
4506 [Metadata_ removeObjectForKey:@"Token"];
4508 [Metadata_ setObject:Token_ forKey:@"Token"];
4513 - (void) setToken:(NSString *)token {
4514 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4517 - (void) setPopupHook:(id)function {
4518 [indirect_ setPopupHook:function];
4521 - (void) scrollToBottom:(NSNumber *)animated {
4522 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4525 - (void) setViewportWidth:(float)width {
4526 [indirect_ setViewportWidthOnMainThread:width];
4529 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4530 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4531 unsigned count([arguments count]);
4533 for (unsigned i(0); i != count; ++i)
4534 values[i] = [arguments objectAtIndex:i];
4535 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4538 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4539 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4541 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4543 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4549 /* @ Loading... Indicator {{{ */
4550 @interface CYLoadingIndicator : UIView {
4551 _H<UIActivityIndicatorView> spinner_;
4553 _H<UIView> container_;
4556 @property (readonly, nonatomic) UILabel *label;
4557 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4561 @implementation CYLoadingIndicator
4563 - (id) initWithFrame:(CGRect)frame {
4564 if ((self = [super initWithFrame:frame]) != nil) {
4565 container_ = [[[UIView alloc] init] autorelease];
4566 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4568 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4569 [spinner_ startAnimating];
4570 [container_ addSubview:spinner_];
4572 label_ = [[[UILabel alloc] init] autorelease];
4573 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4574 [label_ setBackgroundColor:[UIColor clearColor]];
4575 [label_ setTextColor:[UIColor blackColor]];
4576 [label_ setShadowColor:[UIColor whiteColor]];
4577 [label_ setShadowOffset:CGSizeMake(0, 1)];
4578 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4579 [container_ addSubview:label_];
4581 CGSize viewsize = frame.size;
4582 CGSize spinnersize = [spinner_ bounds].size;
4583 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4584 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4586 CGRect containrect = {
4587 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4588 CGSizeMake(bothwidth, spinnersize.height)
4591 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4599 [container_ setFrame:containrect];
4600 [spinner_ setFrame:spinrect];
4601 [label_ setFrame:textrect];
4602 [self addSubview:container_];
4606 - (UILabel *) label {
4610 - (UIActivityIndicatorView *) activityIndicatorView {
4616 /* Emulated Loading Controller {{{ */
4617 @interface CYEmulatedLoadingController : CYViewController {
4618 _transient Database *database_;
4619 _H<CYLoadingIndicator> indicator_;
4620 _H<UITabBar> tabbar_;
4621 _H<UINavigationBar> navbar_;
4626 @implementation CYEmulatedLoadingController
4628 - (id) initWithDatabase:(Database *)database {
4629 if ((self = [super init]) != nil) {
4630 database_ = database;
4635 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4637 UITableView *table([[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]);
4638 [table setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4639 [[self view] addSubview:table];
4641 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4642 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4643 [[self view] addSubview:indicator_];
4645 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4646 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4647 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4648 [[self view] addSubview:tabbar_];
4650 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4651 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4652 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4653 [[self view] addSubview:navbar_];
4656 - (void) releaseSubviews {
4665 /* Cydia Browser Controller {{{ */
4666 @implementation CYBrowserController
4673 - (NSURL *) navigationURL {
4674 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4677 + (void) initialize {
4678 Diversions_ = [[NSMutableSet alloc] initWithCapacity:0];
4681 + (void) addDiversion:(Diversion *)diversion {
4682 [Diversions_ addObject:diversion];
4685 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4686 [super webView:view didClearWindowObject:window forFrame:frame];
4688 WebDataSource *source([frame dataSource]);
4689 NSURLResponse *response([source response]);
4690 NSURL *url([response URL]);
4692 @synchronized (HostConfig_) {
4693 if ([[[url scheme] lowercaseString] isEqualToString:@"https"])
4694 if ([BridgedHosts_ containsObject:[url host]])
4695 [window setValue:cydia_ forKey:@"cydia"];
4699 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4700 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4703 NSURL *url([copy URL]);
4704 NSString *href([url absoluteString]);
4706 for (Diversion *diversion in Diversions_)
4707 if (NSString *diverted = [diversion divert:href]) {
4708 [copy setURL:[NSURL URLWithString:diverted]];
4712 if (System_ != NULL)
4713 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4714 if (Machine_ != NULL)
4715 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4717 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4722 - (void) setDelegate:(id)delegate {
4723 [super setDelegate:delegate];
4724 [cydia_ setDelegate:delegate];
4728 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4729 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4731 WebView *webview([[webview_ _documentView] webView]);
4733 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4736 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4738 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4739 if (Product_ != nil)
4740 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4742 [webview setApplicationNameForUserAgent:application];
4750 @interface NSObject (CydiaScript)
4751 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4754 @implementation NSObject (CydiaScript)
4756 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4762 @implementation NSArray (CydiaScript)
4764 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4765 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4766 for (size_t i(0), e([self count]); i != e; ++i)
4767 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4773 @implementation NSDictionary (CydiaScript)
4775 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4776 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4778 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4785 /* Confirmation Controller {{{ */
4786 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4787 if (!iterator.end())
4788 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4789 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4791 pkgCache::PkgIterator package(dep.TargetPkg());
4794 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4801 @protocol ConfirmationControllerDelegate
4802 - (void) cancelAndClear:(bool)clear;
4803 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4807 @interface ConfirmationController : CYBrowserController {
4808 _transient Database *database_;
4810 UIAlertView *essential_;
4812 NSDictionary *changes_;
4813 NSMutableArray *issues_;
4814 NSDictionary *sizes_;
4819 - (id) initWithDatabase:(Database *)database;
4823 @implementation ConfirmationController
4830 if (essential_ != nil)
4831 [essential_ release];
4838 RestartSubstrate_ = true;
4839 [delegate_ confirmWithNavigationController:[self navigationController]];
4842 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4843 NSString *context([alert context]);
4845 if ([context isEqualToString:@"remove"]) {
4846 if (button == [alert cancelButtonIndex])
4847 [self dismissModalViewControllerAnimated:YES];
4848 else if (button == [alert firstOtherButtonIndex]) {
4852 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4853 } else if ([context isEqualToString:@"unable"]) {
4854 [self dismissModalViewControllerAnimated:YES];
4855 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4857 [super alertView:alert clickedButtonAtIndex:button];
4861 - (void) _doContinue {
4862 [self dismissModalViewControllerAnimated:YES];
4863 [delegate_ cancelAndClear:NO];
4866 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4867 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4871 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4872 [super webView:view didClearWindowObject:window forFrame:frame];
4874 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4875 changes_, @"changes",
4879 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4882 - (id) initWithDatabase:(Database *)database {
4883 if ((self = [super init]) != nil) {
4884 database_ = database;
4886 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4887 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4888 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4889 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4890 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4894 pkgCacheFile &cache([database_ cache]);
4895 NSArray *packages([database_ packages]);
4896 pkgDepCache::Policy *policy([database_ policy]);
4898 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4900 for (Package *package in packages) {
4901 pkgCache::PkgIterator iterator([package iterator]);
4902 NSString *name([package id]);
4904 if ([package broken]) {
4905 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4907 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4909 reasons, @"reasons",
4912 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4916 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4917 pkgCache::DepIterator start;
4918 pkgCache::DepIterator end;
4919 dep.GlobOr(start, end); // ++dep
4921 if (!cache->IsImportantDep(end))
4923 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4926 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4928 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4929 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4930 clauses, @"clauses",
4934 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4936 pkgCache::PkgIterator target(start.TargetPkg());
4937 if (target->ProvidesList != 0)
4938 reason = @"missing";
4940 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4942 reason = @"installed";
4943 installed = [NSString stringWithUTF8String:ver.VerStr()];
4944 } else if (!cache[target].CandidateVerIter(cache).end())
4945 reason = @"uninstalled";
4946 else if (target->ProvidesList == 0)
4947 reason = @"uninstallable";
4949 reason = @"virtual";
4952 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4953 [NSString stringWithUTF8String:start.CompType()], @"operator",
4954 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4957 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4958 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4959 version, @"version",
4961 installed, @"installed",
4964 // yes, seriously. (wtf?)
4972 pkgDepCache::StateCache &state(cache[iterator]);
4974 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4976 if (state.NewInstall())
4977 [installs addObject:name];
4978 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4979 [reinstalls addObject:name];
4980 else if (state.Upgrade())
4981 [upgrades addObject:name];
4982 else if (state.Downgrade())
4983 [downgrades addObject:name];
4984 else if (!state.Delete())
4986 else if (special_r(name))
4987 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4988 [NSNull null], @"package",
4989 [NSArray arrayWithObjects:
4990 [NSDictionary dictionaryWithObjectsAndKeys:
4991 @"Conflicts", @"relationship",
4992 [NSArray arrayWithObjects:
4993 [NSDictionary dictionaryWithObjectsAndKeys:
4995 [NSNull null], @"version",
4996 @"installed", @"reason",
5003 if ([package essential])
5005 [removes addObject:name];
5008 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5009 substrate_ |= DepSubstrate(iterator.CurrentVer());
5014 else if (Advanced_) {
5015 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5017 essential_ = [[UIAlertView alloc]
5018 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5019 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5021 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5023 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5027 [essential_ setContext:@"remove"];
5029 essential_ = [[UIAlertView alloc]
5030 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5031 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5033 cancelButtonTitle:UCLocalize("OKAY")
5034 otherButtonTitles:nil
5037 [essential_ setContext:@"unable"];
5040 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
5041 installs, @"installs",
5042 reinstalls, @"reinstalls",
5043 upgrades, @"upgrades",
5044 downgrades, @"downgrades",
5045 removes, @"removes",
5048 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
5049 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5050 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5053 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5055 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
5056 initWithTitle:UCLocalize("CANCEL")
5057 style:UIBarButtonItemStylePlain
5059 action:@selector(cancelButtonClicked)
5065 - (void) applyRightButton {
5066 if ([issues_ count] == 0 && ![self isLoading])
5067 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5068 initWithTitle:UCLocalize("CONFIRM")
5069 style:UIBarButtonItemStyleDone
5071 action:@selector(confirmButtonClicked)
5074 [[self navigationItem] setRightBarButtonItem:nil];
5078 - (void) cancelButtonClicked {
5079 [self dismissModalViewControllerAnimated:YES];
5080 [delegate_ cancelAndClear:YES];
5084 - (void) confirmButtonClicked {
5085 if (essential_ != nil)
5095 /* Progress Data {{{ */
5096 @interface CydiaProgressData : NSObject {
5097 _transient id delegate_;
5106 _H<NSMutableArray> events_;
5107 _H<NSString> title_;
5109 _H<NSString> status_;
5110 _H<NSString> finish_;
5115 @implementation CydiaProgressData
5117 + (NSArray *) _attributeKeys {
5118 return [NSArray arrayWithObjects:
5130 - (NSArray *) attributeKeys {
5131 return [[self class] _attributeKeys];
5134 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5135 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5139 if ((self = [super init]) != nil) {
5140 events_ = [NSMutableArray arrayWithCapacity:32];
5144 - (void) setDelegate:(id)delegate {
5145 delegate_ = delegate;
5148 - (void) setPercent:(float)value {
5152 - (NSNumber *) percent {
5153 return [NSNumber numberWithFloat:percent_];
5156 - (void) setCurrent:(float)value {
5160 - (NSNumber *) current {
5161 return [NSNumber numberWithFloat:current_];
5164 - (void) setTotal:(float)value {
5168 - (NSNumber *) total {
5169 return [NSNumber numberWithFloat:total_];
5172 - (void) setSpeed:(float)value {
5176 - (NSNumber *) speed {
5177 return [NSNumber numberWithFloat:speed_];
5180 - (NSArray *) events {
5184 - (void) removeAllEvents {
5185 [events_ removeAllObjects];
5188 - (void) addEvent:(CydiaProgressEvent *)event {
5189 [events_ addObject:event];
5192 - (void) setTitle:(NSString *)text {
5196 - (NSString *) title {
5200 - (void) setFinish:(NSString *)text {
5204 - (NSString *) finish {
5205 return (id) finish_ ?: [NSNull null];
5208 - (void) setRunning:(bool)running {
5212 - (NSNumber *) running {
5213 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5218 /* Progress Controller {{{ */
5219 @interface ProgressController : CYBrowserController <
5222 _transient Database *database_;
5223 _H<CydiaProgressData> progress_;
5227 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5229 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5231 - (void) setTitle:(NSString *)title;
5232 - (void) setCancellable:(bool)cancellable;
5236 @implementation ProgressController
5239 [database_ setProgressDelegate:nil];
5240 [progress_ setDelegate:nil];
5244 - (void) updateCancel {
5245 [[self navigationItem] setLeftBarButtonItem:(cancel_ == 1 ? [[[UIBarButtonItem alloc]
5246 initWithTitle:UCLocalize("CANCEL")
5247 style:UIBarButtonItemStylePlain
5249 action:@selector(cancel)
5250 ] autorelease] : nil)];
5253 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5254 if ((self = [super init]) != nil) {
5255 database_ = database;
5256 delegate_ = delegate;
5258 [database_ setProgressDelegate:self];
5260 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5261 [progress_ setDelegate:self];
5263 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5265 [scroller_ setBackgroundColor:[UIColor blackColor]];
5267 [[self navigationItem] setHidesBackButton:YES];
5269 [self updateCancel];
5273 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5274 [super webView:view didClearWindowObject:window forFrame:frame];
5275 [window setValue:progress_ forKey:@"cydiaProgress"];
5278 - (void) updateProgress {
5279 [self dispatchEvent:@"CydiaProgressUpdate"];
5282 - (void) viewWillAppear:(BOOL)animated {
5283 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5284 [super viewWillAppear:animated];
5288 UpdateExternalStatus(0);
5295 [delegate_ terminateWithSuccess];
5296 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5297 [delegate_ suspendWithAnimation:YES];
5299 [delegate_ suspend];*/
5311 system("/usr/bin/sbreload");
5317 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5318 SBReboot(SBSSpringBoardServerPort());
5320 reboot2(RB_AUTOBOOT);
5327 - (void) setTitle:(NSString *)title {
5328 [progress_ setTitle:title];
5329 [self updateProgress];
5332 - (UIBarButtonItem *) rightButton {
5333 return [[progress_ running] boolValue] ? nil : [[[UIBarButtonItem alloc]
5334 initWithTitle:UCLocalize("CLOSE")
5335 style:UIBarButtonItemStylePlain
5337 action:@selector(close)
5341 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5342 UpdateExternalStatus(1);
5344 [progress_ setRunning:true];
5345 [self setTitle:title];
5346 // implicit updateProgress
5348 SHA1SumValue notifyconf; {
5350 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5353 MMap mmap(file, MMap::ReadOnly);
5355 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5356 notifyconf = sha1.Result();
5360 SHA1SumValue springlist; {
5362 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5365 MMap mmap(file, MMap::ReadOnly);
5367 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5368 springlist = sha1.Result();
5372 if (invocation != nil) {
5373 [invocation yieldToSelector:@selector(invoke)];
5374 [self setTitle:@"COMPLETE"];
5379 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5382 MMap mmap(file, MMap::ReadOnly);
5384 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5385 if (!(notifyconf == sha1.Result()))
5392 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5395 MMap mmap(file, MMap::ReadOnly);
5397 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5398 if (!(springlist == sha1.Result()))
5404 if (RestartSubstrate_)
5408 RestartSubstrate_ = false;
5411 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5412 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5413 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5414 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5415 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5419 system("su -c /usr/bin/uicache mobile");
5422 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5424 [progress_ setRunning:false];
5425 [self updateProgress];
5427 [self applyRightButton];
5430 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5431 [progress_ addEvent:event];
5432 [self updateProgress];
5435 - (bool) isProgressCancelled {
5436 return cancel_ == 2;
5441 [self updateCancel];
5444 - (void) setCancellable:(bool)cancellable {
5445 unsigned cancel(cancel_);
5449 else if (cancel_ == 0)
5452 if (cancel != cancel_)
5453 [self updateCancel];
5456 - (void) setProgressCancellable:(NSNumber *)cancellable {
5457 [self setCancellable:[cancellable boolValue]];
5460 - (void) setProgressPercent:(NSNumber *)percent {
5461 [progress_ setPercent:[percent floatValue]];
5462 [self updateProgress];
5465 - (void) setProgressStatus:(NSDictionary *)status {
5466 if (status == nil) {
5467 [progress_ setCurrent:0];
5468 [progress_ setTotal:0];
5469 [progress_ setSpeed:0];
5471 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5473 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5474 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5475 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5478 [self updateProgress];
5484 /* Cell Content View {{{ */
5485 @protocol ContentDelegate
5486 - (void) drawContentRect:(CGRect)rect;
5489 @interface ContentView : UIView {
5490 _transient id<ContentDelegate> delegate_;
5495 @implementation ContentView
5497 - (id) initWithFrame:(CGRect)frame {
5498 if ((self = [super initWithFrame:frame]) != nil) {
5499 [self setNeedsDisplayOnBoundsChange:YES];
5503 - (void) setDelegate:(id<ContentDelegate>)delegate {
5504 delegate_ = delegate;
5507 - (void) drawRect:(CGRect)rect {
5508 [super drawRect:rect];
5509 [delegate_ drawContentRect:rect];
5514 /* Cydia TableView Cell {{{ */
5515 @interface CYTableViewCell : UITableViewCell {
5516 ContentView *content_;
5522 @implementation CYTableViewCell
5529 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5530 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5532 if (view == content_) {
5533 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5534 highlighted_ = highlighted;
5537 [super _updateHighlightColorsForView:view highlighted:highlighted];
5540 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5541 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5542 highlighted_ = selected;
5544 [super setSelected:selected animated:animated];
5545 [content_ setNeedsDisplay];
5551 /* Package Cell {{{ */
5552 @interface PackageCell : CYTableViewCell <
5557 NSString *description_;
5565 - (PackageCell *) init;
5566 - (void) setPackage:(Package *)package;
5568 - (void) drawContentRect:(CGRect)rect;
5572 @implementation PackageCell
5574 - (void) clearPackage {
5585 if (description_ != nil) {
5586 [description_ release];
5590 if (source_ != nil) {
5595 if (badge_ != nil) {
5600 if (placard_ != nil) {
5610 [self clearPackage];
5614 - (PackageCell *) init {
5615 CGRect frame(CGRectMake(0, 0, 320, 74));
5616 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5617 UIView *content([self contentView]);
5618 CGRect bounds([content bounds]);
5620 content_ = [[ContentView alloc] initWithFrame:bounds];
5621 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5622 [content addSubview:content_];
5624 [content_ setDelegate:self];
5625 [content_ setOpaque:YES];
5629 - (NSString *) accessibilityLabel {
5630 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5633 - (void) setPackage:(Package *)package {
5634 [self clearPackage];
5637 Source *source = [package source];
5639 icon_ = [[package icon] retain];
5640 name_ = [[package name] retain];
5643 description_ = [package longDescription];
5644 if (description_ == nil)
5645 description_ = [package shortDescription];
5646 if (description_ != nil)
5647 description_ = [description_ retain];
5649 commercial_ = [package isCommercial];
5651 package_ = [package retain];
5653 NSString *label = nil;
5654 bool trusted = false;
5656 if (source != nil) {
5657 label = [source label];
5658 trusted = [source trusted];
5659 } else if ([[package id] isEqualToString:@"firmware"])
5660 label = UCLocalize("APPLE");
5662 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5664 NSString *from(label);
5666 NSString *section = [package simpleSection];
5667 if (section != nil && ![section isEqualToString:label]) {
5668 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5669 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5672 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5673 source_ = [from retain];
5675 if (NSString *purpose = [package primaryPurpose])
5676 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5677 badge_ = [badge_ retain];
5682 if (NSString *mode = [package_ mode]) {
5683 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5684 color = RemovingColor_;
5685 //placard = @"removing";
5687 color = InstallingColor_;
5688 //placard = @"installing";
5691 // XXX: the removing/installing placards are not @2x
5694 color = [UIColor whiteColor];
5696 if ([package installed] != nil)
5697 placard = @"installed";
5702 [content_ setBackgroundColor:color];
5705 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5706 placard_ = [placard_ retain];
5708 [self setNeedsDisplay];
5709 [content_ setNeedsDisplay];
5712 - (void) drawContentRect:(CGRect)rect {
5713 bool highlighted(highlighted_);
5714 float width([self bounds].size.width);
5717 CGContextRef context(UIGraphicsGetCurrentContext());
5718 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5719 CGContextFillRect(context, rect);
5724 rect.size = [icon_ size];
5726 rect.size.width /= 2;
5727 rect.size.height /= 2;
5729 rect.origin.x = 25 - rect.size.width / 2;
5730 rect.origin.y = 25 - rect.size.height / 2;
5732 [icon_ drawInRect:rect];
5735 if (badge_ != nil) {
5737 rect.size = [badge_ size];
5739 rect.size.width /= 2;
5740 rect.size.height /= 2;
5742 rect.origin.x = 36 - rect.size.width / 2;
5743 rect.origin.y = 36 - rect.size.height / 2;
5745 [badge_ drawInRect:rect];
5752 UISetColor(commercial_ ? Purple_ : Black_);
5753 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5754 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5757 UISetColor(commercial_ ? Purplish_ : Gray_);
5758 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5760 if (placard_ != nil)
5761 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5766 /* Section Cell {{{ */
5767 @interface SectionCell : CYTableViewCell <
5779 - (void) setSection:(Section *)section editing:(BOOL)editing;
5783 @implementation SectionCell
5785 - (void) clearSection {
5786 if (basic_ != nil) {
5791 if (section_ != nil) {
5801 if (count_ != nil) {
5808 [self clearSection];
5814 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5815 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5816 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5817 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5818 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5820 UIView *content([self contentView]);
5821 CGRect bounds([content bounds]);
5823 content_ = [[ContentView alloc] initWithFrame:bounds];
5824 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5825 [content addSubview:content_];
5826 [content_ setBackgroundColor:[UIColor whiteColor]];
5828 [content_ setDelegate:self];
5832 - (void) onSwitch:(id)sender {
5833 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5834 if (metadata == nil) {
5835 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5836 [Sections_ setObject:metadata forKey:basic_];
5839 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5843 - (void) setSection:(Section *)section editing:(BOOL)editing {
5844 if (editing != editing_) {
5846 [switch_ removeFromSuperview];
5848 [self addSubview:switch_];
5852 [self clearSection];
5854 if (section == nil) {
5855 name_ = [UCLocalize("ALL_PACKAGES") retain];
5858 basic_ = [section name];
5860 basic_ = [basic_ retain];
5862 section_ = [section localized];
5863 if (section_ != nil)
5864 section_ = [section_ retain];
5866 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5867 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5870 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5873 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5874 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5876 [content_ setNeedsDisplay];
5879 - (void) setFrame:(CGRect)frame {
5880 [super setFrame:frame];
5882 CGRect rect([switch_ frame]);
5883 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5886 - (NSString *) accessibilityLabel {
5890 - (void) drawContentRect:(CGRect)rect {
5891 bool highlighted(highlighted_ && !editing_);
5893 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5898 float width(rect.size.width);
5904 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5906 CGSize size = [count_ sizeWithFont:Font14_];
5910 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5916 /* File Table {{{ */
5917 @interface FileTable : CYViewController <
5918 UITableViewDataSource,
5921 _transient Database *database_;
5924 NSMutableArray *files_;
5928 - (id) initWithDatabase:(Database *)database;
5929 - (void) setPackage:(Package *)package;
5933 @implementation FileTable
5936 [self releaseSubviews];
5945 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5946 return files_ == nil ? 0 : [files_ count];
5949 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5953 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5954 static NSString *reuseIdentifier = @"Cell";
5956 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5958 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5959 [cell setFont:[UIFont systemFontOfSize:16]];
5961 [cell setText:[files_ objectAtIndex:indexPath.row]];
5962 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5967 - (NSURL *) navigationURL {
5968 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5972 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5974 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5975 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5976 [list_ setRowHeight:24.0f];
5977 [list_ setDataSource:self];
5978 [list_ setDelegate:self];
5979 [[self view] addSubview:list_];
5982 - (void) viewDidLoad {
5983 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5986 - (void) releaseSubviews {
5991 - (id) initWithDatabase:(Database *)database {
5992 if ((self = [super init]) != nil) {
5993 database_ = database;
5995 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5999 - (void) setPackage:(Package *)package {
6000 if (package_ != nil) {
6001 [package_ autorelease];
6010 [files_ removeAllObjects];
6012 if (package != nil) {
6013 package_ = [package retain];
6014 name_ = [[package id] retain];
6016 if (NSArray *files = [package files])
6017 [files_ addObjectsFromArray:files];
6019 if ([files_ count] != 0) {
6020 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6021 [files_ removeObjectAtIndex:0];
6022 [files_ sortUsingSelector:@selector(compareByPath:)];
6024 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6025 [stack addObject:@"/"];
6027 for (int i(0), e([files_ count]); i != e; ++i) {
6028 NSString *file = [files_ objectAtIndex:i];
6029 while (![file hasPrefix:[stack lastObject]])
6030 [stack removeLastObject];
6031 NSString *directory = [stack lastObject];
6032 [stack addObject:[file stringByAppendingString:@"/"]];
6033 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6034 ([stack count] - 2) * 3, "",
6035 [file substringFromIndex:[directory length]]
6044 - (void) reloadData {
6047 [self setPackage:[database_ packageWithName:name_]];
6052 /* Package Controller {{{ */
6053 @interface CYPackageController : CYBrowserController <
6054 UIActionSheetDelegate
6056 _transient Database *database_;
6057 _H<Package> package_;
6060 _H<NSMutableArray> buttons_;
6061 _H<UIBarButtonItem> button_;
6064 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
6068 @implementation CYPackageController
6070 - (NSURL *) navigationURL {
6071 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6074 /* XXX: this is not safe at all... localization of /fail/ */
6075 - (void) _clickButtonWithName:(NSString *)name {
6076 if ([name isEqualToString:UCLocalize("CLEAR")])
6077 [delegate_ clearPackage:package_];
6078 else if ([name isEqualToString:UCLocalize("INSTALL")])
6079 [delegate_ installPackage:package_];
6080 else if ([name isEqualToString:UCLocalize("REINSTALL")])
6081 [delegate_ installPackage:package_];
6082 else if ([name isEqualToString:UCLocalize("REMOVE")])
6083 [delegate_ removePackage:package_];
6084 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6085 [delegate_ installPackage:package_];
6086 else _assert(false);
6089 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6090 NSString *context([sheet context]);
6092 if ([context isEqualToString:@"modify"]) {
6093 if (button != [sheet cancelButtonIndex]) {
6094 NSString *buttonName = [buttons_ objectAtIndex:button];
6095 [self _clickButtonWithName:buttonName];
6098 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6102 - (bool) _allowJavaScriptPanel {
6107 - (void) _customButtonClicked {
6108 int count([buttons_ count]);
6113 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6115 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6116 [buttons addObjectsFromArray:buttons_];
6118 UIActionSheet *sheet = [[[UIActionSheet alloc]
6121 cancelButtonTitle:nil
6122 destructiveButtonTitle:nil
6123 otherButtonTitles:nil
6126 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6128 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6129 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6131 [sheet setContext:@"modify"];
6133 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6137 // We don't want to allow non-commercial packages to do custom things to the install button,
6138 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6139 - (void) customButtonClicked {
6141 [super customButtonClicked];
6143 [self _customButtonClicked];
6146 - (void) reloadButtonClicked {
6147 // Don't reload a commerical package by tapping the loading button,
6148 // but if it's not an Install button, we should forward it on.
6149 if (![package_ uninstalled])
6150 [self _customButtonClicked];
6153 - (void) applyLoadingTitle {
6154 // Don't show "Loading" as the title. Ever.
6157 - (UIBarButtonItem *) rightButton {
6162 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
6163 if ((self = [super init]) != nil) {
6164 database_ = database;
6165 buttons_ = [NSMutableArray arrayWithCapacity:4];
6166 name_ = [NSString stringWithString:name];
6167 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
6171 - (void) reloadData {
6174 package_ = [database_ packageWithName:name_];
6176 [buttons_ removeAllObjects];
6178 if (package_ != nil) {
6179 [(Package *) package_ parse];
6181 commercial_ = [package_ isCommercial];
6183 if ([package_ mode] != nil)
6184 [buttons_ addObject:UCLocalize("CLEAR")];
6185 if ([package_ source] == nil);
6186 else if ([package_ upgradableAndEssential:NO])
6187 [buttons_ addObject:UCLocalize("UPGRADE")];
6188 else if ([package_ uninstalled])
6189 [buttons_ addObject:UCLocalize("INSTALL")];
6191 [buttons_ addObject:UCLocalize("REINSTALL")];
6192 if (![package_ uninstalled])
6193 [buttons_ addObject:UCLocalize("REMOVE")];
6197 switch ([buttons_ count]) {
6198 case 0: title = nil; break;
6199 case 1: title = [buttons_ objectAtIndex:0]; break;
6200 default: title = UCLocalize("MODIFY"); break;
6203 button_ = [[[UIBarButtonItem alloc]
6205 style:UIBarButtonItemStylePlain
6207 action:@selector(customButtonClicked)
6211 - (bool) isLoading {
6212 return commercial_ ? [super isLoading] : false;
6218 /* Package List Controller {{{ */
6219 @interface PackageListController : CYViewController <
6220 UITableViewDataSource,
6223 _transient Database *database_;
6225 NSMutableArray *packages_;
6226 NSMutableArray *sections_;
6228 NSMutableArray *index_;
6229 NSMutableDictionary *indices_;
6233 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6234 - (void) setDelegate:(id)delegate;
6235 - (void) resetCursor;
6239 @implementation PackageListController
6242 [packages_ release];
6243 [sections_ release];
6252 - (void) deselectWithAnimation:(BOOL)animated {
6253 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6256 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6257 CGRect base = [[self view] bounds];
6258 base.size.height -= bounds.size.height;
6259 base.origin = [list_ frame].origin;
6261 [UIView beginAnimations:nil context:NULL];
6262 [UIView setAnimationBeginsFromCurrentState:YES];
6263 [UIView setAnimationCurve:curve];
6264 [UIView setAnimationDuration:duration];
6265 [list_ setFrame:base];
6266 [UIView commitAnimations];
6269 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6270 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6273 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6274 [self resizeForKeyboardBounds:bounds duration:0];
6277 - (void) keyboardWillShow:(NSNotification *)notification {
6280 NSTimeInterval duration;
6281 UIViewAnimationCurve curve;
6282 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6283 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6284 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6285 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6287 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);
6288 UIViewController *base = self;
6289 while ([base parentViewController] != nil)
6290 base = [base parentViewController];
6291 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6292 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6294 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6297 - (void) keyboardWillHide:(NSNotification *)notification {
6298 NSTimeInterval duration;
6299 UIViewAnimationCurve curve;
6300 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6301 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6303 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6306 - (void) viewWillAppear:(BOOL)animated {
6307 [super viewWillAppear:animated];
6309 [self resizeForKeyboardBounds:CGRectZero];
6310 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6311 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6314 - (void) viewWillDisappear:(BOOL)animated {
6315 [super viewWillDisappear:animated];
6317 [self resizeForKeyboardBounds:CGRectZero];
6318 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6319 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6322 - (void) viewDidAppear:(BOOL)animated {
6323 [super viewDidAppear:animated];
6324 [self deselectWithAnimation:animated];
6327 - (void) didSelectPackage:(Package *)package {
6328 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6329 [view setDelegate:delegate_];
6330 [[self navigationController] pushViewController:view animated:YES];
6333 #if TryIndexedCollation
6334 + (BOOL) hasIndexedCollation {
6335 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6339 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6340 NSInteger count([sections_ count]);
6341 return count == 0 ? 1 : count;
6344 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6345 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6347 return [[sections_ objectAtIndex:section] name];
6350 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6351 if ([sections_ count] == 0)
6353 return [[sections_ objectAtIndex:section] count];
6356 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6357 @synchronized (database_) {
6358 if ([database_ era] != era_)
6361 Section *section([sections_ objectAtIndex:[path section]]);
6362 NSInteger row([path row]);
6363 Package *package([packages_ objectAtIndex:([section row] + row)]);
6364 return [[package retain] autorelease];
6367 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6368 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6370 cell = [[[PackageCell alloc] init] autorelease];
6371 [cell setPackage:[self packageAtIndexPath:path]];
6375 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6376 Package *package([self packageAtIndexPath:path]);
6377 package = [database_ packageWithName:[package id]];
6378 [self didSelectPackage:package];
6381 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6382 // XXX: is 20 the most optimal number here?
6383 return [packages_ count] > 20 ? index_ : nil;
6386 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6387 #if TryIndexedCollation
6388 if ([[self class] hasIndexedCollation]) {
6389 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6396 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6397 if ((self = [super init]) != nil) {
6398 database_ = database;
6399 title_ = [title copy];
6400 [[self navigationItem] setTitle:title_];
6402 #if TryIndexedCollation
6403 if ([[self class] hasIndexedCollation])
6404 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6407 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6409 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6411 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6412 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6414 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6415 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6416 [list_ setRowHeight:73];
6417 [[self view] addSubview:list_];
6419 [list_ setDataSource:self];
6420 [list_ setDelegate:self];
6424 - (void) setDelegate:(id)delegate {
6425 delegate_ = delegate;
6428 - (bool) hasPackage:(Package *)package {
6432 - (void) reloadData {
6435 era_ = [database_ era];
6436 NSArray *packages = [database_ packages];
6438 [packages_ removeAllObjects];
6439 [sections_ removeAllObjects];
6441 _profile(PackageTable$reloadData$Filter)
6442 for (Package *package in packages)
6443 if ([self hasPackage:package])
6444 [packages_ addObject:package];
6447 [indices_ removeAllObjects];
6449 Section *section = nil;
6451 #if TryIndexedCollation
6452 if ([[self class] hasIndexedCollation]) {
6453 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6454 NSArray *titles = [collation sectionIndexTitles];
6457 _profile(PackageTable$reloadData$Section)
6458 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6462 _profile(PackageTable$reloadData$Section$Package)
6463 package = [packages_ objectAtIndex:offset];
6464 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6467 while (secidx < index) {
6470 _profile(PackageTable$reloadData$Section$Allocate)
6471 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6474 _profile(PackageTable$reloadData$Section$Add)
6475 [sections_ addObject:section];
6479 [section addToCount];
6485 [index_ removeAllObjects];
6487 _profile(PackageTable$reloadData$Section)
6488 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6492 _profile(PackageTable$reloadData$Section$Package)
6493 package = [packages_ objectAtIndex:offset];
6494 index = [package index];
6497 if (section == nil || [section index] != index) {
6498 _profile(PackageTable$reloadData$Section$Allocate)
6499 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6502 [index_ addObject:[section name]];
6503 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6505 _profile(PackageTable$reloadData$Section$Add)
6506 [sections_ addObject:section];
6510 [section addToCount];
6515 _profile(PackageTable$reloadData$List)
6520 - (void) resetCursor {
6521 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6526 /* Filtered Package List Controller {{{ */
6527 @interface FilteredPackageListController : PackageListController {
6533 - (void) setObject:(id)object;
6534 - (void) setObject:(id)object forFilter:(SEL)filter;
6536 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6540 @implementation FilteredPackageListController
6548 - (void) setFilter:(SEL)filter {
6551 /* XXX: this is an unsafe optimization of doomy hell */
6552 Method method(class_getInstanceMethod([Package class], filter));
6553 _assert(method != NULL);
6554 imp_ = method_getImplementation(method);
6555 _assert(imp_ != NULL);
6558 - (void) setObject:(id)object {
6564 object_ = [object retain];
6567 - (void) setObject:(id)object forFilter:(SEL)filter {
6568 [self setFilter:filter];
6569 [self setObject:object];
6572 - (bool) hasPackage:(Package *)package {
6573 _profile(FilteredPackageTable$hasPackage)
6574 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6578 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6579 if ((self = [super initWithDatabase:database title:title]) != nil) {
6580 [self setFilter:filter];
6581 [self setObject:object];
6588 /* Home Controller {{{ */
6589 @interface HomeController : CYBrowserController {
6594 @implementation HomeController
6597 if ((self = [super init]) != nil) {
6598 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6602 - (NSURL *) navigationURL {
6603 return [NSURL URLWithString:@"cydia://home"];
6606 - (void) aboutButtonClicked {
6607 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6609 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6610 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6611 [alert setCancelButtonIndex:0];
6614 @"Copyright (C) 2008-2011\n"
6615 "Jay Freeman (saurik)\n"
6616 "saurik@saurik.com\n"
6617 "http://www.saurik.com/"
6623 - (void) viewDidLoad {
6624 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6625 initWithTitle:UCLocalize("ABOUT")
6626 style:UIBarButtonItemStylePlain
6628 action:@selector(aboutButtonClicked)
6634 /* Manage Controller {{{ */
6635 @interface ManageController : CYBrowserController {
6638 - (void) queueStatusDidChange;
6642 @implementation ManageController
6645 if ((self = [super init]) != nil) {
6646 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6650 - (NSURL *) navigationURL {
6651 return [NSURL URLWithString:@"cydia://manage"];
6654 - (void) viewDidLoad {
6655 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6656 initWithTitle:UCLocalize("SETTINGS")
6657 style:UIBarButtonItemStylePlain
6659 action:@selector(settingsButtonClicked)
6662 [self queueStatusDidChange];
6665 - (void) settingsButtonClicked {
6666 [delegate_ showSettings];
6670 - (void) queueButtonClicked {
6674 - (void) applyLoadingTitle {
6675 // Disable "Loading" title.
6678 - (void) applyRightButton {
6679 // Disable right button.
6683 - (void) queueStatusDidChange {
6685 if (!IsWildcat_ && Queuing_) {
6686 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6687 initWithTitle:UCLocalize("QUEUE")
6688 style:UIBarButtonItemStyleDone
6690 action:@selector(queueButtonClicked)
6693 [[self navigationItem] setRightBarButtonItem:nil];
6698 - (bool) isLoading {
6699 // Never show as loading.
6706 /* Refresh Bar {{{ */
6707 @interface RefreshBar : UINavigationBar {
6708 UIProgressIndicator *indicator_;
6709 UITextLabel *prompt_;
6710 UIProgressBar *progress_;
6711 UINavigationButton *cancel_;
6716 @implementation RefreshBar
6719 [indicator_ release];
6721 [progress_ release];
6726 - (void) positionViews {
6727 CGRect frame = [cancel_ frame];
6728 frame.size = [cancel_ sizeThatFits:frame.size];
6729 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6730 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6731 [cancel_ setFrame:frame];
6733 CGSize prgsize = {75, 100};
6735 [self frame].size.width - prgsize.width - 10,
6736 ([self frame].size.height - prgsize.height) / 2
6738 [progress_ setFrame:prgrect];
6740 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6741 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6742 CGRect indrect = {{indoffset, indoffset}, indsize};
6743 [indicator_ setFrame:indrect];
6745 CGSize prmsize = {215, indsize.height + 4};
6747 indoffset * 2 + indsize.width,
6748 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6750 [prompt_ setFrame:prmrect];
6753 - (void) setFrame:(CGRect)frame {
6754 [super setFrame:frame];
6755 [self positionViews];
6758 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6759 if ((self = [super initWithFrame:frame]) != nil) {
6760 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6762 [self setBarStyle:UIBarStyleBlack];
6764 UIBarStyle barstyle([self _barStyle:NO]);
6765 bool ugly(barstyle == UIBarStyleDefault);
6767 UIProgressIndicatorStyle style = ugly ?
6768 UIProgressIndicatorStyleMediumBrown :
6769 UIProgressIndicatorStyleMediumWhite;
6771 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6772 [indicator_ setStyle:style];
6773 [indicator_ startAnimation];
6774 [self addSubview:indicator_];
6776 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6777 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6778 [prompt_ setBackgroundColor:[UIColor clearColor]];
6779 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6780 [self addSubview:prompt_];
6782 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6783 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6784 [progress_ setStyle:0];
6785 [self addSubview:progress_];
6787 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6788 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6789 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6790 [cancel_ setBarStyle:barstyle];
6792 [self positionViews];
6796 - (void) setCancellable:(bool)cancellable {
6798 [self addSubview:cancel_];
6800 [cancel_ removeFromSuperview];
6804 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6805 [progress_ setProgress:0];
6809 [self setCancellable:NO];
6812 - (void) setPrompt:(NSString *)prompt {
6813 [prompt_ setText:prompt];
6816 - (void) setProgress:(float)progress {
6817 [progress_ setProgress:progress];
6823 @class CYNavigationController;
6825 /* Cydia Tab Bar Controller {{{ */
6826 @interface CYTabBarController : UITabBarController <
6827 UITabBarControllerDelegate,
6830 _transient Database *database_;
6831 RefreshBar *refreshbar_;
6835 // XXX: ok, "updatedelegate_"?...
6836 _transient NSObject<CydiaDelegate> *updatedelegate_;
6839 UIViewController *remembered_;
6840 _transient UIViewController *transient_;
6843 - (NSArray *) navigationURLCollection;
6844 - (void) dropBar:(BOOL)animated;
6845 - (void) beginUpdate;
6846 - (void) raiseBar:(BOOL)animated;
6851 @implementation CYTabBarController
6853 - (void) setUnselectedViewController:(UIViewController *)transient {
6854 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6855 if (transient != nil) {
6856 if (transient_ == nil)
6857 remembered_ = [[controllers objectAtIndex:0] retain];
6858 transient_ = transient;
6859 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6860 [controllers replaceObjectAtIndex:0 withObject:transient_];
6861 [self setSelectedIndex:0];
6862 [self setViewControllers:controllers];
6863 [self concealTabBarSelection];
6864 } else if (remembered_ != nil) {
6865 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6866 transient_ = transient;
6867 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6868 [remembered_ release];
6870 [self setViewControllers:controllers];
6871 [self revealTabBarSelection];
6875 - (UIViewController *) unselectedViewController {
6879 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6880 if ([self unselectedViewController])
6881 [self setUnselectedViewController:nil];
6884 - (NSArray *) navigationURLCollection {
6885 NSMutableArray *items([NSMutableArray array]);
6887 // XXX: Should this deal with transient view controllers?
6888 for (id navigation in [self viewControllers]) {
6889 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6891 [items addObject:stack];
6897 - (void) reloadData {
6898 for (CYViewController *controller in [self viewControllers])
6899 [controller reloadData];
6901 [(CYNavigationController *)[self unselectedViewController] reloadData];
6905 [refreshbar_ release];
6906 [[NSNotificationCenter defaultCenter] removeObserver:self];
6911 - (id) initWithDatabase:(Database *)database {
6912 if ((self = [super init]) != nil) {
6913 database_ = database;
6914 [self setDelegate:self];
6916 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6917 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6919 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6923 - (void) setUpdate:(NSDate *)date {
6927 - (void) beginUpdate {
6928 [refreshbar_ start];
6931 [updatedelegate_ retainNetworkActivityIndicator];
6935 detachNewThreadSelector:@selector(performUpdate)
6941 - (void) performUpdate { _pooled
6943 status.setDelegate(self);
6944 [database_ updateWithStatus:status];
6947 performSelectorOnMainThread:@selector(completeUpdate)
6953 - (void) stopUpdateWithSelector:(SEL)selector {
6955 [updatedelegate_ releaseNetworkActivityIndicator];
6957 [self raiseBar:YES];
6960 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6963 - (void) completeUpdate {
6966 [self stopUpdateWithSelector:@selector(reloadData)];
6969 - (void) cancelUpdate {
6970 [self stopUpdateWithSelector:@selector(updateData)];
6973 - (void) cancelPressed {
6974 [self cancelUpdate];
6981 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6982 [refreshbar_ setPrompt:[event compoundMessage]];
6985 - (bool) isProgressCancelled {
6989 - (void) setProgressCancellable:(NSNumber *)cancellable {
6990 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6993 - (void) setProgressPercent:(NSNumber *)percent {
6994 [refreshbar_ setProgress:[percent floatValue]];
6997 - (void) setProgressStatus:(NSDictionary *)status {
6999 [self setProgressPercent:[status objectForKey:@"Percent"]];
7002 - (void) setUpdateDelegate:(id)delegate {
7003 updatedelegate_ = delegate;
7006 - (CGFloat) statusBarHeight {
7007 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7008 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7010 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7014 - (UIView *) transitionView {
7015 if ([self respondsToSelector:@selector(_transitionView)])
7016 return [self _transitionView];
7018 return MSHookIvar<id>(self, "_viewControllerTransitionView");
7021 - (void) dropBar:(BOOL)animated {
7026 UIView *transition([self transitionView]);
7027 [[self view] addSubview:refreshbar_];
7029 CGRect barframe([refreshbar_ frame]);
7031 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
7032 barframe.origin.y = [self statusBarHeight];
7034 barframe.origin.y = 0;
7036 [refreshbar_ setFrame:barframe];
7039 [UIView beginAnimations:nil context:NULL];
7041 CGRect viewframe = [transition frame];
7042 viewframe.origin.y += barframe.size.height;
7043 viewframe.size.height -= barframe.size.height;
7044 [transition setFrame:viewframe];
7047 [UIView commitAnimations];
7049 // Ensure bar has the proper width for our view, it might have changed
7050 barframe.size.width = viewframe.size.width;
7051 [refreshbar_ setFrame:barframe];
7053 // XXX: fix Apple's layout bug
7054 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7057 - (void) raiseBar:(BOOL)animated {
7062 UIView *transition([self transitionView]);
7063 [refreshbar_ removeFromSuperview];
7065 CGRect barframe([refreshbar_ frame]);
7068 [UIView beginAnimations:nil context:NULL];
7070 CGRect viewframe = [transition frame];
7071 viewframe.origin.y -= barframe.size.height;
7072 viewframe.size.height += barframe.size.height;
7073 [transition setFrame:viewframe];
7076 [UIView commitAnimations];
7078 // XXX: fix Apple's layout bug
7079 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7083 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7084 // XXX: fix Apple's layout bug
7085 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7089 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7090 bool dropped(dropped_);
7095 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7100 // XXX: fix Apple's layout bug
7101 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7104 - (void) statusBarFrameChanged:(NSNotification *)notification {
7113 /* Cydia Navigation Controller {{{ */
7114 @interface CYNavigationController : UINavigationController {
7115 _transient Database *database_;
7116 _transient id<UINavigationControllerDelegate> delegate_;
7119 - (NSArray *) navigationURLCollection;
7120 - (id) initWithDatabase:(Database *)database;
7121 - (void) reloadData;
7126 @implementation CYNavigationController
7128 - (NSArray *) navigationURLCollection {
7129 NSMutableArray *stack([NSMutableArray array]);
7131 for (CYViewController *controller in [self viewControllers]) {
7132 NSString *url = [[controller navigationURL] absoluteString];
7134 [stack addObject:url];
7140 - (void) reloadData {
7141 for (CYViewController *page in [self viewControllers]) {
7142 // Only reload controllers that have already loaded.
7143 // This prevents a page from accidentally loading too
7144 // early if it hasn't been shown on the screen yet.
7145 if ([page hasLoaded])
7150 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
7151 delegate_ = delegate;
7154 - (id) initWithDatabase:(Database *)database {
7155 if ((self = [super init]) != nil) {
7156 database_ = database;
7163 /* Cydia:// Protocol {{{ */
7164 @interface CydiaURLProtocol : NSURLProtocol {
7169 @implementation CydiaURLProtocol
7171 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7172 NSURL *url([request URL]);
7176 NSString *scheme([[url scheme] lowercaseString]);
7177 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7179 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7185 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7189 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7190 id<NSURLProtocolClient> client([self client]);
7192 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7194 NSData *data(UIImagePNGRepresentation(icon));
7196 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7197 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7198 [client URLProtocol:self didLoadData:data];
7199 [client URLProtocolDidFinishLoading:self];
7203 - (void) startLoading {
7204 id<NSURLProtocolClient> client([self client]);
7205 NSURLRequest *request([self request]);
7207 NSURL *url([request URL]);
7208 NSString *href([url absoluteString]);
7209 NSString *scheme([[url scheme] lowercaseString]);
7213 if ([scheme isEqualToString:@"cydia"])
7214 path = [href substringFromIndex:8];
7215 else if ([scheme isEqualToString:@"about"])
7216 path = [href substringFromIndex:12];
7217 else _assert(false);
7219 NSRange slash([path rangeOfString:@"/"]);
7222 if (slash.location == NSNotFound) {
7226 command = [path substringToIndex:slash.location];
7227 path = [path substringFromIndex:(slash.location + 1)];
7230 Database *database([Database sharedInstance]);
7232 if ([command isEqualToString:@"package-icon"]) {
7235 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7236 Package *package([database packageWithName:path]);
7239 UIImage *icon([package icon]);
7240 [self _returnPNGWithImage:icon forRequest:request];
7241 } else if ([command isEqualToString:@"source-icon"]) {
7244 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7245 NSString *source(Simplify(path));
7246 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7248 icon = [UIImage applicationImageNamed:@"unknown.png"];
7249 [self _returnPNGWithImage:icon forRequest:request];
7250 } else if ([command isEqualToString:@"uikit-image"]) {
7253 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7254 UIImage *icon(_UIImageWithName(path));
7255 [self _returnPNGWithImage:icon forRequest:request];
7256 } else if ([command isEqualToString:@"section-icon"]) {
7259 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7260 NSString *section(Simplify(path));
7261 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7263 icon = [UIImage applicationImageNamed:@"unknown.png"];
7264 [self _returnPNGWithImage:icon forRequest:request];
7266 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7270 - (void) stopLoading {
7276 /* Section Controller {{{ */
7277 @interface SectionController : FilteredPackageListController {
7278 _H<NSString> section_;
7281 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7285 @implementation SectionController
7287 - (NSURL *) navigationURL {
7288 NSString *name = section_;
7292 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7295 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7298 title = UCLocalize("ALL_PACKAGES");
7299 else if (![name isEqual:@""])
7300 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7302 title = UCLocalize("NO_SECTION");
7304 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7311 /* Sections Controller {{{ */
7312 @interface SectionsController : CYViewController <
7313 UITableViewDataSource,
7316 _transient Database *database_;
7317 NSMutableArray *sections_;
7318 NSMutableArray *filtered_;
7322 - (id) initWithDatabase:(Database *)database;
7323 - (void) editButtonClicked;
7327 @implementation SectionsController
7330 [self releaseSubviews];
7331 [sections_ release];
7332 [filtered_ release];
7337 - (NSURL *) navigationURL {
7338 return [NSURL URLWithString:@"cydia://sections"];
7341 - (void) updateNavigationItem {
7342 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7343 if ([sections_ count] == 0) {
7344 [[self navigationItem] setRightBarButtonItem:nil];
7346 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7347 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7349 action:@selector(editButtonClicked)
7350 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7354 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7355 [super setEditing:editing animated:animated];
7360 [delegate_ updateData];
7362 [self updateNavigationItem];
7365 - (void) viewDidAppear:(BOOL)animated {
7366 [super viewDidAppear:animated];
7367 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7370 - (void) viewWillDisappear:(BOOL)animated {
7371 [super viewWillDisappear:animated];
7372 if ([self isEditing]) [self setEditing:NO];
7375 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7376 Section *section = nil;
7377 int index = [indexPath row];
7378 if (![self isEditing]) {
7381 section = [filtered_ objectAtIndex:index];
7383 section = [sections_ objectAtIndex:index];
7388 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7389 if ([self isEditing])
7390 return [sections_ count];
7392 return [filtered_ count] + 1;
7395 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7399 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7400 static NSString *reuseIdentifier = @"SectionCell";
7402 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7404 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7406 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7411 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7412 if ([self isEditing])
7415 Section *section = [self sectionAtIndexPath:indexPath];
7417 SectionController *controller = [[[SectionController alloc]
7418 initWithDatabase:database_
7419 section:[section name]
7421 [controller setDelegate:delegate_];
7423 [[self navigationController] pushViewController:controller animated:YES];
7427 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7429 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7430 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7431 [list_ setRowHeight:45.0f];
7432 [list_ setDataSource:self];
7433 [list_ setDelegate:self];
7434 [[self view] addSubview:list_];
7437 - (void) viewDidLoad {
7438 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7441 - (void) releaseSubviews {
7446 - (id) initWithDatabase:(Database *)database {
7447 if ((self = [super init]) != nil) {
7448 database_ = database;
7450 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7451 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7455 - (void) reloadData {
7458 NSArray *packages = [database_ packages];
7460 [sections_ removeAllObjects];
7461 [filtered_ removeAllObjects];
7463 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7466 for (Package *package in packages) {
7467 NSString *name([package section]);
7468 NSString *key(name == nil ? @"" : name);
7472 _profile(SectionsView$reloadData$Section)
7473 section = [sections objectForKey:key];
7474 if (section == nil) {
7475 _profile(SectionsView$reloadData$Section$Allocate)
7476 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7477 [sections setObject:section forKey:key];
7482 [section addToCount];
7484 _profile(SectionsView$reloadData$Filter)
7485 if (![package valid] || ![package visible])
7493 [sections_ addObjectsFromArray:[sections allValues]];
7495 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7497 for (Section *section in sections_) {
7498 size_t count([section row]);
7502 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7503 [section setCount:count];
7504 [filtered_ addObject:section];
7507 [self updateNavigationItem];
7512 - (void) editButtonClicked {
7513 [self setEditing:![self isEditing] animated:YES];
7519 /* Changes Controller {{{ */
7520 @interface ChangesController : CYViewController <
7521 UITableViewDataSource,
7524 _transient Database *database_;
7526 CFMutableArrayRef packages_;
7527 NSMutableArray *sections_;
7532 - (id) initWithDatabase:(Database *)database;
7536 @implementation ChangesController
7539 [self releaseSubviews];
7540 CFRelease(packages_);
7541 [sections_ release];
7546 - (NSURL *) navigationURL {
7547 return [NSURL URLWithString:@"cydia://changes"];
7550 - (void) viewDidAppear:(BOOL)animated {
7551 [super viewDidAppear:animated];
7552 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7555 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7556 NSInteger count([sections_ count]);
7557 return count == 0 ? 1 : count;
7560 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7561 if ([sections_ count] == 0)
7563 return [[sections_ objectAtIndex:section] name];
7566 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7567 if ([sections_ count] == 0)
7569 return [[sections_ objectAtIndex:section] count];
7572 - (Package *) packageAtIndex:(NSUInteger)index {
7573 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7576 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7577 @synchronized (database_) {
7578 if ([database_ era] != era_)
7581 NSUInteger sectionIndex([path section]);
7582 if (sectionIndex >= [sections_ count])
7584 Section *section([sections_ objectAtIndex:sectionIndex]);
7585 NSInteger row([path row]);
7586 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7589 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7590 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7592 cell = [[[PackageCell alloc] init] autorelease];
7593 [cell setPackage:[self packageAtIndexPath:path]];
7597 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7598 Package *package([self packageAtIndexPath:path]);
7599 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7600 [view setDelegate:delegate_];
7601 [[self navigationController] pushViewController:view animated:YES];
7605 - (void) refreshButtonClicked {
7606 [delegate_ beginUpdate];
7607 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7610 - (void) upgradeButtonClicked {
7611 [delegate_ distUpgrade];
7615 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7617 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7618 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7619 [list_ setRowHeight:73];
7620 [list_ setDataSource:self];
7621 [list_ setDelegate:self];
7622 [[self view] addSubview:list_];
7625 - (void) viewDidLoad {
7626 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7629 - (void) releaseSubviews {
7634 - (id) initWithDatabase:(Database *)database {
7635 if ((self = [super init]) != nil) {
7636 database_ = database;
7638 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7639 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7643 // this mostly works because reloadData (below) is @synchronized (database_)
7644 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7645 - (void) _reloadPackages:(NSArray *)packages {
7646 CFRelease(packages_);
7647 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7650 _profile(ChangesController$_reloadPackages$Filter)
7651 for (Package *package in packages)
7652 if ([package upgradableAndEssential:YES] || [package visible])
7653 CFArrayAppendValue(packages_, package);
7656 _profile(ChangesController$_reloadPackages$radixSort)
7657 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7662 - (void) _reloadData {
7663 @synchronized (database_) {
7664 era_ = [database_ era];
7665 NSArray *packages = [database_ packages];
7667 [sections_ removeAllObjects];
7670 UIProgressHUD *hud([delegate_ addProgressHUD]);
7671 [hud setText:UCLocalize("LOADING")];
7672 //NSLog(@"HUD:%@::%@", delegate_, hud);
7673 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7674 [delegate_ removeProgressHUD:hud];
7676 [self _reloadPackages:packages];
7679 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7680 Section *ignored = nil;
7681 Section *section = nil;
7685 bool unseens = false;
7687 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7689 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7690 Package *package = [self packageAtIndex:offset];
7692 BOOL uae = [package upgradableAndEssential:YES];
7696 time_t seen([package seen]);
7698 if (section == nil || last != seen) {
7702 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7705 _profile(ChangesController$reloadData$Allocate)
7706 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7707 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7708 [sections_ addObject:section];
7712 [section addToCount];
7713 } else if ([package ignored]) {
7714 if (ignored == nil) {
7715 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7717 [ignored addToCount];
7720 [upgradable addToCount];
7725 CFRelease(formatter);
7728 Section *last = [sections_ lastObject];
7729 size_t count = [last count];
7730 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7731 [sections_ removeLastObject];
7734 if ([ignored count] != 0)
7735 [sections_ insertObject:ignored atIndex:0];
7737 [sections_ insertObject:upgradable atIndex:0];
7742 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7743 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7744 style:UIBarButtonItemStylePlain
7746 action:@selector(upgradeButtonClicked)
7749 if (![delegate_ updating])
7750 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7751 initWithTitle:UCLocalize("REFRESH")
7752 style:UIBarButtonItemStylePlain
7754 action:@selector(refreshButtonClicked)
7760 - (void) reloadData {
7762 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7767 /* Search Controller {{{ */
7768 @interface SearchController : FilteredPackageListController <
7771 _H<UISearchBar> search_;
7775 - (id) initWithDatabase:(Database *)database;
7776 - (void) setSearchTerm:(NSString *)term;
7777 - (void) reloadData;
7781 @implementation SearchController
7784 [search_ setDelegate:nil];
7788 - (NSURL *) navigationURL {
7789 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7790 return [NSURL URLWithString:@"cydia://search"];
7792 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7795 - (void) setSearchTerm:(NSString *)searchTerm {
7796 [search_ setText:searchTerm];
7800 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7801 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7802 [search_ resignFirstResponder];
7806 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7807 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7811 - (id) initWithDatabase:(Database *)database {
7812 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7813 search_ = [[[UISearchBar alloc] init] autorelease];
7814 [search_ setDelegate:self];
7818 - (void) viewDidAppear:(BOOL)animated {
7819 [super viewDidAppear:animated];
7821 if (!searchloaded_) {
7822 searchloaded_ = YES;
7823 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7824 [search_ layoutSubviews];
7825 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7827 UITextField *textField;
7828 if ([search_ respondsToSelector:@selector(searchField)])
7829 textField = [search_ searchField];
7831 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7833 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7834 [textField setEnablesReturnKeyAutomatically:NO];
7835 [[self navigationItem] setTitleView:textField];
7839 - (void) reloadData {
7840 [self setObject:[search_ text]];
7846 - (void) didSelectPackage:(Package *)package {
7847 [search_ resignFirstResponder];
7848 [super didSelectPackage:package];
7853 /* Package Settings Controller {{{ */
7854 @interface PackageSettingsController : CYViewController <
7855 UITableViewDataSource,
7858 _transient Database *database_;
7861 UITableView *table_;
7862 UISwitch *subscribedSwitch_;
7863 UISwitch *ignoredSwitch_;
7864 UITableViewCell *subscribedCell_;
7865 UITableViewCell *ignoredCell_;
7868 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7872 @implementation PackageSettingsController
7875 [self releaseSubviews];
7882 - (NSURL *) navigationURL {
7883 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7886 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7887 if (package_ == nil)
7890 if ([package_ installed] == nil)
7896 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7897 if (package_ == nil)
7900 // both sections contain just one item right now.
7904 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7908 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7910 return UCLocalize("SHOW_ALL_CHANGES_EX");
7912 return UCLocalize("IGNORE_UPGRADES_EX");
7915 - (void) onSubscribed:(id)control {
7916 bool value([control isOn]);
7917 if (package_ == nil)
7919 if ([package_ setSubscribed:value])
7920 [delegate_ updateData];
7923 - (void) _updateIgnored {
7924 const char *package([name_ UTF8String]);
7925 bool on([ignoredSwitch_ isOn]);
7927 pid_t pid(ExecFork());
7929 FILE *dpkg(popen("dpkg --set-selections", "w"));
7930 fwrite(package, strlen(package), 1, dpkg);
7933 fwrite(" hold\n", 6, 1, dpkg);
7935 fwrite(" install\n", 9, 1, dpkg);
7945 int result(waitpid(pid, &status, 0));
7948 _assert(result == pid);
7954 - (void) onIgnored:(id)control {
7955 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7956 [invocation setTarget:self];
7957 [invocation setSelector:@selector(_updateIgnored)];
7959 [delegate_ reloadDataWithInvocation:invocation];
7962 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7963 if (package_ == nil)
7966 switch ([indexPath section]) {
7967 case 0: return subscribedCell_;
7968 case 1: return ignoredCell_;
7977 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7979 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7980 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7981 [table_ setDataSource:self];
7982 [table_ setDelegate:self];
7983 [[self view] addSubview:table_];
7985 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7986 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7987 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7989 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7990 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7991 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7993 subscribedCell_ = [[UITableViewCell alloc] init];
7994 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7995 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7996 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7998 ignoredCell_ = [[UITableViewCell alloc] init];
7999 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8000 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8001 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8004 - (void) viewDidLoad {
8005 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8008 - (void) releaseSubviews {
8009 [ignoredCell_ release];
8012 [subscribedCell_ release];
8013 subscribedCell_ = nil;
8018 [ignoredSwitch_ release];
8019 ignoredSwitch_ = nil;
8021 [subscribedSwitch_ release];
8022 subscribedSwitch_ = nil;
8025 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8026 if ((self = [super init]) != nil) {
8027 database_ = database;
8028 name_ = [package retain];
8032 - (void) reloadData {
8035 if (package_ != nil)
8036 [package_ autorelease];
8037 package_ = [database_ packageWithName:name_];
8039 if (package_ != nil) {
8040 package_ = [package_ retain];
8041 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8042 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8043 } // XXX: what now, G?
8045 [table_ reloadData];
8051 /* Installed Controller {{{ */
8052 @interface InstalledController : FilteredPackageListController {
8056 - (id) initWithDatabase:(Database *)database;
8058 - (void) updateRoleButton;
8059 - (void) queueStatusDidChange;
8063 @implementation InstalledController
8069 - (NSURL *) navigationURL {
8070 return [NSURL URLWithString:@"cydia://installed"];
8073 - (id) initWithDatabase:(Database *)database {
8074 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8075 [self updateRoleButton];
8076 [self queueStatusDidChange];
8081 - (void) queueButtonClicked {
8086 - (void) queueStatusDidChange {
8090 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8091 initWithTitle:UCLocalize("QUEUE")
8092 style:UIBarButtonItemStyleDone
8094 action:@selector(queueButtonClicked)
8097 [[self navigationItem] setLeftBarButtonItem:nil];
8103 - (void) updateRoleButton {
8104 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8105 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8106 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8107 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8109 action:@selector(roleButtonClicked)
8113 - (void) roleButtonClicked {
8114 [self setObject:[NSNumber numberWithBool:expert_]];
8118 [self updateRoleButton];
8124 /* Source Cell {{{ */
8125 @interface SourceCell : CYTableViewCell <
8133 - (void) setSource:(Source *)source;
8137 @implementation SourceCell
8139 - (void) clearSource {
8149 - (void) setSource:(Source *)source {
8153 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
8155 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8156 icon_ = [icon_ retain];
8158 origin_ = [[source name] retain];
8159 label_ = [[source uri] retain];
8161 [content_ setNeedsDisplay];
8169 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8170 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8171 UIView *content([self contentView]);
8172 CGRect bounds([content bounds]);
8174 content_ = [[ContentView alloc] initWithFrame:bounds];
8175 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8176 [content_ setBackgroundColor:[UIColor whiteColor]];
8177 [content addSubview:content_];
8179 [content_ setDelegate:self];
8180 [content_ setOpaque:YES];
8184 - (NSString *) accessibilityLabel {
8188 - (void) drawContentRect:(CGRect)rect {
8189 bool highlighted(highlighted_);
8190 float width(rect.size.width);
8193 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8200 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8204 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8209 /* Source Controller {{{ */
8210 @interface SourceController : FilteredPackageListController {
8211 _transient Source *source_;
8215 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8219 @implementation SourceController
8221 - (NSURL *) navigationURL {
8222 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8225 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8226 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8228 key_ = [[source key] retain];
8232 - (void) reloadData {
8233 source_ = [database_ sourceWithKey:key_];
8235 key_ = [[source_ key] retain];
8236 [self setObject:source_];
8238 [[self navigationItem] setTitle:[source_ label]];
8245 /* Sources Controller {{{ */
8246 @interface SourcesController : CYViewController <
8247 UITableViewDataSource,
8250 _transient Database *database_;
8252 NSMutableArray *sources_;
8256 UIProgressHUD *hud_;
8259 //NSURLConnection *installer_;
8260 NSURLConnection *trivial_;
8261 NSURLConnection *trivial_bz2_;
8262 NSURLConnection *trivial_gz_;
8263 //NSURLConnection *automatic_;
8268 - (id) initWithDatabase:(Database *)database;
8269 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8273 @implementation SourcesController
8275 - (void) _releaseConnection:(NSURLConnection *)connection {
8276 if (connection != nil) {
8277 [connection cancel];
8278 //[connection setDelegate:nil];
8279 [connection release];
8284 [self releaseSubviews];
8290 //[self _releaseConnection:installer_];
8291 [self _releaseConnection:trivial_];
8292 [self _releaseConnection:trivial_gz_];
8293 [self _releaseConnection:trivial_bz2_];
8294 //[self _releaseConnection:automatic_];
8300 - (NSURL *) navigationURL {
8301 return [NSURL URLWithString:@"cydia://sources"];
8304 - (void) viewDidAppear:(BOOL)animated {
8305 [super viewDidAppear:animated];
8306 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8309 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8310 return offset_ == 0 ? 1 : 2;
8313 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8314 switch (section + (offset_ == 0 ? 1 : 0)) {
8315 case 0: return UCLocalize("ENTERED_BY_USER");
8316 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8322 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8323 int count = [sources_ count];
8325 case 0: return (offset_ == 0 ? count : offset_);
8326 case 1: return count - offset_;
8332 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8334 switch (indexPath.section) {
8335 case 0: idx = indexPath.row; break;
8336 case 1: idx = indexPath.row + offset_; break;
8340 return [sources_ objectAtIndex:idx];
8343 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8344 static NSString *cellIdentifier = @"SourceCell";
8346 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8347 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8348 [cell setSource:[self sourceAtIndexPath:indexPath]];
8349 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8354 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8355 Source *source = [self sourceAtIndexPath:indexPath];
8357 SourceController *controller = [[[SourceController alloc]
8358 initWithDatabase:database_
8362 [controller setDelegate:delegate_];
8364 [[self navigationController] pushViewController:controller animated:YES];
8367 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8368 Source *source = [self sourceAtIndexPath:indexPath];
8369 return [source record] != nil;
8372 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8373 Source *source = [self sourceAtIndexPath:indexPath];
8374 [Sources_ removeObjectForKey:[source key]];
8375 [delegate_ syncData];
8379 [delegate_ addTrivialSource:href_];
8380 [delegate_ syncData];
8383 - (NSString *) getWarning {
8384 NSString *href(href_);
8385 NSRange colon([href rangeOfString:@"://"]);
8386 if (colon.location != NSNotFound)
8387 href = [href substringFromIndex:(colon.location + 3)];
8388 href = [href stringByAddingPercentEscapes];
8389 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8390 href = [href stringByCachingURLWithCurrentCDN];
8392 NSURL *url([NSURL URLWithString:href]);
8394 NSStringEncoding encoding;
8395 NSError *error(nil);
8397 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8398 return [warning length] == 0 ? nil : warning;
8402 - (void) _endConnection:(NSURLConnection *)connection {
8403 // XXX: the memory management in this method is horribly awkward
8405 NSURLConnection **field = NULL;
8406 if (connection == trivial_)
8408 else if (connection == trivial_bz2_)
8409 field = &trivial_bz2_;
8410 else if (connection == trivial_gz_)
8411 field = &trivial_gz_;
8412 _assert(field != NULL);
8413 [connection release];
8418 trivial_bz2_ == nil &&
8424 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8427 UIAlertView *alert = [[[UIAlertView alloc]
8428 initWithTitle:UCLocalize("SOURCE_WARNING")
8431 cancelButtonTitle:UCLocalize("CANCEL")
8433 UCLocalize("ADD_ANYWAY"),
8437 [alert setContext:@"warning"];
8438 [alert setNumberOfRows:1];
8442 } else if (error_ != nil) {
8443 UIAlertView *alert = [[[UIAlertView alloc]
8444 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8445 message:[error_ localizedDescription]
8447 cancelButtonTitle:UCLocalize("OK")
8448 otherButtonTitles:nil
8451 [alert setContext:@"urlerror"];
8454 UIAlertView *alert = [[[UIAlertView alloc]
8455 initWithTitle:UCLocalize("NOT_REPOSITORY")
8456 message:UCLocalize("NOT_REPOSITORY_EX")
8458 cancelButtonTitle:UCLocalize("OK")
8459 otherButtonTitles:nil
8462 [alert setContext:@"trivial"];
8466 [delegate_ releaseNetworkActivityIndicator];
8468 [delegate_ removeProgressHUD:hud_];
8477 if (error_ != nil) {
8484 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8485 switch ([response statusCode]) {
8491 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8492 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8494 error_ = [error retain];
8495 [self _endConnection:connection];
8498 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8499 [self _endConnection:connection];
8502 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8503 NSMutableURLRequest *request = [NSMutableURLRequest
8504 requestWithURL:[NSURL URLWithString:href]
8505 cachePolicy:NSURLRequestUseProtocolCachePolicy
8506 timeoutInterval:120.0
8509 [request setHTTPMethod:method];
8511 if (Machine_ != NULL)
8512 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8513 if (UniqueID_ != nil)
8514 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8516 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8519 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8520 NSString *context([alert context]);
8522 if ([context isEqualToString:@"source"]) {
8525 NSString *href = [[alert textField] text];
8527 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8529 if (![href hasSuffix:@"/"])
8530 href_ = [href stringByAppendingString:@"/"];
8533 href_ = [href_ retain];
8535 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8536 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8537 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8538 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8542 // XXX: this is stupid
8543 hud_ = [[delegate_ addProgressHUD] retain];
8544 [hud_ setText:UCLocalize("VERIFYING_URL")];
8545 [delegate_ retainNetworkActivityIndicator];
8554 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8555 } else if ([context isEqualToString:@"trivial"])
8556 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8557 else if ([context isEqualToString:@"urlerror"])
8558 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8559 else if ([context isEqualToString:@"warning"]) {
8574 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8579 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8581 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8582 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8583 [list_ setRowHeight:56];
8584 [list_ setDataSource:self];
8585 [list_ setDelegate:self];
8586 [[self view] addSubview:list_];
8589 - (void) viewDidLoad {
8590 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8591 [self updateButtonsForEditingStatus:NO animated:NO];
8594 - (void) releaseSubviews {
8599 - (id) initWithDatabase:(Database *)database {
8600 if ((self = [super init]) != nil) {
8601 database_ = database;
8602 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8606 - (void) reloadData {
8610 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8613 [sources_ removeAllObjects];
8614 [sources_ addObjectsFromArray:[database_ sources]];
8616 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8619 int count([sources_ count]);
8621 for (int i = 0; i != count; i++) {
8622 if ([[sources_ objectAtIndex:i] record] == nil)
8627 [list_ setEditing:NO];
8628 [self updateButtonsForEditingStatus:NO animated:NO];
8632 - (void) showAddSourcePrompt {
8633 UIAlertView *alert = [[[UIAlertView alloc]
8634 initWithTitle:UCLocalize("ENTER_APT_URL")
8637 cancelButtonTitle:UCLocalize("CANCEL")
8639 UCLocalize("ADD_SOURCE"),
8643 [alert setContext:@"source"];
8644 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8646 [alert setNumberOfRows:1];
8647 [alert addTextFieldWithValue:@"http://" label:@""];
8649 UITextInputTraits *traits = [[alert textField] textInputTraits];
8650 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8651 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8652 [traits setKeyboardType:UIKeyboardTypeURL];
8653 // XXX: UIReturnKeyDone
8654 [traits setReturnKeyType:UIReturnKeyNext];
8659 - (void) addButtonClicked {
8660 [self showAddSourcePrompt];
8663 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8664 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8665 initWithTitle:UCLocalize("ADD")
8666 style:UIBarButtonItemStylePlain
8668 action:@selector(addButtonClicked)
8669 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8671 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8672 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8673 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8675 action:@selector(editButtonClicked)
8676 ] autorelease] animated:animated];
8678 if (IsWildcat_ && !editing)
8679 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8680 initWithTitle:UCLocalize("SETTINGS")
8681 style:UIBarButtonItemStylePlain
8683 action:@selector(settingsButtonClicked)
8687 - (void) settingsButtonClicked {
8688 [delegate_ showSettings];
8691 - (void) editButtonClicked {
8692 [list_ setEditing:![list_ isEditing] animated:YES];
8694 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8700 /* Settings Controller {{{ */
8701 @interface SettingsController : CYViewController <
8702 UITableViewDataSource,
8705 _transient Database *database_;
8706 // XXX: ok, "roledelegate_"?...
8707 _transient id roledelegate_;
8708 UITableView *table_;
8709 UISegmentedControl *segment_;
8713 - (void) showDoneButton;
8714 - (void) resizeSegmentedControl;
8718 @implementation SettingsController
8721 [self releaseSubviews];
8727 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8729 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8730 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8731 [table_ setDelegate:self];
8732 [table_ setDataSource:self];
8733 [[self view] addSubview:table_];
8735 NSArray *items = [NSArray arrayWithObjects:
8737 UCLocalize("HACKER"),
8738 UCLocalize("DEVELOPER"),
8740 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8741 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8742 [container_ addSubview:segment_];
8745 - (void) viewDidLoad {
8746 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8749 if ([Role_ isEqualToString:@"User"]) index = 0;
8750 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8751 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8753 [segment_ setSelectedSegmentIndex:index];
8754 [self showDoneButton];
8757 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8758 [self resizeSegmentedControl];
8761 - (void) releaseSubviews {
8768 [container_ release];
8772 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8773 if ((self = [super init]) != nil) {
8774 database_ = database;
8775 roledelegate_ = delegate;
8779 - (void) resizeSegmentedControl {
8780 CGFloat width = [[self view] frame].size.width;
8781 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8784 - (void) viewWillAppear:(BOOL)animated {
8785 [super viewWillAppear:animated];
8787 [self resizeSegmentedControl];
8790 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8791 [self resizeSegmentedControl];
8794 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8795 [self resizeSegmentedControl];
8799 NSString *role(nil);
8801 switch ([segment_ selectedSegmentIndex]) {
8802 case 0: role = @"User"; break;
8803 case 1: role = @"Hacker"; break;
8804 case 2: role = @"Developer"; break;
8809 if (![role isEqualToString:Role_]) {
8810 bool rolling(Role_ == nil);
8813 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8817 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8821 [roledelegate_ loadData];
8823 [roledelegate_ updateData];
8827 - (void) segmentChanged:(UISegmentedControl *)control {
8828 [self showDoneButton];
8831 - (void) saveAndClose {
8834 [[self navigationItem] setRightBarButtonItem:nil];
8835 [[self navigationController] dismissModalViewControllerAnimated:YES];
8838 - (void) doneButtonClicked {
8839 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8840 [spinner startAnimating];
8841 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8842 [[self navigationItem] setRightBarButtonItem:spinItem];
8844 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8847 - (void) showDoneButton {
8848 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8849 initWithTitle:UCLocalize("DONE")
8850 style:UIBarButtonItemStyleDone
8852 action:@selector(doneButtonClicked)
8853 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8856 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8857 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8861 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8865 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8866 return nil; // This method is required by the protocol.
8869 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8871 return UCLocalize("ROLE_EX");
8873 return [NSString stringWithFormat:
8874 @"%@: %@\n%@: %@\n%@: %@",
8875 UCLocalize("USER"), UCLocalize("USER_EX"),
8876 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8877 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8882 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8883 return section == 3 ? 44.0f : 0;
8886 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8887 return section == 3 ? container_ : nil;
8890 - (void) reloadData {
8893 [table_ reloadData];
8898 /* Stash Controller {{{ */
8899 @interface StashController : CYViewController {
8900 UIActivityIndicatorView *spinner_;
8907 @implementation StashController
8910 [self releaseSubviews];
8916 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8917 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8919 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8920 CGRect spinrect = [spinner_ frame];
8921 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8922 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8923 [spinner_ setFrame:spinrect];
8924 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8925 [[self view] addSubview:spinner_];
8926 [spinner_ startAnimating];
8929 captrect.size.width = [[self view] frame].size.width;
8930 captrect.size.height = 40.0f;
8931 captrect.origin.x = 0;
8932 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8933 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8934 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8935 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8936 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8937 [caption_ setTextColor:[UIColor whiteColor]];
8938 [caption_ setBackgroundColor:[UIColor clearColor]];
8939 [caption_ setShadowColor:[UIColor blackColor]];
8940 [caption_ setTextAlignment:UITextAlignmentCenter];
8941 [[self view] addSubview:caption_];
8944 statusrect.size.width = [[self view] frame].size.width;
8945 statusrect.size.height = 30.0f;
8946 statusrect.origin.x = 0;
8947 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8948 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8949 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8950 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8951 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8952 [status_ setTextColor:[UIColor whiteColor]];
8953 [status_ setBackgroundColor:[UIColor clearColor]];
8954 [status_ setShadowColor:[UIColor blackColor]];
8955 [status_ setTextAlignment:UITextAlignmentCenter];
8956 [[self view] addSubview:status_];
8959 - (void) releaseSubviews {
8973 @interface Cydia : UIApplication <
8974 ConfirmationControllerDelegate,
8977 UINavigationControllerDelegate,
8978 UITabBarControllerDelegate
8980 // XXX: evaluate all fields for _transient
8983 CYTabBarController *tabbar_;
8984 CYEmulatedLoadingController *emulated_;
8986 NSMutableArray *essential_;
8987 NSMutableArray *broken_;
8989 Database *database_;
8996 StashController *stash_;
9005 @implementation Cydia
9007 - (void) beginUpdate {
9008 [tabbar_ beginUpdate];
9012 return [tabbar_ updating];
9016 if ([broken_ count] != 0) {
9017 int count = [broken_ count];
9019 UIAlertView *alert = [[[UIAlertView alloc]
9020 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9021 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9023 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
9025 UCLocalize("TEMPORARY_IGNORE"),
9029 [alert setContext:@"fixhalf"];
9030 [alert setNumberOfRows:2];
9032 } else if (!Ignored_ && [essential_ count] != 0) {
9033 int count = [essential_ count];
9035 UIAlertView *alert = [[[UIAlertView alloc]
9036 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9037 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9039 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9041 UCLocalize("UPGRADE_ESSENTIAL"),
9042 UCLocalize("COMPLETE_UPGRADE"),
9046 [alert setContext:@"upgrade"];
9051 - (void) _saveConfig {
9057 NSString *error(nil);
9059 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9061 NSError *error(nil);
9062 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9063 NSLog(@"failure to save metadata data: %@", error);
9068 NSLog(@"failure to serialize metadata: %@", error);
9073 // Navigation controller for the queuing badge.
9074 - (CYNavigationController *) queueNavigationController {
9075 NSArray *controllers = [tabbar_ viewControllers];
9076 return [controllers objectAtIndex:3];
9079 - (void) _updateData {
9082 [tabbar_ reloadData];
9084 CYNavigationController *navigation = [self queueNavigationController];
9086 id queuedelegate = nil;
9087 if ([[navigation viewControllers] count] > 0)
9088 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9090 [queuedelegate queueStatusDidChange];
9091 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9094 - (void) _refreshIfPossible:(NSDate *)update {
9095 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9097 bool recently = false;
9098 if (update != nil) {
9099 NSTimeInterval interval([update timeIntervalSinceNow]);
9100 if (interval <= 0 && interval > -(15*60))
9104 // Don't automatic refresh if:
9105 // - We already refreshed recently.
9106 // - We already auto-refreshed this launch.
9107 // - Auto-refresh is disabled.
9108 if (recently || loaded_ || ManualRefresh) {
9109 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9111 // If we are cancelling, we need to make sure it knows it's already loaded.
9115 // We are going to load, so remember that.
9119 SCNetworkReachabilityFlags flags; {
9120 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9121 SCNetworkReachabilityGetFlags(reachability, &flags);
9122 CFRelease(reachability);
9125 // XXX: this elaborate mess is what Apple is using to determine this? :(
9126 // XXX: do we care if the user has to intervene? maybe that's ok?
9128 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9129 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9130 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9131 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9132 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9133 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9137 // If we can reach the server, auto-refresh!
9139 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9144 - (void) refreshIfPossible {
9145 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9148 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
9149 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9150 [hud setText:UCLocalize("RELOADING_DATA")];
9152 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9155 [self removeProgressHUD:hud];
9159 [essential_ removeAllObjects];
9160 [broken_ removeAllObjects];
9162 NSArray *packages([database_ packages]);
9163 for (Package *package in packages) {
9165 [broken_ addObject:package];
9166 if ([package upgradableAndEssential:NO]) {
9167 if ([package essential])
9168 [essential_ addObject:package];
9173 NSLog(@"changes:#%u", changes);
9175 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9178 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9179 [changesItem setBadgeValue:badge];
9180 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9181 [self setApplicationIconBadgeNumber:changes];
9184 [changesItem setBadgeValue:nil];
9185 [changesItem setAnimatedBadge:NO];
9186 [self setApplicationIconBadgeNumber:0];
9191 [self refreshIfPossible];
9194 - (void) updateData {
9203 @synchronized (self) {
9204 [self _reloadDataWithInvocation:nil];
9208 - (void) disemulate {
9209 if (emulated_ == nil)
9212 [window_ addSubview:[tabbar_ view]];
9213 [[emulated_ view] removeFromSuperview];
9214 [emulated_ release];
9216 [window_ setUserInteractionEnabled:YES];
9219 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9220 UINavigationController *navigation([[[CYNavigationController alloc] initWithRootViewController:controller] autorelease]);
9222 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9224 UIViewController *parent;
9225 if (emulated_ == nil)
9234 [parent presentModalViewController:navigation animated:YES];
9237 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9238 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9240 if (navigation != nil)
9241 [navigation pushViewController:progress animated:YES];
9243 [self presentModalViewController:progress force:YES];
9245 [progress invoke:invocation withTitle:title];
9249 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9250 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9253 - (void) repairWithInvocation:(NSInvocation *)invocation {
9255 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9259 - (void) repairWithSelector:(SEL)selector {
9260 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9266 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
9267 _assert(file != NULL);
9269 for (NSString *key in [Sources_ allKeys]) {
9270 NSDictionary *source([Sources_ objectForKey:key]);
9272 fprintf(file, "%s %s %s\n",
9273 [[source objectForKey:@"Type"] UTF8String],
9274 [[source objectForKey:@"URI"] UTF8String],
9275 [[source objectForKey:@"Distribution"] UTF8String]
9281 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9286 - (void) addTrivialSource:(NSString *)href {
9287 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
9290 @"./", @"Distribution",
9291 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
9296 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9297 @synchronized (self) {
9298 [self _reloadDataWithInvocation:invocation];
9302 - (void) reloadData {
9303 [self reloadDataWithInvocation:nil];
9307 pkgProblemResolver *resolver = [database_ resolver];
9309 resolver->InstallProtect();
9310 if (!resolver->Resolve(true))
9315 // XXX: this is a really crappy way of doing this.
9316 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9317 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9318 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9319 if ([tabbar_ updating])
9320 [tabbar_ cancelUpdate];
9322 if (![database_ prepare])
9325 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9326 [page setDelegate:self];
9327 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
9328 [confirm_ setDelegate:self];
9331 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9332 [tabbar_ presentModalViewController:confirm_ animated:YES];
9338 @synchronized (self) {
9343 - (void) clearPackage:(Package *)package {
9344 @synchronized (self) {
9351 - (void) installPackages:(NSArray *)packages {
9352 @synchronized (self) {
9353 for (Package *package in packages)
9360 - (void) installPackage:(Package *)package {
9361 @synchronized (self) {
9368 - (void) removePackage:(Package *)package {
9369 @synchronized (self) {
9376 - (void) distUpgrade {
9377 @synchronized (self) {
9378 if (![database_ upgrade])
9384 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9387 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
9392 - (void) showSettings {
9393 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9394 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9396 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9397 [tabbar_ presentModalViewController:nav animated:YES];
9400 - (void) retainNetworkActivityIndicator {
9401 if (activity_++ == 0)
9402 [self setNetworkActivityIndicatorVisible:YES];
9405 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9409 - (void) releaseNetworkActivityIndicator {
9410 if (--activity_ == 0)
9411 [self setNetworkActivityIndicatorVisible:NO];
9414 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9419 - (void) cancelAndClear:(bool)clear {
9420 @synchronized (self) {
9432 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9433 NSString *context([alert context]);
9435 if ([context isEqualToString:@"conffile"]) {
9436 FILE *input = [database_ input];
9437 if (button == [alert cancelButtonIndex])
9438 fprintf(input, "N\n");
9439 else if (button == [alert firstOtherButtonIndex])
9440 fprintf(input, "Y\n");
9443 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9444 } else if ([context isEqualToString:@"fixhalf"]) {
9445 if (button == [alert cancelButtonIndex]) {
9446 @synchronized (self) {
9447 for (Package *broken in broken_) {
9450 NSString *id = [broken id];
9451 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9452 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9453 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9454 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9460 } else if (button == [alert firstOtherButtonIndex]) {
9461 [broken_ removeAllObjects];
9465 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9466 } else if ([context isEqualToString:@"upgrade"]) {
9467 if (button == [alert firstOtherButtonIndex]) {
9468 @synchronized (self) {
9469 for (Package *essential in essential_)
9470 [essential install];
9475 } else if (button == [alert firstOtherButtonIndex] + 1) {
9477 } else if (button == [alert cancelButtonIndex]) {
9481 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9485 - (void) system:(NSString *)command { _pooled
9487 system([command UTF8String]);
9491 - (void) applicationWillSuspend {
9493 [super applicationWillSuspend];
9496 - (BOOL) isSafeToSuspend {
9499 NSLog(@"isSafeToSuspend: locked_ != 0");
9504 // Use external process status API internally.
9505 // This is probably a really bad idea.
9506 // XXX: what is the point of this? does this solve anything at all?
9507 uint64_t status = 0;
9509 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9510 notify_get_state(notify_token, &status);
9511 notify_cancel(notify_token);
9516 NSLog(@"isSafeToSuspend: status != 0");
9522 NSLog(@"isSafeToSuspend: -> true");
9527 - (void) applicationSuspend:(__GSEvent *)event {
9528 if ([self isSafeToSuspend])
9529 [super applicationSuspend:event];
9532 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9533 if ([self isSafeToSuspend])
9534 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9537 - (void) _setSuspended:(BOOL)value {
9538 if ([self isSafeToSuspend])
9539 [super _setSuspended:value];
9542 - (UIProgressHUD *) addProgressHUD {
9543 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9544 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9546 [window_ setUserInteractionEnabled:NO];
9549 UIViewController *target = tabbar_;
9550 while ([target modalViewController] != nil) target = [target modalViewController];
9551 [[target view] addSubview:hud];
9557 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9559 [hud removeFromSuperview];
9560 [window_ setUserInteractionEnabled:YES];
9564 - (CYViewController *) pageForPackage:(NSString *)name {
9565 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9568 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9569 NSString *scheme([[url scheme] lowercaseString]);
9570 if ([[url absoluteString] length] <= [scheme length] + 3)
9572 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9573 NSArray *components([path pathComponents]);
9575 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9576 return [self pageForPackage:[components objectAtIndex:1]];
9578 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9581 NSString *base([components objectAtIndex:0]);
9583 CYViewController *controller = nil;
9585 if ([base isEqualToString:@"url"]) {
9586 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9587 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9588 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9589 } else if (!external && [components count] == 1) {
9590 if ([base isEqualToString:@"manage"]) {
9591 controller = [[[ManageController alloc] init] autorelease];
9594 if ([base isEqualToString:@"sources"]) {
9595 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9598 if ([base isEqualToString:@"home"]) {
9599 controller = [[[HomeController alloc] init] autorelease];
9602 if ([base isEqualToString:@"sections"]) {
9603 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9606 if ([base isEqualToString:@"search"]) {
9607 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9610 if ([base isEqualToString:@"changes"]) {
9611 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9614 if ([base isEqualToString:@"installed"]) {
9615 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9617 } else if ([components count] == 2) {
9618 NSString *argument = [components objectAtIndex:1];
9620 if ([base isEqualToString:@"package"]) {
9621 controller = [self pageForPackage:argument];
9624 if (!external && [base isEqualToString:@"search"]) {
9625 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9626 [(SearchController *)controller setSearchTerm:argument];
9629 if (!external && [base isEqualToString:@"sections"]) {
9630 if ([argument isEqualToString:@"all"])
9632 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9635 if (!external && [base isEqualToString:@"sources"]) {
9636 if ([argument isEqualToString:@"add"]) {
9637 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9638 [(SourcesController *)controller showAddSourcePrompt];
9640 Source *source = [database_ sourceWithKey:argument];
9641 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9645 if (!external && [base isEqualToString:@"launch"]) {
9646 [self launchApplicationWithIdentifier:argument suspended:NO];
9649 } else if (!external && [components count] == 3) {
9650 NSString *arg1 = [components objectAtIndex:1];
9651 NSString *arg2 = [components objectAtIndex:2];
9653 if ([base isEqualToString:@"package"]) {
9654 if ([arg2 isEqualToString:@"settings"]) {
9655 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9656 } else if ([arg2 isEqualToString:@"files"]) {
9657 if (Package *package = [database_ packageWithName:arg1]) {
9658 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9659 [(FileTable *)controller setPackage:package];
9665 [controller setDelegate:self];
9669 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9670 CYViewController *page([self pageForURL:url forExternal:external]);
9673 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9674 [nav setViewControllers:[NSArray arrayWithObject:page]];
9675 [tabbar_ setUnselectedViewController:nav];
9681 - (void) applicationOpenURL:(NSURL *)url {
9682 [super applicationOpenURL:url];
9684 if (!loaded_) starturl_ = [url retain];
9685 else [self openCydiaURL:url forExternal:YES];
9688 - (void) applicationWillResignActive:(UIApplication *)application {
9689 // Stop refreshing if you get a phone call or lock the device.
9690 if ([tabbar_ updating])
9691 [tabbar_ cancelUpdate];
9693 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9694 [super applicationWillResignActive:application];
9697 - (void) applicationWillTerminate:(UIApplication *)application {
9699 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9700 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9701 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9706 - (void) setConfigurationData:(NSString *)data {
9707 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9709 if (!conffile_r(data)) {
9710 lprintf("E:invalid conffile\n");
9714 NSString *ofile = conffile_r[1];
9715 //NSString *nfile = conffile_r[2];
9717 UIAlertView *alert = [[[UIAlertView alloc]
9718 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9719 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9721 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9723 UCLocalize("ACCEPT_NEW_COPY"),
9724 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9728 [alert setContext:@"conffile"];
9729 [alert setNumberOfRows:2];
9733 - (void) addStashController {
9735 stash_ = [[StashController alloc] init];
9736 [window_ addSubview:[stash_ view]];
9739 - (void) removeStashController {
9740 [[stash_ view] removeFromSuperview];
9746 [self setIdleTimerDisabled:YES];
9748 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9749 UpdateExternalStatus(1);
9750 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9751 UpdateExternalStatus(0);
9753 [self removeStashController];
9755 if (ExecFork() == 0) {
9756 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9757 perror("launchctl stop");
9761 - (void) setupViewControllers {
9762 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9764 NSMutableArray *items([NSMutableArray arrayWithObjects:
9765 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9766 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9767 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9768 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9772 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9773 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9775 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9778 NSMutableArray *controllers([NSMutableArray array]);
9779 for (UITabBarItem *item in items) {
9780 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9781 [controller setTabBarItem:item];
9782 [controllers addObject:controller];
9784 [tabbar_ setViewControllers:controllers];
9786 [tabbar_ setUpdateDelegate:self];
9789 - (void) applicationDidFinishLaunching:(id)unused {
9791 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9792 [self setApplicationSupportsShakeToEdit:NO];
9794 @synchronized (HostConfig_) {
9795 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9798 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9799 initWithMemoryCapacity:524288
9800 diskCapacity:10485760
9801 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9804 [CYBrowserController _initialize];
9806 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9808 Font12_ = [[UIFont systemFontOfSize:12] retain];
9809 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9810 Font14_ = [[UIFont systemFontOfSize:14] retain];
9811 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9812 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9814 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9815 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9817 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9818 [window_ orderFront:self];
9819 [window_ makeKey:self];
9820 [window_ setHidden:NO];
9823 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9824 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9825 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9826 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9827 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9828 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9829 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9830 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9831 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9834 [self addStashController];
9835 // XXX: this would be much cleaner as a yieldToSelector:
9836 // that way the removeStashController could happen right here inline
9837 // we also could no longer require the useless stash_ field anymore
9838 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9842 database_ = [Database sharedInstance];
9843 [database_ setDelegate:self];
9845 [window_ setUserInteractionEnabled:NO];
9846 [self setupViewControllers];
9848 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9849 [window_ addSubview:[emulated_ view]];
9851 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9855 - (NSArray *) defaultStartPages {
9856 NSMutableArray *standard = [NSMutableArray array];
9857 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9858 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9859 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9861 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9863 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9864 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9866 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9873 [window_ setUserInteractionEnabled:YES];
9874 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9877 if ([emulated_ modalViewController] != nil)
9878 [emulated_ dismissModalViewControllerAnimated:YES];
9879 [window_ setUserInteractionEnabled:NO];
9887 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9888 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9889 int standardIndex = 0;
9890 NSArray *standard = [self defaultStartPages];
9897 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9898 if (valid && closed != nil) {
9899 NSTimeInterval interval([closed timeIntervalSinceNow]);
9900 // XXX: Is 15 minutes the optimal time here?
9901 if (interval > 0 && interval <= -(15*60))
9905 if (valid && [saved count] != [standard count])
9909 for (unsigned int i = 0; i < [standard count]; i++) {
9910 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9911 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9912 // but it's good enough for now.
9913 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9920 NSArray *items = nil;
9922 [tabbar_ setSelectedIndex:savedIndex];
9925 [tabbar_ setSelectedIndex:standardIndex];
9929 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9930 NSArray *stack = [items objectAtIndex:tab];
9931 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9932 NSMutableArray *current = [NSMutableArray array];
9934 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9935 NSString *addr = [stack objectAtIndex:nav];
9936 NSURL *url = [NSURL URLWithString:addr];
9937 CYViewController *page = [self pageForURL:url forExternal:NO];
9939 [current addObject:page];
9942 [navigation setViewControllers:current];
9945 // (Try to) show the startup URL.
9946 if (starturl_ != nil) {
9947 [self openCydiaURL:starturl_ forExternal:NO];
9948 [starturl_ release];
9953 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9954 if (item != nil && IsWildcat_) {
9955 [sheet showFromBarButtonItem:item animated:YES];
9957 [sheet showInView:window_];
9961 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9962 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9963 [progress setTitle:task];
9964 [progress addProgressEvent:event];
9967 - (void) addProgressEventForTask:(NSArray *)data {
9968 CydiaProgressEvent *event([data objectAtIndex:0]);
9969 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9970 [self addProgressEvent:event forTask:task];
9973 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9974 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9980 id Alloc_(id self, SEL selector) {
9981 id object = alloc_(self, selector);
9982 lprintf("[%s]A-%p\n", self->isa->name, object);
9987 id Dealloc_(id self, SEL selector) {
9988 id object = dealloc_(self, selector);
9989 lprintf("[%s]D-%p\n", self->isa->name, object);
9993 Class $WebDefaultUIKitDelegate;
9995 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9996 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9997 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9998 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
10001 static NSNumber *shouldPlayKeyboardSounds;
10005 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
10007 case 1104: // Keyboard Button Clicked
10008 case 1105: // Keyboard Delete Repeated
10009 if (shouldPlayKeyboardSounds == nil) {
10010 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
10011 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
10014 if (![shouldPlayKeyboardSounds boolValue])
10018 _UIHardware$_playSystemSound$(self, _cmd, sound);
10022 Class $UIApplication;
10024 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
10025 static BOOL initialized = NO;
10026 static BOOL started = NO;
10028 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
10029 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
10031 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
10032 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
10033 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
10034 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
10036 if (initialized && !enabled) {
10038 [bundle performSelector:@selector(_accessibilityStopServer)];
10039 } else if (enabled) {
10043 [bundle performSelector:@selector(_accessibilityStartServer)];
10049 Class $NSURLConnection;
10051 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10052 NSMutableURLRequest *copy([request mutableCopy]);
10054 NSURL *url([copy URL]);
10055 NSString *host([url host]);
10056 NSString *scheme([[url scheme] lowercaseString]);
10058 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10060 @synchronized (HostConfig_) {
10061 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10062 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10063 [copy setHTTPShouldUsePipelining:YES];
10066 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10070 int main(int argc, char *argv[]) { _pooled
10073 UpdateExternalStatus(0);
10075 if (Class $UIDevice = objc_getClass("UIDevice")) {
10076 UIDevice *device([$UIDevice currentDevice]);
10077 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10079 IsWildcat_ = false;
10081 UIScreen *screen([UIScreen mainScreen]);
10082 if ([screen respondsToSelector:@selector(scale)])
10083 ScreenScale_ = [screen scale];
10087 UIDevice *device([UIDevice currentDevice]);
10088 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10089 Idiom_ = @"iphone";
10091 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10092 if (idiom == UIUserInterfaceIdiomPhone)
10093 Idiom_ = @"iphone";
10094 else if (idiom == UIUserInterfaceIdiomPad)
10097 NSLog(@"unknown UIUserInterfaceIdiom!");
10100 SessionData_ = [[NSMutableDictionary alloc] initWithCapacity:4];
10102 HostConfig_ = [[NSObject alloc] init];
10103 @synchronized (HostConfig_) {
10104 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10105 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10108 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
10110 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10112 /* Library Hacks {{{ */
10113 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10115 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10116 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10117 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10118 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10119 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10122 $NSURLConnection = objc_getClass("NSURLConnection");
10123 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10124 if (NSURLConnection$init$ != NULL) {
10125 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10126 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10129 $UIHardware = objc_getClass("UIHardware");
10130 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
10131 if (UIHardware$_playSystemSound$ != NULL) {
10132 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
10133 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
10136 $UIApplication = objc_getClass("UIApplication");
10137 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
10138 if (UIApplication$_updateApplicationAccessibility != NULL) {
10139 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
10140 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
10143 /* Set Locale {{{ */
10144 Locale_ = CFLocaleCopyCurrent();
10145 Languages_ = [NSLocale preferredLanguages];
10147 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10148 //NSLog(@"%@", [Languages_ description]);
10151 if (Locale_ != NULL)
10152 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10153 else if (Languages_ == nil || [Languages_ count] == 0)
10154 // XXX: consider just setting to C and then falling through?
10157 lang = [[Languages_ objectAtIndex:0] UTF8String];
10158 setenv("LANG", lang, true);
10159 std::setlocale(LC_ALL, lang);
10162 NSLog(@"Setting Language: %s", lang);
10165 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10167 /* Parse Arguments {{{ */
10168 bool substrate(false);
10174 for (int argi(1); argi != argc; ++argi)
10175 if (strcmp(argv[argi], "--") == 0) {
10177 argv[argi] = argv[0];
10183 for (int argi(1); argi != arge; ++argi)
10184 if (strcmp(args[argi], "--substrate") == 0)
10187 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10191 App_ = [[NSBundle mainBundle] bundlePath];
10197 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10198 alloc_ = alloc->method_imp;
10199 alloc->method_imp = (IMP) &Alloc_;*/
10201 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10202 dealloc_ = dealloc->method_imp;
10203 dealloc->method_imp = (IMP) &Dealloc_;*/
10205 /* System Information {{{ */
10209 size = sizeof(maxproc);
10210 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10211 perror("sysctlbyname(\"kern.maxproc\", ?)");
10212 else if (maxproc < 64) {
10214 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10215 perror("sysctlbyname(\"kern.maxproc\", #)");
10218 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10219 char *osversion = new char[size];
10220 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10221 perror("sysctlbyname(\"kern.osversion\", ?)");
10223 System_ = [NSString stringWithUTF8String:osversion];
10225 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10226 char *machine = new char[size];
10227 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10228 perror("sysctlbyname(\"hw.machine\", ?)");
10230 Machine_ = machine;
10232 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
10233 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
10234 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
10235 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
10239 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
10240 NSData *data((NSData *) ecid);
10241 size_t length([data length]);
10242 uint8_t bytes[length];
10243 [data getBytes:bytes];
10244 char string[length * 2 + 1];
10245 for (size_t i(0); i != length; ++i)
10246 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
10247 ChipID_ = [NSString stringWithUTF8String:string];
10251 IOObjectRelease(service);
10255 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
10257 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10258 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10259 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10261 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10262 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10263 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10265 if (mcc != NULL && mnc != NULL)
10266 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10273 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10274 Build_ = [system objectForKey:@"ProductBuildVersion"];
10275 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10276 Product_ = [info objectForKey:@"SafariProductVersion"];
10277 Safari_ = [info objectForKey:@"CFBundleVersion"];
10280 /* Load Database {{{ */
10282 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10284 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10286 if (Metadata_ == NULL)
10287 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10289 Settings_ = [Metadata_ objectForKey:@"Settings"];
10291 Packages_ = [Metadata_ objectForKey:@"Packages"];
10292 Sections_ = [Metadata_ objectForKey:@"Sections"];
10293 Sources_ = [Metadata_ objectForKey:@"Sources"];
10295 Token_ = [Metadata_ objectForKey:@"Token"];
10298 if (Settings_ != nil)
10299 Role_ = [Settings_ objectForKey:@"Role"];
10301 if (Sections_ == nil) {
10302 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10303 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10306 if (Sources_ == nil) {
10307 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10308 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10313 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10316 if (Packages_ != nil) {
10318 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10322 [Metadata_ removeObjectForKey:@"Packages"];
10328 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10330 #define MobileSubstrate_(name) \
10331 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10332 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10333 if (handle == NULL) \
10334 NSLog(@"%s", dlerror()); \
10337 MobileSubstrate_(Activator)
10338 MobileSubstrate_(libstatusbar)
10339 MobileSubstrate_(SimulatedKeyEvents)
10340 MobileSubstrate_(WinterBoard)
10342 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10343 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10345 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10347 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10348 unlink("/tmp/.cydia.fw");
10350 } else if (access("/User", F_OK) != 0 || version < 4) {
10353 system("/usr/libexec/cydia/firmware.sh");
10357 _assert([[NSFileManager defaultManager]
10358 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10359 withIntermediateDirectories:YES
10364 if (access("/tmp/cydia.chk", F_OK) == 0) {
10365 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10366 _assert(errno == ENOENT);
10367 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10368 _assert(errno == ENOENT);
10371 /* APT Initialization {{{ */
10372 _assert(pkgInitConfig(*_config));
10373 _assert(pkgInitSystem(*_config, _system));
10376 _config->Set("APT::Acquire::Translation", lang);
10378 // XXX: this timeout might be important :(
10379 //_config->Set("Acquire::http::Timeout", 15);
10381 _config->Set("Acquire::http::MaxParallel", 3);
10383 /* Color Choices {{{ */
10384 space_ = CGColorSpaceCreateDeviceRGB();
10386 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10387 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10388 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10389 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10390 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10391 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10392 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10393 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10394 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10396 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10397 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10399 /* UIKit Configuration {{{ */
10400 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10401 if ($GSFontSetUseLegacyFontMetrics != NULL)
10402 $GSFontSetUseLegacyFontMetrics(YES);
10404 // XXX: I have a feeling this was important
10405 //UIKeyboardDisableAutomaticAppearance();
10408 Colon_ = UCLocalize("COLON_DELIMITED");
10409 Elision_ = UCLocalize("ELISION");
10410 Error_ = UCLocalize("ERROR");
10411 Warning_ = UCLocalize("WARNING");
10414 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10416 CGColorSpaceRelease(space_);
10417 CFRelease(Locale_);