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) const {
882 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
885 _finline bool operator ()(NSString *data) {
886 // XXX: length is for characters, not for bytes
887 return operator ()([data UTF8String], [data length]);
890 _finline bool operator ()(const char *data) {
891 return operator ()(data, strlen(data));
894 bool operator ()(const char *data, size_t size) {
896 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
899 NSString *operator ->*(NSString *format) const {
901 for (int i(0); i != capture_; ++i)
902 values[i] = this->operator [](i + 1);
904 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
908 /* Mime Addresses {{{ */
909 @interface Address : NSObject {
915 - (NSString *) address;
917 - (void) setAddress:(NSString *)address;
919 + (Address *) addressWithString:(NSString *)string;
920 - (Address *) initWithString:(NSString *)string;
924 @implementation Address
933 - (NSString *) name {
937 - (NSString *) address {
941 - (void) setAddress:(NSString *)address {
943 [address_ autorelease];
947 address_ = [address retain];
950 + (Address *) addressWithString:(NSString *)string {
951 return [[[Address alloc] initWithString:string] autorelease];
954 + (NSArray *) _attributeKeys {
955 return [NSArray arrayWithObjects:
961 - (NSArray *) attributeKeys {
962 return [[self class] _attributeKeys];
965 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
966 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
969 - (Address *) initWithString:(NSString *)string {
970 if ((self = [super init]) != nil) {
971 const char *data = [string UTF8String];
972 size_t size = [string length];
974 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
976 if (address_r(data, size)) {
977 name_ = [address_r[1] retain];
978 address_ = [address_r[2] retain];
980 name_ = [string retain];
988 /* CoreGraphics Primitives {{{ */
993 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
994 CGFloat color[] = {red, green, blue, alpha};
995 return CGColorCreate(space, color);
1004 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
1005 color_(Create_(space, red, green, blue, alpha))
1007 Set(space, red, green, blue, alpha);
1012 CGColorRelease(color_);
1019 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1021 color_ = Create_(space, red, green, blue, alpha);
1024 operator CGColorRef() {
1030 /* Random Global Variables {{{ */
1031 static const int PulseInterval_ = 50000;
1033 static const NSString *UI_;
1036 static bool RestartSubstrate_;
1037 static NSArray *Finishes_;
1039 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1040 #define NotifyConfig_ "/etc/notify.conf"
1042 static bool Queuing_;
1044 static CYColor Blue_;
1045 static CYColor Blueish_;
1046 static CYColor Black_;
1047 static CYColor Off_;
1048 static CYColor White_;
1049 static CYColor Gray_;
1050 static CYColor Green_;
1051 static CYColor Purple_;
1052 static CYColor Purplish_;
1054 static UIColor *InstallingColor_;
1055 static UIColor *RemovingColor_;
1057 static NSString *App_;
1059 static BOOL Advanced_;
1060 static BOOL Ignored_;
1062 static UIFont *Font12_;
1063 static UIFont *Font12Bold_;
1064 static UIFont *Font14_;
1065 static UIFont *Font18Bold_;
1066 static UIFont *Font22Bold_;
1068 static const char *Machine_ = NULL;
1069 static NSString *System_ = nil;
1070 static NSString *SerialNumber_ = nil;
1071 static NSString *ChipID_ = nil;
1072 static _H<NSString> Token_;
1073 static NSString *UniqueID_ = nil;
1074 static NSString *PLMN_ = nil;
1075 static NSString *Build_ = nil;
1076 static NSString *Product_ = nil;
1077 static NSString *Safari_ = nil;
1079 static CFLocaleRef Locale_;
1080 static NSArray *Languages_;
1081 static CGColorSpaceRef space_;
1083 static NSDictionary *SectionMap_;
1084 static NSMutableDictionary *Metadata_;
1085 static _transient NSMutableDictionary *Settings_;
1086 static _transient NSString *Role_;
1087 static _transient NSMutableDictionary *Packages_;
1088 static _transient NSMutableDictionary *Sections_;
1089 static _transient NSMutableDictionary *Sources_;
1090 static bool Changed_;
1094 static CGFloat ScreenScale_;
1095 static NSString *Idiom_;
1097 static NSMutableDictionary *SessionData_;
1098 static NSObject *HostConfig_;
1099 static NSMutableSet *BridgedHosts_;
1100 static NSMutableSet *PipelinedHosts_;
1102 static NSString *kCydiaProgressEventTypeError = @"Error";
1103 static NSString *kCydiaProgressEventTypeInformation = @"Information";
1104 static NSString *kCydiaProgressEventTypeStatus = @"Status";
1105 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
1108 /* Display Helpers {{{ */
1109 inline float Interpolate(float begin, float end, float fraction) {
1110 return (end - begin) * fraction + begin;
1113 static _finline const char *StripVersion_(const char *version) {
1114 const char *colon(strchr(version, ':'));
1115 return colon == NULL ? version : colon + 1;
1118 NSString *LocalizeSection(NSString *section) {
1119 static Pcre title_r("^(.*?) \\((.*)\\)$");
1120 if (title_r(section)) {
1121 NSString *parent(title_r[1]);
1122 NSString *child(title_r[2]);
1124 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1125 LocalizeSection(parent),
1126 LocalizeSection(child)
1130 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1133 NSString *Simplify(NSString *title) {
1134 const char *data = [title UTF8String];
1135 size_t size = [title length];
1137 static Pcre square_r("^\\[(.*)\\]$");
1138 if (square_r(data, size))
1139 return Simplify(square_r[1]);
1141 static Pcre paren_r("^\\((.*)\\)$");
1142 if (paren_r(data, size))
1143 return Simplify(paren_r[1]);
1145 static Pcre title_r("^(.*?) \\((.*)\\)$");
1146 if (title_r(data, size))
1147 return Simplify(title_r[1]);
1153 NSString *GetLastUpdate() {
1154 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1157 return UCLocalize("NEVER_OR_UNKNOWN");
1159 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1160 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1162 CFRelease(formatter);
1164 return [(NSString *) formatted autorelease];
1167 bool isSectionVisible(NSString *section) {
1168 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1169 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1170 return hidden == nil || ![hidden boolValue];
1175 /* Delegate Prototypes {{{ */
1178 @class CydiaProgressEvent;
1180 @protocol DatabaseDelegate
1181 - (void) repairWithSelector:(SEL)selector;
1182 - (void) setConfigurationData:(NSString *)data;
1183 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
1186 @class CYPackageController;
1188 @protocol CydiaDelegate
1189 - (void) retainNetworkActivityIndicator;
1190 - (void) releaseNetworkActivityIndicator;
1191 - (void) clearPackage:(Package *)package;
1192 - (void) installPackage:(Package *)package;
1193 - (void) installPackages:(NSArray *)packages;
1194 - (void) removePackage:(Package *)package;
1195 - (void) beginUpdate;
1197 - (void) distUpgrade;
1199 - (void) updateData;
1201 - (void) addTrivialSource:(NSString *)href;
1202 - (void) showSettings;
1203 - (UIProgressHUD *) addProgressHUD;
1204 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1205 - (CYViewController *) pageForPackage:(NSString *)name;
1206 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1207 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1211 /* ProgressEvent Interface/Delegate {{{ */
1212 @interface CydiaProgressEvent : NSObject {
1213 _H<NSString> message_;
1217 _H<NSString> package_;
1219 _H<NSString> version_;
1222 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type;
1223 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package;
1224 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item;
1226 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type;
1228 - (NSString *) message;
1229 - (NSString *) type;
1232 - (NSString *) package;
1234 - (NSString *) version;
1236 - (void) setItem:(NSArray *)item;
1237 - (void) setPackage:(NSString *)package;
1238 - (void) setURL:(NSString *)url;
1239 - (void) setVersion:(NSString *)version;
1241 - (NSString *) compound:(NSString *)value;
1242 - (NSString *) compoundMessage;
1243 - (NSString *) compoundTitle;
1247 @protocol ProgressDelegate
1248 - (void) addProgressEvent:(CydiaProgressEvent *)event;
1249 - (void) setProgressPercent:(NSNumber *)percent;
1250 - (void) setProgressStatus:(NSDictionary *)status;
1251 - (void) setProgressCancellable:(NSNumber *)cancellable;
1252 - (bool) isProgressCancelled;
1253 - (void) setTitle:(NSString *)title;
1256 /* Status Delegation {{{ */
1258 public pkgAcquireStatus
1261 _transient NSObject<ProgressDelegate> *delegate_;
1271 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1272 delegate_ = delegate;
1275 NSObject<ProgressDelegate> *getDelegate() const {
1279 virtual bool MediaChange(std::string media, std::string drive) {
1283 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1286 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1287 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1288 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
1289 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1292 virtual void Done(pkgAcquire::ItemDesc &item) {
1295 virtual void Fail(pkgAcquire::ItemDesc &item) {
1297 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1298 item.Owner->Status == pkgAcquire::Item::StatDone
1302 std::string &error(item.Owner->ErrorText);
1306 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
1307 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1310 virtual bool Pulse(pkgAcquire *Owner) {
1311 bool value = pkgAcquireStatus::Pulse(Owner);
1314 double(CurrentBytes + CurrentItems) /
1315 double(TotalBytes + TotalItems)
1318 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1319 [NSNumber numberWithDouble:percent], @"Percent",
1321 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1322 [NSNumber numberWithDouble:TotalBytes], @"Total",
1323 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1324 nil] waitUntilDone:YES];
1326 if (value && ![delegate_ isProgressCancelled])
1334 _finline bool WasCancelled() const {
1338 virtual void Start() {
1339 pkgAcquireStatus::Start();
1340 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1343 virtual void Stop() {
1344 pkgAcquireStatus::Stop();
1345 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1346 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1350 /* Database Interface {{{ */
1351 typedef std::map< unsigned long, _H<Source> > SourceMap;
1353 @interface Database : NSObject {
1359 pkgCacheFile cache_;
1360 pkgDepCache::Policy *policy_;
1361 pkgRecords *records_;
1362 pkgProblemResolver *resolver_;
1363 pkgAcquire *fetcher_;
1365 SPtr<pkgPackageManager> manager_;
1366 pkgSourceList *list_;
1368 SourceMap sourceMap_;
1369 NSMutableArray *sourceList_;
1371 CFMutableArrayRef packages_;
1373 _transient NSObject<DatabaseDelegate> *delegate_;
1374 _transient NSObject<ProgressDelegate> *progress_;
1382 std::map<const char *, _H<NSString> > sections_;
1385 + (Database *) sharedInstance;
1388 - (void) _readCydia:(NSNumber *)fd;
1389 - (void) _readStatus:(NSNumber *)fd;
1390 - (void) _readOutput:(NSNumber *)fd;
1394 - (Package *) packageWithName:(NSString *)name;
1396 - (pkgCacheFile &) cache;
1397 - (pkgDepCache::Policy *) policy;
1398 - (pkgRecords *) records;
1399 - (pkgProblemResolver *) resolver;
1400 - (pkgAcquire &) fetcher;
1401 - (pkgSourceList &) list;
1402 - (NSArray *) packages;
1403 - (NSArray *) sources;
1404 - (Source *) sourceWithKey:(NSString *)key;
1405 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1413 - (void) updateWithStatus:(Status &)status;
1415 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1417 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1418 - (NSObject<ProgressDelegate> *) progressDelegate;
1420 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1422 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1426 /* ProgressEvent Implementation {{{ */
1427 @implementation CydiaProgressEvent
1429 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1430 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1433 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1434 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1435 [event setPackage:package];
1439 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1440 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1442 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1443 NSArray *fields([description componentsSeparatedByString:@" "]);
1444 [event setItem:fields];
1446 if ([fields count] > 3) {
1447 [event setPackage:[fields objectAtIndex:2]];
1448 [event setVersion:[fields objectAtIndex:3]];
1451 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1456 + (NSArray *) _attributeKeys {
1457 return [NSArray arrayWithObjects:
1467 - (NSArray *) attributeKeys {
1468 return [[self class] _attributeKeys];
1471 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1472 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1475 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1476 if ((self = [super init]) != nil) {
1482 - (NSString *) message {
1486 - (NSString *) type {
1490 - (NSArray *) item {
1491 return (id) item_ ?: [NSNull null];
1494 - (void) setItem:(NSArray *)item {
1498 - (NSString *) package {
1499 return (id) package_ ?: [NSNull null];
1502 - (void) setPackage:(NSString *)package {
1506 - (NSString *) url {
1507 return (id) url_ ?: [NSNull null];
1510 - (void) setURL:(NSString *)url {
1514 - (void) setVersion:(NSString *)version {
1518 - (NSString *) version {
1519 return (id) version_ ?: [NSNull null];
1522 - (NSString *) compound:(NSString *)value {
1524 NSString *mode(nil); {
1525 NSString *type([self type]);
1526 if ([type isEqualToString:kCydiaProgressEventTypeError])
1527 mode = UCLocalize("ERROR");
1528 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1529 mode = UCLocalize("WARNING");
1533 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1539 - (NSString *) compoundMessage {
1540 return [self compound:[self message]];
1543 - (NSString *) compoundTitle {
1546 if (package_ == nil)
1548 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1549 title = [package name];
1553 return [self compound:title];
1559 // Cytore Definitions {{{
1560 struct PackageValue :
1563 Cytore::Offset<PackageValue> next_;
1565 uint32_t index_ : 23;
1566 uint32_t subscribed_ : 1;
1583 Cytore::Offset<PackageValue> packages_[1 << 16];
1586 static Cytore::File<MetaValue> MetaFile_;
1588 // Cytore Helper Functions {{{
1589 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1590 SplitHash nhash = { hashlittle(name, length) };
1592 PackageValue *metadata;
1594 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1595 offset: if (offset->IsNull()) {
1596 *offset = MetaFile_.New<PackageValue>(length + 1);
1597 metadata = &MetaFile_.Get(*offset);
1599 if (metadata == NULL) {
1603 metadata = new PackageValue();
1604 memset(metadata, 0, sizeof(*metadata));
1607 memcpy(metadata->name_, name, length + 1);
1608 metadata->nhash_ = nhash.u16[1];
1610 metadata = &MetaFile_.Get(*offset);
1612 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1613 offset = &metadata->next_;
1621 static void PackageImport(const void *key, const void *value, void *context) {
1622 bool &fail(*reinterpret_cast<bool *>(context));
1625 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1626 NSLog(@"failed to import package %@", key);
1630 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1631 NSDictionary *package((NSDictionary *) value);
1633 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1634 if ([subscribed boolValue] && !metadata->subscribed_)
1635 metadata->subscribed_ = true;
1637 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1638 time_t time([date timeIntervalSince1970]);
1639 if (metadata->first_ > time || metadata->first_ == 0)
1640 metadata->first_ = time;
1643 NSDate *date([package objectForKey:@"LastSeen"]);
1644 NSString *version([package objectForKey:@"LastVersion"]);
1646 if (date != nil && version != nil) {
1647 time_t time([date timeIntervalSince1970]);
1648 if (metadata->last_ < time || metadata->last_ == 0)
1649 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1650 size_t length(strlen(buffer));
1651 uint16_t vhash(hashlittle(buffer, length));
1653 size_t capped(std::min<size_t>(8, length));
1654 char *latest(buffer + length - capped);
1656 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1657 metadata->vhash_ = vhash;
1659 metadata->last_ = time;
1665 /* Source Class {{{ */
1666 @interface Source : NSObject {
1667 CYString depiction_;
1668 CYString description_;
1674 CYString distribution_;
1679 _H<NSString> authority_;
1681 CYString defaultIcon_;
1683 _H<NSDictionary> record_;
1687 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1689 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1691 - (NSString *) depictionForPackage:(NSString *)package;
1692 - (NSString *) supportForPackage:(NSString *)package;
1694 - (NSDictionary *) record;
1698 - (NSString *) distribution;
1699 - (NSString *) type;
1701 - (NSString *) host;
1703 - (NSString *) name;
1704 - (NSString *) shortDescription;
1705 - (NSString *) label;
1706 - (NSString *) origin;
1707 - (NSString *) version;
1709 - (NSString *) defaultIcon;
1713 @implementation Source
1717 distribution_.clear();
1720 description_.clear();
1726 defaultIcon_.clear();
1734 // XXX: this is a very inefficient way to call these deconstructors
1739 + (NSArray *) _attributeKeys {
1740 return [NSArray arrayWithObjects:
1747 @"shortDescription",
1755 - (NSArray *) attributeKeys {
1756 return [[self class] _attributeKeys];
1759 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1760 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1763 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1766 trusted_ = index->IsTrusted();
1768 uri_.set(pool, index->GetURI());
1769 distribution_.set(pool, index->GetDist());
1770 type_.set(pool, index->GetType());
1772 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1773 if (dindex != NULL) {
1775 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1778 pkgTagFile tags(&fd);
1780 pkgTagSection section;
1787 {"default-icon", &defaultIcon_},
1788 {"depiction", &depiction_},
1789 {"description", &description_},
1791 {"origin", &origin_},
1792 {"support", &support_},
1793 {"version", &version_},
1796 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1797 const char *start, *end;
1799 if (section.Find(names[i].name_, start, end)) {
1800 CYString &value(*names[i].value_);
1801 value.set(pool, start, end - start);
1807 record_ = [Sources_ objectForKey:[self key]];
1809 NSURL *url([NSURL URLWithString:uri_]);
1813 host_ = [host_ lowercaseString];
1816 // XXX: this is due to a bug in _H<>
1817 authority_ = (id) host_;
1819 authority_ = [url path];
1822 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1823 if ((self = [super init]) != nil) {
1824 [self setMetaIndex:index inPool:pool];
1828 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1829 NSDictionary *lhr = [self record];
1830 NSDictionary *rhr = [source record];
1833 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1835 NSString *lhs = [self name];
1836 NSString *rhs = [source name];
1838 if ([lhs length] != 0 && [rhs length] != 0) {
1839 unichar lhc = [lhs characterAtIndex:0];
1840 unichar rhc = [rhs characterAtIndex:0];
1842 if (isalpha(lhc) && !isalpha(rhc))
1843 return NSOrderedAscending;
1844 else if (!isalpha(lhc) && isalpha(rhc))
1845 return NSOrderedDescending;
1848 return [lhs compare:rhs options:LaxCompareOptions_];
1851 - (NSString *) depictionForPackage:(NSString *)package {
1852 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1855 - (NSString *) supportForPackage:(NSString *)package {
1856 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1859 - (NSDictionary *) record {
1867 - (NSString *) uri {
1871 - (NSString *) distribution {
1872 return distribution_;
1875 - (NSString *) type {
1879 - (NSString *) key {
1880 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1883 - (NSString *) host {
1887 - (NSString *) name {
1888 return origin_.empty() ? (id) authority_ : origin_;
1891 - (NSString *) shortDescription {
1892 return description_;
1895 - (NSString *) label {
1896 return label_.empty() ? (id) authority_ : label_;
1899 - (NSString *) origin {
1903 - (NSString *) version {
1907 - (NSString *) defaultIcon {
1908 return defaultIcon_;
1913 /* CydiaOperation Class {{{ */
1914 @interface CydiaOperation : NSObject {
1915 NSString *operator_;
1919 - (NSString *) operator;
1920 - (NSString *) value;
1924 @implementation CydiaOperation
1927 [operator_ release];
1932 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1933 if ((self = [super init]) != nil) {
1934 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1935 value_ = [[NSString alloc] initWithUTF8String:value];
1939 + (NSArray *) _attributeKeys {
1940 return [NSArray arrayWithObjects:
1946 - (NSArray *) attributeKeys {
1947 return [[self class] _attributeKeys];
1950 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1951 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1954 - (NSString *) operator {
1958 - (NSString *) value {
1964 /* CydiaClause Class {{{ */
1965 @interface CydiaClause : NSObject {
1967 CydiaOperation *version_;
1970 - (NSString *) package;
1971 - (CydiaOperation *) version;
1975 @implementation CydiaClause
1983 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1984 if ((self = [super init]) != nil) {
1985 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1987 if (const char *version = dep.TargetVer())
1988 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1990 version_ = [[NSNull null] retain];
1994 + (NSArray *) _attributeKeys {
1995 return [NSArray arrayWithObjects:
2001 - (NSArray *) attributeKeys {
2002 return [[self class] _attributeKeys];
2005 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2006 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2009 - (NSString *) package {
2013 - (CydiaOperation *) version {
2019 /* CydiaRelation Class {{{ */
2020 @interface CydiaRelation : NSObject {
2021 NSString *relationship_;
2022 NSMutableArray *clauses_;
2025 - (NSString *) relationship;
2026 - (NSArray *) clauses;
2030 @implementation CydiaRelation
2033 [relationship_ release];
2038 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2039 if ((self = [super init]) != nil) {
2040 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
2041 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
2043 pkgCache::DepIterator start;
2044 pkgCache::DepIterator end;
2045 dep.GlobOr(start, end); // ++dep
2048 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2050 // yes, seriously. (wtf?)
2058 + (NSArray *) _attributeKeys {
2059 return [NSArray arrayWithObjects:
2065 - (NSArray *) attributeKeys {
2066 return [[self class] _attributeKeys];
2069 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2070 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2073 - (NSString *) relationship {
2074 return relationship_;
2077 - (NSArray *) clauses {
2081 - (void) addClause:(CydiaClause *)clause {
2082 [clauses_ addObject:clause];
2087 /* Package Class {{{ */
2088 struct ParsedPackage {
2093 CYString depiction_;
2103 @interface Package : NSObject {
2106 uint32_t essential_ : 1;
2107 uint32_t obsolete_ : 1;
2108 uint32_t ignored_ : 1;
2112 _transient Database *database_;
2114 pkgCache::VerIterator version_;
2115 pkgCache::PkgIterator iterator_;
2116 pkgCache::VerFileIterator file_;
2122 CYString installed_;
2124 const char *section_;
2125 _transient NSString *section$_;
2129 PackageValue *metadata_;
2130 ParsedPackage *parsed_;
2132 NSMutableArray *tags_;
2135 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2136 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2138 - (pkgCache::PkgIterator) iterator;
2141 - (NSString *) section;
2142 - (NSString *) simpleSection;
2144 - (NSString *) longSection;
2145 - (NSString *) shortSection;
2149 - (Address *) maintainer;
2151 - (NSString *) longDescription;
2152 - (NSString *) shortDescription;
2155 - (PackageValue *) metadata;
2158 - (bool) subscribed;
2159 - (bool) setSubscribed:(bool)subscribed;
2163 - (NSString *) latest;
2164 - (NSString *) installed;
2165 - (BOOL) uninstalled;
2168 - (BOOL) upgradableAndEssential:(BOOL)essential;
2171 - (BOOL) unfiltered;
2175 - (BOOL) halfConfigured;
2176 - (BOOL) halfInstalled;
2178 - (NSString *) mode;
2181 - (NSString *) name;
2183 - (NSString *) homepage;
2184 - (NSString *) depiction;
2185 - (Address *) author;
2187 - (NSString *) support;
2189 - (NSArray *) files;
2190 - (NSArray *) warnings;
2191 - (NSArray *) applications;
2193 - (Source *) source;
2195 - (BOOL) matches:(NSString *)text;
2197 - (bool) hasSupportingRole;
2198 - (BOOL) hasTag:(NSString *)tag;
2199 - (NSString *) primaryPurpose;
2200 - (NSArray *) purposes;
2201 - (bool) isCommercial;
2203 - (void) setIndex:(size_t)index;
2205 - (CYString &) cyname;
2207 - (uint32_t) compareBySection:(NSArray *)sections;
2212 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2213 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2214 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2215 - (bool) isVisibleInSection:(NSString *)section;
2216 - (bool) isVisibleInSource:(Source *)source;
2220 uint32_t PackageChangesRadix(Package *self, void *) {
2225 uint32_t timestamp : 30;
2226 uint32_t ignored : 1;
2227 uint32_t upgradable : 1;
2231 bool upgradable([self upgradableAndEssential:YES]);
2232 value.bits.upgradable = upgradable ? 1 : 0;
2235 value.bits.timestamp = 0;
2236 value.bits.ignored = [self ignored] ? 0 : 1;
2237 value.bits.upgradable = 1;
2239 value.bits.timestamp = [self seen] >> 2;
2240 value.bits.ignored = 0;
2241 value.bits.upgradable = 0;
2244 return _not(uint32_t) - value.key;
2247 uint32_t PackagePrefixRadix(Package *self, void *context) {
2248 size_t offset(reinterpret_cast<size_t>(context));
2249 CYString &name([self cyname]);
2251 size_t size(name.size());
2254 char *text(name.data());
2257 if (!isdigit(text[0]))
2261 while (size != digits && isdigit(text[digits]))
2269 if (offset == 0 && zeros != 0) {
2270 memset(data, '0', zeros);
2271 memcpy(data + zeros, text, 4 - zeros);
2273 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2274 if (size <= offset - zeros)
2277 text += offset - zeros;
2278 size -= offset - zeros;
2281 memcpy(data, text, 4);
2283 memcpy(data, text, size);
2284 memset(data + size, 0, 4 - size);
2287 for (size_t i(0); i != 4; ++i)
2288 if (isalpha(data[i]))
2296 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2298 /* XXX: ntohl may be more honest */
2299 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2302 CYString &(*PackageName)(Package *self, SEL sel);
2304 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2305 _profile(PackageNameCompare)
2306 CYString &lhi(PackageName(lhs, @selector(cyname)));
2307 CYString &rhi(PackageName(rhs, @selector(cyname)));
2308 CFStringRef lhn(lhi), rhn(rhi);
2311 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2312 else if (rhn == NULL)
2313 return NSOrderedDescending;
2315 _profile(PackageNameCompare$NumbersLast)
2316 if (!lhi.empty() && !rhi.empty()) {
2317 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2318 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2319 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2320 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2321 return lha ? NSOrderedAscending : NSOrderedDescending;
2325 CFIndex length = CFStringGetLength(lhn);
2327 _profile(PackageNameCompare$Compare)
2328 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2333 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2334 return PackageNameCompare(*lhs, *rhs, context);
2337 struct PackageNameOrdering :
2338 std::binary_function<Package *, Package *, bool>
2340 _finline bool operator ()(Package *lhs, Package *rhs) const {
2341 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2345 @implementation Package
2347 - (NSString *) description {
2348 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2352 if (parsed_ != NULL)
2361 + (NSString *) webScriptNameForSelector:(SEL)selector {
2363 else if (selector == @selector(clear))
2365 else if (selector == @selector(getField:))
2367 else if (selector == @selector(hasTag:))
2369 else if (selector == @selector(install))
2371 else if (selector == @selector(remove))
2377 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2378 return [self webScriptNameForSelector:selector] == nil;
2381 + (NSArray *) _attributeKeys {
2382 return [NSArray arrayWithObjects:
2401 @"shortDescription",
2414 - (NSArray *) attributeKeys {
2415 return [[self class] _attributeKeys];
2418 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2419 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2422 - (NSArray *) relations {
2423 @synchronized (database_) {
2424 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2425 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2426 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2430 - (NSString *) getField:(NSString *)name {
2431 @synchronized (database_) {
2432 if ([database_ era] != era_ || file_.end())
2435 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2437 const char *start, *end;
2438 if (!parser.Find([name UTF8String], start, end))
2439 return (NSString *) [NSNull null];
2441 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2445 if (parsed_ != NULL)
2447 @synchronized (database_) {
2448 if ([database_ era] != era_ || file_.end())
2451 ParsedPackage *parsed(new ParsedPackage);
2454 _profile(Package$parse)
2455 pkgRecords::Parser *parser;
2457 _profile(Package$parse$Lookup)
2458 parser = &[database_ records]->Lookup(file_);
2463 _profile(Package$parse$Find)
2468 {"icon", &parsed->icon_},
2469 {"depiction", &parsed->depiction_},
2470 {"homepage", &parsed->homepage_},
2471 {"website", &website},
2472 {"bugs", &parsed->bugs_},
2473 {"support", &parsed->support_},
2474 {"sponsor", &parsed->sponsor_},
2475 {"author", &parsed->author_},
2478 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2479 const char *start, *end;
2481 if (parser->Find(names[i].name_, start, end)) {
2482 CYString &value(*names[i].value_);
2483 _profile(Package$parse$Value)
2484 value.set(pool_, start, end - start);
2490 _profile(Package$parse$Tagline)
2491 const char *start, *end;
2492 if (parser->ShortDesc(start, end)) {
2493 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2496 while (stop != start && stop[-1] == '\r')
2498 parsed->tagline_.set(pool_, start, stop - start);
2502 _profile(Package$parse$Retain)
2503 if (parsed->homepage_.empty())
2504 parsed->homepage_ = website;
2505 if (parsed->homepage_ == parsed->depiction_)
2506 parsed->homepage_.clear();
2511 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2512 if ((self = [super init]) != nil) {
2513 _profile(Package$initWithVersion)
2516 database_ = database;
2517 era_ = [database era];
2521 pkgCache::PkgIterator iterator(version.ParentPkg());
2522 iterator_ = iterator;
2524 _profile(Package$initWithVersion$Version)
2525 if (!version_.end())
2526 file_ = version_.FileList();
2528 pkgCache &cache([database_ cache]);
2529 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2533 _profile(Package$initWithVersion$Cache)
2534 name_.set(NULL, iterator.Display());
2536 latest_.set(NULL, StripVersion_(version_.VerStr()));
2538 pkgCache::VerIterator current(iterator.CurrentVer());
2540 installed_.set(NULL, StripVersion_(current.VerStr()));
2543 _profile(Package$initWithVersion$Tags)
2544 pkgCache::TagIterator tag(iterator.TagList());
2546 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2548 const char *name(tag.Name());
2549 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2551 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2552 if (strcmp(name + 6, "enduser") == 0)
2554 else if (strcmp(name + 6, "hacker") == 0)
2556 else if (strcmp(name + 6, "developer") == 0)
2558 else if (strcmp(name + 6, "cydia") == 0)
2564 if (strncmp(name, "cydia::", 7) == 0) {
2565 if (strcmp(name + 7, "essential") == 0)
2567 else if (strcmp(name + 7, "obsolete") == 0)
2572 } while (!tag.end());
2576 _profile(Package$initWithVersion$Metadata)
2577 const char *mixed(iterator.Name());
2578 size_t size(strlen(mixed));
2579 char lower[size + 1];
2581 for (size_t i(0); i != size; ++i)
2582 lower[i] = mixed[i] | 0x20;
2585 PackageValue *metadata(PackageFind(lower, size));
2586 metadata_ = metadata;
2588 id_.set(NULL, metadata->name_, size);
2590 const char *latest(version_.VerStr());
2591 size_t length(strlen(latest));
2593 uint16_t vhash(hashlittle(latest, length));
2595 size_t capped(std::min<size_t>(8, length));
2596 latest = latest + length - capped;
2598 if (metadata->first_ == 0)
2599 metadata->first_ = now_;
2601 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2602 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2603 metadata->vhash_ = vhash;
2604 metadata->last_ = now_;
2605 } else if (metadata->last_ == 0)
2606 metadata->last_ = metadata->first_;
2609 _profile(Package$initWithVersion$Section)
2610 section_ = iterator.Section();
2613 _profile(Package$initWithVersion$Flags)
2614 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2615 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2620 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2621 pkgCache::VerIterator version;
2623 _profile(Package$packageWithIterator$GetCandidateVer)
2624 version = [database policy]->GetCandidateVer(iterator);
2632 _profile(Package$packageWithIterator$Allocate)
2633 package = [Package allocWithZone:zone];
2636 _profile(Package$packageWithIterator$Initialize)
2638 initWithVersion:version
2645 _profile(Package$packageWithIterator$Autorelease)
2646 package = [package autorelease];
2652 - (pkgCache::PkgIterator) iterator {
2656 - (NSString *) section {
2657 if (section$_ == nil) {
2658 if (section_ == NULL)
2661 _profile(Package$section$mappedSectionForPointer)
2662 section$_ = [database_ mappedSectionForPointer:section_];
2667 - (NSString *) simpleSection {
2668 if (NSString *section = [self section])
2669 return Simplify(section);
2674 - (NSString *) longSection {
2675 return LocalizeSection([self section]);
2678 - (NSString *) shortSection {
2679 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2682 - (NSString *) uri {
2685 pkgIndexFile *index;
2686 pkgCache::PkgFileIterator file(file_.File());
2687 if (![database_ list].FindIndex(file, index))
2689 return [NSString stringWithUTF8String:iterator_->Path];
2690 //return [NSString stringWithUTF8String:file.Site()];
2691 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2695 - (Address *) maintainer {
2696 @synchronized (database_) {
2697 if ([database_ era] != era_ || file_.end())
2700 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2701 const std::string &maintainer(parser->Maintainer());
2702 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2706 @synchronized (database_) {
2707 if ([database_ era] != era_ || version_.end())
2710 return version_->InstalledSize;
2713 - (NSString *) longDescription {
2714 @synchronized (database_) {
2715 if ([database_ era] != era_ || file_.end())
2718 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2719 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2721 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2722 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2723 if ([lines count] < 2)
2726 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2727 for (size_t i(1), e([lines count]); i != e; ++i) {
2728 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2729 [trimmed addObject:trim];
2732 return [trimmed componentsJoinedByString:@"\n"];
2735 - (NSString *) shortDescription {
2736 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2740 _profile(Package$index)
2741 CFStringRef name((CFStringRef) [self name]);
2742 if (CFStringGetLength(name) == 0)
2744 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2745 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2747 return toupper(character);
2751 - (PackageValue *) metadata {
2756 PackageValue *metadata([self metadata]);
2757 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2760 - (bool) subscribed {
2761 return [self metadata]->subscribed_;
2764 - (bool) setSubscribed:(bool)subscribed {
2765 PackageValue *metadata([self metadata]);
2766 if (metadata->subscribed_ == subscribed)
2768 metadata->subscribed_ = subscribed;
2776 - (NSString *) latest {
2780 - (NSString *) installed {
2784 - (BOOL) uninstalled {
2785 return installed_.empty();
2789 return !version_.end();
2792 - (BOOL) upgradableAndEssential:(BOOL)essential {
2793 _profile(Package$upgradableAndEssential)
2794 pkgCache::VerIterator current(iterator_.CurrentVer());
2796 return essential && essential_;
2798 return !version_.end() && version_ != current;
2802 - (BOOL) essential {
2807 return [database_ cache][iterator_].InstBroken();
2810 - (BOOL) unfiltered {
2811 _profile(Package$unfiltered$obsolete)
2812 if (_unlikely(obsolete_))
2816 _profile(Package$unfiltered$hasSupportingRole)
2817 if (_unlikely(![self hasSupportingRole]))
2825 if (![self unfiltered])
2830 _profile(Package$visible$section)
2831 section = [self section];
2834 _profile(Package$visible$isSectionVisible)
2835 if (!isSectionVisible(section))
2843 unsigned char current(iterator_->CurrentState);
2844 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2847 - (BOOL) halfConfigured {
2848 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2851 - (BOOL) halfInstalled {
2852 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2856 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2857 return state.Mode != pkgDepCache::ModeKeep;
2860 - (NSString *) mode {
2861 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2863 switch (state.Mode) {
2864 case pkgDepCache::ModeDelete:
2865 if ((state.iFlags & pkgDepCache::Purge) != 0)
2869 case pkgDepCache::ModeKeep:
2870 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2871 return @"REINSTALL";
2872 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2876 case pkgDepCache::ModeInstall:
2877 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2878 return @"REINSTALL";
2879 else*/ switch (state.Status) {
2881 return @"DOWNGRADE";
2887 return @"NEW_INSTALL";
2898 - (NSString *) name {
2899 return name_.empty() ? id_ : name_;
2902 - (UIImage *) icon {
2903 NSString *section = [self simpleSection];
2906 if (parsed_ != NULL)
2907 if (NSString *href = parsed_->icon_)
2908 if ([href hasPrefix:@"file:///"])
2909 // XXX: correct escaping
2910 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2911 if (icon == nil) if (section != nil)
2912 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2913 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2914 if ([dicon hasPrefix:@"file:///"])
2915 // XXX: correct escaping
2916 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2918 icon = [UIImage applicationImageNamed:@"unknown.png"];
2922 - (NSString *) homepage {
2923 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2926 - (NSString *) depiction {
2927 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2930 - (Address *) sponsor {
2931 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2934 - (Address *) author {
2935 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2938 - (NSString *) support {
2939 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2942 - (NSArray *) files {
2943 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2944 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2947 fin.open([path UTF8String]);
2952 while (std::getline(fin, line))
2953 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2958 - (NSString *) state {
2959 @synchronized (database_) {
2960 if ([database_ era] != era_ || file_.end())
2963 switch (iterator_->CurrentState) {
2964 case pkgCache::State::NotInstalled:
2965 return @"NotInstalled";
2966 case pkgCache::State::UnPacked:
2968 case pkgCache::State::HalfConfigured:
2969 return @"HalfConfigured";
2970 case pkgCache::State::HalfInstalled:
2971 return @"HalfInstalled";
2972 case pkgCache::State::ConfigFiles:
2973 return @"ConfigFiles";
2974 case pkgCache::State::Installed:
2975 return @"Installed";
2976 case pkgCache::State::TriggersAwaited:
2977 return @"TriggersAwaited";
2978 case pkgCache::State::TriggersPending:
2979 return @"TriggersPending";
2982 return (NSString *) [NSNull null];
2985 - (NSString *) selection {
2986 @synchronized (database_) {
2987 if ([database_ era] != era_ || file_.end())
2990 switch (iterator_->SelectedState) {
2991 case pkgCache::State::Unknown:
2993 case pkgCache::State::Install:
2995 case pkgCache::State::Hold:
2997 case pkgCache::State::DeInstall:
2998 return @"DeInstall";
2999 case pkgCache::State::Purge:
3003 return (NSString *) [NSNull null];
3006 - (NSArray *) warnings {
3007 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3008 const char *name(iterator_.Name());
3010 size_t length(strlen(name));
3011 if (length < 2) invalid:
3012 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3013 else for (size_t i(0); i != length; ++i)
3015 /* XXX: technically this is not allowed */
3016 (name[i] < 'A' || name[i] > 'Z') &&
3017 (name[i] < 'a' || name[i] > 'z') &&
3018 (name[i] < '0' || name[i] > '9') &&
3019 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3022 if (strcmp(name, "cydia") != 0) {
3025 bool _private = false;
3028 bool repository = [[self section] isEqualToString:@"Repositories"];
3030 if (NSArray *files = [self files])
3031 for (NSString *file in files)
3032 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3034 else if (!user && [file isEqualToString:@"/User"])
3036 else if (!_private && [file isEqualToString:@"/private"])
3038 else if (!stash && [file isEqualToString:@"/var/stash"])
3041 /* XXX: this is not sensitive enough. only some folders are valid. */
3042 if (cydia && !repository)
3043 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3045 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3047 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3049 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3052 return [warnings count] == 0 ? nil : warnings;
3055 - (NSArray *) applications {
3056 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3058 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3060 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
3061 if (NSArray *files = [self files])
3062 for (NSString *file in files)
3063 if (application_r(file)) {
3064 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3065 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3066 if ([id isEqualToString:me])
3069 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3071 display = application_r[1];
3073 NSString *bundle([file stringByDeletingLastPathComponent]);
3074 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3075 if (icon == nil || [icon length] == 0)
3077 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3079 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3080 [applications addObject:application];
3082 [application addObject:id];
3083 [application addObject:display];
3084 [application addObject:url];
3087 return [applications count] == 0 ? nil : applications;
3090 - (Source *) source {
3091 if (source_ == nil) {
3092 @synchronized (database_) {
3093 if ([database_ era] != era_ || file_.end())
3094 source_ = (Source *) [NSNull null];
3096 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
3100 return source_ == (Source *) [NSNull null] ? nil : source_;
3103 - (BOOL) matches:(NSString *)text {
3109 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
3110 if (range.location != NSNotFound)
3113 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
3114 if (range.location != NSNotFound)
3119 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
3120 if (range.location != NSNotFound)
3126 - (bool) hasSupportingRole {
3131 if ([Role_ isEqualToString:@"User"])
3135 if ([Role_ isEqualToString:@"Hacker"])
3139 if ([Role_ isEqualToString:@"Developer"])
3144 - (NSArray *) tags {
3148 - (BOOL) hasTag:(NSString *)tag {
3149 return tags_ == nil ? NO : [tags_ containsObject:tag];
3152 - (NSString *) primaryPurpose {
3153 for (NSString *tag in tags_)
3154 if ([tag hasPrefix:@"purpose::"])
3155 return [tag substringFromIndex:9];
3159 - (NSArray *) purposes {
3160 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3161 for (NSString *tag in tags_)
3162 if ([tag hasPrefix:@"purpose::"])
3163 [purposes addObject:[tag substringFromIndex:9]];
3164 return [purposes count] == 0 ? nil : purposes;
3167 - (bool) isCommercial {
3168 return [self hasTag:@"cydia::commercial"];
3171 - (void) setIndex:(size_t)index {
3172 if (metadata_->index_ != index)
3173 metadata_->index_ = index;
3176 - (CYString &) cyname {
3177 return name_.empty() ? id_ : name_;
3180 - (uint32_t) compareBySection:(NSArray *)sections {
3181 NSString *section([self section]);
3182 for (size_t i(0), e([sections count]); i != e; ++i) {
3183 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3187 return _not(uint32_t);
3191 @synchronized (database_) {
3192 pkgProblemResolver *resolver = [database_ resolver];
3193 resolver->Clear(iterator_);
3195 pkgCacheFile &cache([database_ cache]);
3196 cache->SetReInstall(iterator_, false);
3197 cache->MarkKeep(iterator_, false);
3201 @synchronized (database_) {
3202 pkgProblemResolver *resolver = [database_ resolver];
3203 resolver->Clear(iterator_);
3204 resolver->Protect(iterator_);
3206 pkgCacheFile &cache([database_ cache]);
3207 cache->SetReInstall(iterator_, false);
3208 cache->MarkInstall(iterator_, false);
3210 pkgDepCache::StateCache &state((*cache)[iterator_]);
3211 if (!state.Install())
3212 cache->SetReInstall(iterator_, true);
3216 @synchronized (database_) {
3217 pkgProblemResolver *resolver = [database_ resolver];
3218 resolver->Clear(iterator_);
3219 resolver->Remove(iterator_);
3220 resolver->Protect(iterator_);
3222 pkgCacheFile &cache([database_ cache]);
3223 cache->SetReInstall(iterator_, false);
3224 cache->MarkDelete(iterator_, true);
3227 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3228 _profile(Package$isUnfilteredAndSearchedForBy)
3231 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3232 value &= [self unfiltered];
3235 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3236 value &= [self matches:search];
3243 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3244 if ([search length] == 0)
3247 _profile(Package$isUnfilteredAndSelectedForBy)
3250 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3251 value &= [self unfiltered];
3254 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3255 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3262 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3263 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3266 - (bool) isVisibleInSection:(NSString *)name {
3267 NSString *section([self section]);
3271 section == nil && [name length] == 0 ||
3272 [name isEqualToString:section]
3273 ) && [self visible];
3276 - (bool) isVisibleInSource:(Source *)source {
3277 return [self source] == source && [self visible];
3282 /* Section Class {{{ */
3283 @interface Section : NSObject {
3288 NSString *localized_;
3291 - (NSComparisonResult) compareByLocalized:(Section *)section;
3292 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3293 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3294 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3295 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3296 - (NSString *) name;
3303 - (void) addToCount;
3305 - (void) setCount:(size_t)count;
3306 - (NSString *) localized;
3310 @implementation Section
3314 if (localized_ != nil)
3315 [localized_ release];
3319 - (NSComparisonResult) compareByLocalized:(Section *)section {
3320 NSString *lhs(localized_);
3321 NSString *rhs([section localized]);
3323 /*if ([lhs length] != 0 && [rhs length] != 0) {
3324 unichar lhc = [lhs characterAtIndex:0];
3325 unichar rhc = [rhs characterAtIndex:0];
3327 if (isalpha(lhc) && !isalpha(rhc))
3328 return NSOrderedAscending;
3329 else if (!isalpha(lhc) && isalpha(rhc))
3330 return NSOrderedDescending;
3333 return [lhs compare:rhs options:LaxCompareOptions_];
3336 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3337 if ((self = [self initWithName:name localize:NO]) != nil) {
3338 if (localized != nil)
3339 localized_ = [localized retain];
3343 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3344 return [self initWithName:name row:0 localize:localize];
3347 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3348 if ((self = [super init]) != nil) {
3349 name_ = [name retain];
3353 localized_ = [LocalizeSection(name_) retain];
3357 /* XXX: localize the index thingees */
3358 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3359 if ((self = [super init]) != nil) {
3360 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3366 - (NSString *) name {
3386 - (void) addToCount {
3390 - (void) setCount:(size_t)count {
3394 - (NSString *) localized {
3401 static NSString *Colon_;
3402 static NSString *Elision_;
3403 static NSString *Error_;
3404 static NSString *Warning_;
3406 /* Database Implementation {{{ */
3407 @implementation Database
3409 + (Database *) sharedInstance {
3410 static Database *instance;
3411 if (instance == nil)
3412 instance = [[Database alloc] init];
3420 - (void) releasePackages {
3421 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3422 CFArrayRemoveAllValues(packages_);
3426 // XXX: actually implement this thing
3428 [sourceList_ release];
3429 [self releasePackages];
3430 apr_pool_destroy(pool_);
3431 NSRecycleZone(zone_);
3435 - (void) _readCydia:(NSNumber *)fd { _pooled
3436 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3437 std::istream is(&ib);
3440 static Pcre finish_r("^finish:([^:]*)$");
3442 while (std::getline(is, line)) {
3443 const char *data(line.c_str());
3444 size_t size = line.size();
3445 lprintf("C:%s\n", data);
3447 if (finish_r(data, size)) {
3448 NSString *finish = finish_r[1];
3449 int index = [Finishes_ indexOfObject:finish];
3450 if (index != INT_MAX && index > Finish_)
3458 - (void) _readStatus:(NSNumber *)fd { _pooled
3459 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3460 std::istream is(&ib);
3463 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3464 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3466 while (std::getline(is, line)) {
3467 const char *data(line.c_str());
3468 size_t size(line.size());
3469 lprintf("S:%s\n", data);
3471 if (conffile_r(data, size)) {
3472 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3473 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3474 } else if (strncmp(data, "status: ", 8) == 0) {
3475 // status: <package>: {unpacked,half-configured,installed}
3476 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3477 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3478 } else if (strncmp(data, "processing: ", 12) == 0) {
3479 // processing: configure: config-test
3480 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3481 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3482 } else if (pmstatus_r(data, size)) {
3483 std::string type([pmstatus_r[1] UTF8String]);
3485 NSString *package = pmstatus_r[2];
3486 if ([package isEqualToString:@"dpkg-exec"])
3489 float percent([pmstatus_r[3] floatValue]);
3490 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3492 NSString *string = pmstatus_r[4];
3494 if (type == "pmerror") {
3495 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3496 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3497 } else if (type == "pmstatus") {
3498 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3499 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3500 } else if (type == "pmconffile")
3501 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3503 lprintf("E:unknown pmstatus\n");
3505 lprintf("E:unknown status\n");
3511 - (void) _readOutput:(NSNumber *)fd { _pooled
3512 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3513 std::istream is(&ib);
3516 while (std::getline(is, line)) {
3517 lprintf("O:%s\n", line.c_str());
3519 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3520 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3530 - (Package *) packageWithName:(NSString *)name {
3531 @synchronized (self) {
3532 if (static_cast<pkgDepCache *>(cache_) == NULL)
3534 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3535 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3539 if ((self = [super init]) != nil) {
3546 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3547 apr_pool_create(&pool_, NULL);
3549 size_t capacity(MetaFile_->active_);
3555 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3556 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3560 _assert(pipe(fds) != -1);
3563 _config->Set("APT::Keep-Fds::", cydiafd_);
3564 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3567 detachNewThreadSelector:@selector(_readCydia:)
3569 withObject:[NSNumber numberWithInt:fds[0]]
3572 _assert(pipe(fds) != -1);
3576 detachNewThreadSelector:@selector(_readStatus:)
3578 withObject:[NSNumber numberWithInt:fds[0]]
3581 _assert(pipe(fds) != -1);
3582 _assert(dup2(fds[0], 0) != -1);
3583 _assert(close(fds[0]) != -1);
3585 input_ = fdopen(fds[1], "a");
3587 _assert(pipe(fds) != -1);
3588 _assert(dup2(fds[1], 1) != -1);
3589 _assert(close(fds[1]) != -1);
3592 detachNewThreadSelector:@selector(_readOutput:)
3594 withObject:[NSNumber numberWithInt:fds[0]]
3599 - (pkgCacheFile &) cache {
3603 - (pkgDepCache::Policy *) policy {
3607 - (pkgRecords *) records {
3611 - (pkgProblemResolver *) resolver {
3615 - (pkgAcquire &) fetcher {
3619 - (pkgSourceList &) list {
3623 - (NSArray *) packages {
3624 return (NSArray *) packages_;
3627 - (NSArray *) sources {
3631 - (Source *) sourceWithKey:(NSString *)key {
3632 for (Source *source in [self sources]) {
3633 if ([[source key] isEqualToString:key])
3638 - (bool) popErrorWithTitle:(NSString *)title {
3641 while (!_error->empty()) {
3643 bool warning(!_error->PopMessage(error));
3648 size_t size(error.size());
3649 if (size == 0 || error[size - 1] != '\n')
3651 error.resize(size - 1);
3654 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3656 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3662 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3663 return [self popErrorWithTitle:title] || !success;
3666 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3667 @synchronized (self) {
3670 [self releasePackages];
3673 [sourceList_ removeAllObjects];
3693 apr_pool_clear(pool_);
3695 NSRecycleZone(zone_);
3696 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3698 int chk(creat("/tmp/cydia.chk", 0644));
3702 if (invocation != nil)
3703 [invocation invoke];
3705 NSString *title(UCLocalize("DATABASE"));
3708 OpProgress progress;
3709 while (!cache_.Open(progress, true)) { pop:
3711 bool warning(!_error->PopMessage(error));
3712 lprintf("cache_.Open():[%s]\n", error.c_str());
3714 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3715 [delegate_ repairWithSelector:@selector(configure)];
3716 else if (error == "The package lists or status file could not be parsed or opened.")
3717 [delegate_ repairWithSelector:@selector(update)];
3718 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3719 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3720 // else if (error == "Malformed Status line")
3721 // else if (error == "The list of sources could not be read.")
3723 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3733 unlink("/tmp/cydia.chk");
3735 now_ = [[NSDate date] timeIntervalSince1970];
3737 policy_ = new pkgDepCache::Policy();
3738 records_ = new pkgRecords(cache_);
3739 resolver_ = new pkgProblemResolver(cache_);
3740 fetcher_ = new pkgAcquire(&status_);
3743 list_ = new pkgSourceList();
3744 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3747 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3748 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3752 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3755 if (cache_->BrokenCount() != 0) {
3756 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3759 if (cache_->BrokenCount() != 0) {
3760 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3764 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3768 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3769 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3770 [sourceList_ addObject:object];
3772 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3773 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3774 // XXX: this could be more intelligent
3775 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3776 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3778 sourceMap_[cached->ID] = object;
3783 /*std::vector<Package *> packages;
3784 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3785 [packages_ release];
3790 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3791 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3792 //packages.push_back(package);
3793 CFArrayAppendValue(packages_, [package retain]);
3797 /*if (packages.empty())
3798 packages_ = [[NSArray alloc] init];
3800 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3803 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3804 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3805 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3813 /*if (!packages.empty())
3814 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3815 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3817 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3819 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3821 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3825 size_t count(CFArrayGetCount(packages_));
3826 MetaFile_->active_ = count;
3828 for (size_t index(0); index != count; ++index)
3829 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3833 } } CYPoolEnd() _trace(); }
3836 @synchronized (self) {
3838 resolver_ = new pkgProblemResolver(cache_);
3840 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3841 if (!cache_[iterator].Keep())
3842 cache_->MarkKeep(iterator, false);
3843 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3844 cache_->SetReInstall(iterator, false);
3847 - (void) configure {
3848 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3850 system([dpkg UTF8String]);
3855 // XXX: I don't remember this condition
3860 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3862 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3864 if ([self popErrorWithTitle:title])
3868 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3871 public pkgArchiveCleaner
3874 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3879 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3886 fetcher_->Shutdown();
3888 pkgRecords records(cache_);
3890 lock_ = new FileFd();
3891 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3893 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3895 if ([self popErrorWithTitle:title])
3899 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3902 manager_ = (_system->CreatePM(cache_));
3903 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3910 bool substrate(RestartSubstrate_);
3911 RestartSubstrate_ = false;
3913 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3915 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3917 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3919 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3920 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3923 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3925 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3927 [self popErrorWithTitle:title];
3931 bool failed = false;
3932 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3933 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3935 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3941 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3949 RestartSubstrate_ = true;
3952 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3954 if (_error->PendingError()) {
3959 if (result == pkgPackageManager::Failed) {
3964 if (result != pkgPackageManager::Completed) {
3969 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3971 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3973 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3974 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3977 if (![before isEqualToArray:after])
3982 NSString *title(UCLocalize("UPGRADE"));
3983 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3989 [self updateWithStatus:status_];
3992 - (void) updateWithStatus:(Status &)status {
3993 NSString *title(UCLocalize("REFRESHING_DATA"));
3996 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4000 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4001 if ([self popErrorWithTitle:title])
4004 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4006 bool success(ListUpdate(status, list, PulseInterval_));
4007 if (status.WasCancelled())
4010 [self popErrorWithTitle:title forOperation:success];
4012 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4014 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
4018 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4019 delegate_ = delegate;
4022 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4023 progress_ = delegate;
4024 status_.setDelegate(delegate);
4027 - (NSObject<ProgressDelegate> *) progressDelegate {
4031 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4032 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4033 return i == sourceMap_.end() ? nil : i->second;
4036 - (NSString *) mappedSectionForPointer:(const char *)section {
4037 _H<NSString> *mapped;
4039 _profile(Database$mappedSectionForPointer$Cache)
4040 mapped = §ions_[section];
4043 if (*mapped == NULL) {
4044 size_t length(strlen(section));
4045 char spaced[length + 1];
4047 _profile(Database$mappedSectionForPointer$Replace)
4048 for (size_t index(0); index != length; ++index)
4049 spaced[index] = section[index] == '_' ? ' ' : section[index];
4050 spaced[length] = '\0';
4055 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4056 string = [NSString stringWithUTF8String:spaced];
4059 _profile(Database$mappedSectionForPointer$Map)
4060 string = [SectionMap_ objectForKey:string] ?: string;
4070 static NSMutableSet *Diversions_;
4072 @interface Diversion : NSObject {
4075 _H<NSString> format_;
4080 @implementation Diversion
4082 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4083 if ((self = [super init]) != nil) {
4084 pattern_ = [from UTF8String];
4090 - (NSString *) divert:(NSString *)url {
4091 return !pattern_(url) ? nil : pattern_->*format_;
4094 + (NSURL *) divertURL:(NSURL *)url {
4096 NSString *href([url absoluteString]);
4098 for (Diversion *diversion in Diversions_)
4099 if (NSString *diverted = [diversion divert:href]) {
4100 url = [NSURL URLWithString:diverted];
4107 - (NSString *) key {
4111 - (NSUInteger) hash {
4115 - (BOOL) isEqual:(Diversion *)object {
4116 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4121 @interface CydiaObject : NSObject {
4123 _transient id delegate_;
4126 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4130 @interface CYBrowserController : BrowserController {
4131 CydiaObject *cydia_;
4134 + (void) addDiversion:(Diversion *)diversion;
4138 /* Web Scripting {{{ */
4139 @implementation CydiaObject
4142 [indirect_ release];
4146 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4147 if ((self = [super init]) != nil) {
4148 indirect_ = [indirect retain];
4152 - (void) setDelegate:(id)delegate {
4153 delegate_ = delegate;
4156 + (NSArray *) _attributeKeys {
4157 return [NSArray arrayWithObjects:
4172 - (NSArray *) attributeKeys {
4173 return [[self class] _attributeKeys];
4176 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4177 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4180 - (NSString *) version {
4184 - (NSString *) device {
4185 return [[UIDevice currentDevice] uniqueIdentifier];
4188 - (NSString *) firmware {
4189 return [[UIDevice currentDevice] systemVersion];
4192 - (NSString *) hostname {
4193 return [[UIDevice currentDevice] name];
4196 - (NSString *) idiom {
4197 return (id) Idiom_ ?: [NSNull null];
4200 - (NSString *) plmn {
4201 return (id) PLMN_ ?: [NSNull null];
4204 - (NSString *) ecid {
4205 return (id) ChipID_ ?: [NSNull null];
4208 - (NSString *) serial {
4209 return SerialNumber_;
4212 - (NSString *) role {
4213 return (id) Role_ ?: [NSNull null];
4216 - (NSString *) model {
4217 return [NSString stringWithUTF8String:Machine_];
4220 - (NSString *) token {
4221 return (id) Token_ ?: [NSNull null];
4224 + (NSString *) webScriptNameForSelector:(SEL)selector {
4226 else if (selector == @selector(addBridgedHost:))
4227 return @"addBridgedHost";
4228 else if (selector == @selector(addPipelinedHost:scheme:))
4229 return @"addPipelinedHost";
4230 else if (selector == @selector(addTrivialSource:))
4231 return @"addTrivialSource";
4232 else if (selector == @selector(close))
4234 else if (selector == @selector(divert::))
4236 else if (selector == @selector(du:))
4238 else if (selector == @selector(stringWithFormat:arguments:))
4240 else if (selector == @selector(getAllSources))
4241 return @"getAllSourcs";
4242 else if (selector == @selector(getKernelNumber:))
4243 return @"getKernelNumber";
4244 else if (selector == @selector(getKernelString:))
4245 return @"getKernelString";
4246 else if (selector == @selector(getInstalledPackages))
4247 return @"getInstalledPackages";
4248 else if (selector == @selector(getPackageById:))
4249 return @"getPackageById";
4250 else if (selector == @selector(getSessionValue:))
4251 return @"getSessionValue";
4252 else if (selector == @selector(installPackages:))
4253 return @"installPackages";
4254 else if (selector == @selector(localizedStringForKey:value:table:))
4256 else if (selector == @selector(popViewController:))
4257 return @"popViewController";
4258 else if (selector == @selector(refreshSources))
4259 return @"refreshSources";
4260 else if (selector == @selector(removeButton))
4261 return @"removeButton";
4262 else if (selector == @selector(setSessionValue::))
4263 return @"setSessionValue";
4264 else if (selector == @selector(substitutePackageNames:))
4265 return @"substitutePackageNames";
4266 else if (selector == @selector(scrollToBottom:))
4267 return @"scrollToBottom";
4268 else if (selector == @selector(setAllowsNavigationAction:))
4269 return @"setAllowsNavigationAction";
4270 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4271 return @"setButtonImage";
4272 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4273 return @"setButtonTitle";
4274 else if (selector == @selector(setHidesBackButton:))
4275 return @"setHidesBackButton";
4276 else if (selector == @selector(setHidesNavigationBar:))
4277 return @"setHidesNavigationBar";
4278 else if (selector == @selector(setNavigationBarStyle:))
4279 return @"setNavigationBarStyle";
4280 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4281 return @"setNavigationBarTintColor";
4282 else if (selector == @selector(setPopupHook:))
4283 return @"setPopupHook";
4284 else if (selector == @selector(setToken:))
4286 else if (selector == @selector(setViewportWidth:))
4287 return @"setViewportWidth";
4288 else if (selector == @selector(statfs:))
4290 else if (selector == @selector(supports:))
4296 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4297 return [self webScriptNameForSelector:selector] == nil;
4300 - (BOOL) supports:(NSString *)feature {
4301 return [feature isEqualToString:@"window.open"];
4304 - (void) divert:(NSString *)from :(NSString *)to {
4305 [CYBrowserController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4308 - (NSNumber *) getKernelNumber:(NSString *)name {
4309 const char *string([name UTF8String]);
4312 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4313 return (id) [NSNull null];
4315 if (size != sizeof(int))
4316 return (id) [NSNull null];
4319 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4320 return (id) [NSNull null];
4322 return [NSNumber numberWithInt:value];
4325 - (NSString *) getKernelString:(NSString *)name {
4326 const char *string([name UTF8String]);
4329 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4330 return (id) [NSNull null];
4332 char value[size + 1];
4333 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4334 return (id) [NSNull null];
4336 // XXX: just in case you request something ludicrous
4339 return [NSString stringWithCString:value];
4342 - (id) getSessionValue:(NSString *)key {
4343 @synchronized (SessionData_) {
4344 return [SessionData_ objectForKey:key];
4347 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4348 @synchronized (SessionData_) {
4349 if (value == (id) [WebUndefined undefined])
4350 [SessionData_ removeObjectForKey:key];
4352 [SessionData_ setObject:value forKey:key];
4355 - (void) addBridgedHost:(NSString *)host {
4356 @synchronized (HostConfig_) {
4357 [BridgedHosts_ addObject:host];
4360 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4361 @synchronized (HostConfig_) {
4362 if (scheme != (id) [WebUndefined undefined])
4363 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4365 [PipelinedHosts_ addObject:host];
4368 - (void) popViewController:(NSNumber *)value {
4369 if (value == (id) [WebUndefined undefined])
4370 value = [NSNumber numberWithBool:YES];
4371 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4374 - (void) addTrivialSource:(NSString *)href {
4375 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4378 - (void) refreshSources {
4379 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4382 - (NSArray *) getAllSources {
4383 return [[Database sharedInstance] sources];
4386 - (NSArray *) getInstalledPackages {
4387 Database *database([Database sharedInstance]);
4388 @synchronized (database) {
4389 NSArray *packages([database packages]);
4390 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4391 for (Package *package in packages)
4392 if (![package uninstalled])
4393 [installed addObject:package];
4397 - (Package *) getPackageById:(NSString *)id {
4398 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4402 return (Package *) [NSNull null];
4405 - (NSArray *) statfs:(NSString *)path {
4408 if (path == nil || statfs([path UTF8String], &stat) == -1)
4411 return [NSArray arrayWithObjects:
4412 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4413 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4414 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4418 - (NSNumber *) du:(NSString *)path {
4419 NSNumber *value(nil);
4422 _assert(pipe(fds) != -1);
4424 pid_t pid(ExecFork());
4426 _assert(dup2(fds[1], 1) != -1);
4427 _assert(close(fds[0]) != -1);
4428 _assert(close(fds[1]) != -1);
4429 /* XXX: this should probably not use du */
4430 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4435 _assert(close(fds[1]) != -1);
4437 if (FILE *du = fdopen(fds[0], "r")) {
4439 while (fgets(line, sizeof(line), du) != NULL) {
4440 size_t length(strlen(line));
4441 while (length != 0 && line[length - 1] == '\n')
4442 line[--length] = '\0';
4443 if (char *tab = strchr(line, '\t')) {
4445 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4450 } else _assert(close(fds[0]));
4454 if (waitpid(pid, &status, 0) == -1)
4457 else _assert(false);
4463 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4466 - (void) installPackages:(NSArray *)packages {
4467 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4470 - (NSString *) substitutePackageNames:(NSString *)message {
4471 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4472 for (size_t i(0), e([words count]); i != e; ++i) {
4473 NSString *word([words objectAtIndex:i]);
4474 if (Package *package = [[Database sharedInstance] packageWithName:word])
4475 [words replaceObjectAtIndex:i withObject:[package name]];
4478 return [words componentsJoinedByString:@" "];
4481 - (void) removeButton {
4482 [indirect_ removeButton];
4485 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4486 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4489 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4490 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4493 - (void) setAllowsNavigationAction:(NSString *)value {
4494 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4497 - (void) setHidesBackButton:(NSString *)value {
4498 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4501 - (void) setHidesNavigationBar:(NSString *)value {
4502 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4505 - (void) setNavigationBarStyle:(NSString *)value {
4506 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4509 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4510 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4511 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4512 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4515 - (void) _setToken:(NSString *)token {
4519 [Metadata_ removeObjectForKey:@"Token"];
4521 [Metadata_ setObject:Token_ forKey:@"Token"];
4526 - (void) setToken:(NSString *)token {
4527 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4530 - (void) setPopupHook:(id)function {
4531 [indirect_ setPopupHook:function];
4534 - (void) scrollToBottom:(NSNumber *)animated {
4535 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4538 - (void) setViewportWidth:(float)width {
4539 [indirect_ setViewportWidthOnMainThread:width];
4542 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4543 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4544 unsigned count([arguments count]);
4546 for (unsigned i(0); i != count; ++i)
4547 values[i] = [arguments objectAtIndex:i];
4548 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4551 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4552 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4554 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4556 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4562 /* @ Loading... Indicator {{{ */
4563 @interface CYLoadingIndicator : UIView {
4564 _H<UIActivityIndicatorView> spinner_;
4566 _H<UIView> container_;
4569 @property (readonly, nonatomic) UILabel *label;
4570 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4574 @implementation CYLoadingIndicator
4576 - (id) initWithFrame:(CGRect)frame {
4577 if ((self = [super initWithFrame:frame]) != nil) {
4578 container_ = [[[UIView alloc] init] autorelease];
4579 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4581 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4582 [spinner_ startAnimating];
4583 [container_ addSubview:spinner_];
4585 label_ = [[[UILabel alloc] init] autorelease];
4586 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4587 [label_ setBackgroundColor:[UIColor clearColor]];
4588 [label_ setTextColor:[UIColor blackColor]];
4589 [label_ setShadowColor:[UIColor whiteColor]];
4590 [label_ setShadowOffset:CGSizeMake(0, 1)];
4591 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4592 [container_ addSubview:label_];
4594 CGSize viewsize = frame.size;
4595 CGSize spinnersize = [spinner_ bounds].size;
4596 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4597 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4599 CGRect containrect = {
4600 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4601 CGSizeMake(bothwidth, spinnersize.height)
4604 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4612 [container_ setFrame:containrect];
4613 [spinner_ setFrame:spinrect];
4614 [label_ setFrame:textrect];
4615 [self addSubview:container_];
4619 - (UILabel *) label {
4623 - (UIActivityIndicatorView *) activityIndicatorView {
4629 /* Emulated Loading Controller {{{ */
4630 @interface CYEmulatedLoadingController : CYViewController {
4631 _transient Database *database_;
4632 _H<CYLoadingIndicator> indicator_;
4633 _H<UITabBar> tabbar_;
4634 _H<UINavigationBar> navbar_;
4639 @implementation CYEmulatedLoadingController
4641 - (id) initWithDatabase:(Database *)database {
4642 if ((self = [super init]) != nil) {
4643 database_ = database;
4648 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4650 UITableView *table([[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]);
4651 [table setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4652 [[self view] addSubview:table];
4654 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4655 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4656 [[self view] addSubview:indicator_];
4658 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4659 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4660 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4661 [[self view] addSubview:tabbar_];
4663 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4664 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4665 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4666 [[self view] addSubview:navbar_];
4669 - (void) releaseSubviews {
4678 /* Cydia Browser Controller {{{ */
4679 @implementation CYBrowserController
4686 - (NSURL *) navigationURL {
4687 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4690 + (void) initialize {
4691 Diversions_ = [[NSMutableSet alloc] initWithCapacity:0];
4694 + (void) addDiversion:(Diversion *)diversion {
4695 [Diversions_ addObject:diversion];
4698 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4699 [super webView:view didClearWindowObject:window forFrame:frame];
4701 WebDataSource *source([frame dataSource]);
4702 NSURLResponse *response([source response]);
4703 NSURL *url([response URL]);
4704 NSString *scheme([[url scheme] lowercaseString]);
4706 bool bridged(false);
4708 @synchronized (HostConfig_) {
4709 if ([scheme isEqualToString:@"file"])
4711 else if ([scheme isEqualToString:@"https"])
4712 if ([BridgedHosts_ containsObject:[url host]])
4717 [window setValue:cydia_ forKey:@"cydia"];
4720 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4721 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4723 [copy setURL:[Diversion divertURL:[copy URL]]];
4725 if (System_ != NULL)
4726 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4727 if (Machine_ != NULL)
4728 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4730 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4735 - (void) setDelegate:(id)delegate {
4736 [super setDelegate:delegate];
4737 [cydia_ setDelegate:delegate];
4741 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4742 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4744 WebView *webview([[webview_ _documentView] webView]);
4746 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4749 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4751 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4752 if (Product_ != nil)
4753 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4755 [webview setApplicationNameForUserAgent:application];
4763 @interface NSObject (CydiaScript)
4764 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4767 @implementation NSObject (CydiaScript)
4769 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4775 @implementation NSArray (CydiaScript)
4777 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4778 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4779 for (size_t i(0), e([self count]); i != e; ++i)
4780 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4786 @implementation NSDictionary (CydiaScript)
4788 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4789 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4791 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4798 /* Confirmation Controller {{{ */
4799 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4800 if (!iterator.end())
4801 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4802 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4804 pkgCache::PkgIterator package(dep.TargetPkg());
4807 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4814 @protocol ConfirmationControllerDelegate
4815 - (void) cancelAndClear:(bool)clear;
4816 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4820 @interface ConfirmationController : CYBrowserController {
4821 _transient Database *database_;
4823 UIAlertView *essential_;
4825 NSDictionary *changes_;
4826 NSMutableArray *issues_;
4827 NSDictionary *sizes_;
4832 - (id) initWithDatabase:(Database *)database;
4836 @implementation ConfirmationController
4843 if (essential_ != nil)
4844 [essential_ release];
4851 RestartSubstrate_ = true;
4852 [delegate_ confirmWithNavigationController:[self navigationController]];
4855 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4856 NSString *context([alert context]);
4858 if ([context isEqualToString:@"remove"]) {
4859 if (button == [alert cancelButtonIndex])
4860 [self dismissModalViewControllerAnimated:YES];
4861 else if (button == [alert firstOtherButtonIndex]) {
4865 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4866 } else if ([context isEqualToString:@"unable"]) {
4867 [self dismissModalViewControllerAnimated:YES];
4868 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4870 [super alertView:alert clickedButtonAtIndex:button];
4874 - (void) _doContinue {
4875 [self dismissModalViewControllerAnimated:YES];
4876 [delegate_ cancelAndClear:NO];
4879 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4880 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4884 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4885 [super webView:view didClearWindowObject:window forFrame:frame];
4887 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4888 changes_, @"changes",
4892 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4895 - (id) initWithDatabase:(Database *)database {
4896 if ((self = [super init]) != nil) {
4897 database_ = database;
4899 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4900 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4901 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4902 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4903 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4907 pkgCacheFile &cache([database_ cache]);
4908 NSArray *packages([database_ packages]);
4909 pkgDepCache::Policy *policy([database_ policy]);
4911 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4913 for (Package *package in packages) {
4914 pkgCache::PkgIterator iterator([package iterator]);
4915 NSString *name([package id]);
4917 if ([package broken]) {
4918 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4920 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4922 reasons, @"reasons",
4925 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4929 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4930 pkgCache::DepIterator start;
4931 pkgCache::DepIterator end;
4932 dep.GlobOr(start, end); // ++dep
4934 if (!cache->IsImportantDep(end))
4936 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4939 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4941 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4942 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4943 clauses, @"clauses",
4947 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4949 pkgCache::PkgIterator target(start.TargetPkg());
4950 if (target->ProvidesList != 0)
4951 reason = @"missing";
4953 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4955 reason = @"installed";
4956 installed = [NSString stringWithUTF8String:ver.VerStr()];
4957 } else if (!cache[target].CandidateVerIter(cache).end())
4958 reason = @"uninstalled";
4959 else if (target->ProvidesList == 0)
4960 reason = @"uninstallable";
4962 reason = @"virtual";
4965 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4966 [NSString stringWithUTF8String:start.CompType()], @"operator",
4967 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4970 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4971 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4972 version, @"version",
4974 installed, @"installed",
4977 // yes, seriously. (wtf?)
4985 pkgDepCache::StateCache &state(cache[iterator]);
4987 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4989 if (state.NewInstall())
4990 [installs addObject:name];
4991 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4992 [reinstalls addObject:name];
4993 else if (state.Upgrade())
4994 [upgrades addObject:name];
4995 else if (state.Downgrade())
4996 [downgrades addObject:name];
4997 else if (!state.Delete())
4999 else if (special_r(name))
5000 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5001 [NSNull null], @"package",
5002 [NSArray arrayWithObjects:
5003 [NSDictionary dictionaryWithObjectsAndKeys:
5004 @"Conflicts", @"relationship",
5005 [NSArray arrayWithObjects:
5006 [NSDictionary dictionaryWithObjectsAndKeys:
5008 [NSNull null], @"version",
5009 @"installed", @"reason",
5016 if ([package essential])
5018 [removes addObject:name];
5021 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5022 substrate_ |= DepSubstrate(iterator.CurrentVer());
5027 else if (Advanced_) {
5028 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5030 essential_ = [[UIAlertView alloc]
5031 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5032 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5034 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5036 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5040 [essential_ setContext:@"remove"];
5042 essential_ = [[UIAlertView alloc]
5043 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5044 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5046 cancelButtonTitle:UCLocalize("OKAY")
5047 otherButtonTitles:nil
5050 [essential_ setContext:@"unable"];
5053 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
5054 installs, @"installs",
5055 reinstalls, @"reinstalls",
5056 upgrades, @"upgrades",
5057 downgrades, @"downgrades",
5058 removes, @"removes",
5061 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
5062 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5063 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5066 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5068 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
5069 initWithTitle:UCLocalize("CANCEL")
5070 style:UIBarButtonItemStylePlain
5072 action:@selector(cancelButtonClicked)
5078 - (void) applyRightButton {
5079 if ([issues_ count] == 0 && ![self isLoading])
5080 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5081 initWithTitle:UCLocalize("CONFIRM")
5082 style:UIBarButtonItemStyleDone
5084 action:@selector(confirmButtonClicked)
5087 [[self navigationItem] setRightBarButtonItem:nil];
5091 - (void) cancelButtonClicked {
5092 [self dismissModalViewControllerAnimated:YES];
5093 [delegate_ cancelAndClear:YES];
5097 - (void) confirmButtonClicked {
5098 if (essential_ != nil)
5108 /* Progress Data {{{ */
5109 @interface CydiaProgressData : NSObject {
5110 _transient id delegate_;
5119 _H<NSMutableArray> events_;
5120 _H<NSString> title_;
5122 _H<NSString> status_;
5123 _H<NSString> finish_;
5128 @implementation CydiaProgressData
5130 + (NSArray *) _attributeKeys {
5131 return [NSArray arrayWithObjects:
5143 - (NSArray *) attributeKeys {
5144 return [[self class] _attributeKeys];
5147 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5148 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5152 if ((self = [super init]) != nil) {
5153 events_ = [NSMutableArray arrayWithCapacity:32];
5157 - (void) setDelegate:(id)delegate {
5158 delegate_ = delegate;
5161 - (void) setPercent:(float)value {
5165 - (NSNumber *) percent {
5166 return [NSNumber numberWithFloat:percent_];
5169 - (void) setCurrent:(float)value {
5173 - (NSNumber *) current {
5174 return [NSNumber numberWithFloat:current_];
5177 - (void) setTotal:(float)value {
5181 - (NSNumber *) total {
5182 return [NSNumber numberWithFloat:total_];
5185 - (void) setSpeed:(float)value {
5189 - (NSNumber *) speed {
5190 return [NSNumber numberWithFloat:speed_];
5193 - (NSArray *) events {
5197 - (void) removeAllEvents {
5198 [events_ removeAllObjects];
5201 - (void) addEvent:(CydiaProgressEvent *)event {
5202 [events_ addObject:event];
5205 - (void) setTitle:(NSString *)text {
5209 - (NSString *) title {
5213 - (void) setFinish:(NSString *)text {
5217 - (NSString *) finish {
5218 return (id) finish_ ?: [NSNull null];
5221 - (void) setRunning:(bool)running {
5225 - (NSNumber *) running {
5226 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5231 /* Progress Controller {{{ */
5232 @interface ProgressController : CYBrowserController <
5235 _transient Database *database_;
5236 _H<CydiaProgressData> progress_;
5240 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5242 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5244 - (void) setTitle:(NSString *)title;
5245 - (void) setCancellable:(bool)cancellable;
5249 @implementation ProgressController
5252 [database_ setProgressDelegate:nil];
5253 [progress_ setDelegate:nil];
5257 - (void) updateCancel {
5258 [[self navigationItem] setLeftBarButtonItem:(cancel_ == 1 ? [[[UIBarButtonItem alloc]
5259 initWithTitle:UCLocalize("CANCEL")
5260 style:UIBarButtonItemStylePlain
5262 action:@selector(cancel)
5263 ] autorelease] : nil)];
5266 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5267 if ((self = [super init]) != nil) {
5268 database_ = database;
5269 delegate_ = delegate;
5271 [database_ setProgressDelegate:self];
5273 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5274 [progress_ setDelegate:self];
5276 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5278 [scroller_ setBackgroundColor:[UIColor blackColor]];
5280 [[self navigationItem] setHidesBackButton:YES];
5282 [self updateCancel];
5286 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5287 [super webView:view didClearWindowObject:window forFrame:frame];
5288 [window setValue:progress_ forKey:@"cydiaProgress"];
5291 - (void) updateProgress {
5292 [self dispatchEvent:@"CydiaProgressUpdate"];
5295 - (void) viewWillAppear:(BOOL)animated {
5296 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5297 [super viewWillAppear:animated];
5301 UpdateExternalStatus(0);
5308 [delegate_ terminateWithSuccess];
5309 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5310 [delegate_ suspendWithAnimation:YES];
5312 [delegate_ suspend];*/
5324 system("/usr/bin/sbreload");
5330 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5331 SBReboot(SBSSpringBoardServerPort());
5333 reboot2(RB_AUTOBOOT);
5340 - (void) setTitle:(NSString *)title {
5341 [progress_ setTitle:title];
5342 [self updateProgress];
5345 - (UIBarButtonItem *) rightButton {
5346 return [[progress_ running] boolValue] ? nil : [[[UIBarButtonItem alloc]
5347 initWithTitle:UCLocalize("CLOSE")
5348 style:UIBarButtonItemStylePlain
5350 action:@selector(close)
5354 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5355 UpdateExternalStatus(1);
5357 [progress_ setRunning:true];
5358 [self setTitle:title];
5359 // implicit updateProgress
5361 SHA1SumValue notifyconf; {
5363 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5366 MMap mmap(file, MMap::ReadOnly);
5368 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5369 notifyconf = sha1.Result();
5373 SHA1SumValue springlist; {
5375 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5378 MMap mmap(file, MMap::ReadOnly);
5380 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5381 springlist = sha1.Result();
5385 if (invocation != nil) {
5386 [invocation yieldToSelector:@selector(invoke)];
5387 [self setTitle:@"COMPLETE"];
5392 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5395 MMap mmap(file, MMap::ReadOnly);
5397 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5398 if (!(notifyconf == sha1.Result()))
5405 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5408 MMap mmap(file, MMap::ReadOnly);
5410 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5411 if (!(springlist == sha1.Result()))
5417 if (RestartSubstrate_)
5421 RestartSubstrate_ = false;
5424 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5425 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5426 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5427 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5428 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5432 system("su -c /usr/bin/uicache mobile");
5435 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5437 [progress_ setRunning:false];
5438 [self updateProgress];
5440 [self applyRightButton];
5443 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5444 [progress_ addEvent:event];
5445 [self updateProgress];
5448 - (bool) isProgressCancelled {
5449 return cancel_ == 2;
5454 [self updateCancel];
5457 - (void) setCancellable:(bool)cancellable {
5458 unsigned cancel(cancel_);
5462 else if (cancel_ == 0)
5465 if (cancel != cancel_)
5466 [self updateCancel];
5469 - (void) setProgressCancellable:(NSNumber *)cancellable {
5470 [self setCancellable:[cancellable boolValue]];
5473 - (void) setProgressPercent:(NSNumber *)percent {
5474 [progress_ setPercent:[percent floatValue]];
5475 [self updateProgress];
5478 - (void) setProgressStatus:(NSDictionary *)status {
5479 if (status == nil) {
5480 [progress_ setCurrent:0];
5481 [progress_ setTotal:0];
5482 [progress_ setSpeed:0];
5484 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5486 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5487 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5488 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5491 [self updateProgress];
5497 /* Cell Content View {{{ */
5498 @protocol ContentDelegate
5499 - (void) drawContentRect:(CGRect)rect;
5502 @interface ContentView : UIView {
5503 _transient id<ContentDelegate> delegate_;
5508 @implementation ContentView
5510 - (id) initWithFrame:(CGRect)frame {
5511 if ((self = [super initWithFrame:frame]) != nil) {
5512 [self setNeedsDisplayOnBoundsChange:YES];
5516 - (void) setDelegate:(id<ContentDelegate>)delegate {
5517 delegate_ = delegate;
5520 - (void) drawRect:(CGRect)rect {
5521 [super drawRect:rect];
5522 [delegate_ drawContentRect:rect];
5527 /* Cydia TableView Cell {{{ */
5528 @interface CYTableViewCell : UITableViewCell {
5529 ContentView *content_;
5535 @implementation CYTableViewCell
5542 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5543 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5545 if (view == content_) {
5546 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5547 highlighted_ = highlighted;
5550 [super _updateHighlightColorsForView:view highlighted:highlighted];
5553 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5554 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5555 highlighted_ = selected;
5557 [super setSelected:selected animated:animated];
5558 [content_ setNeedsDisplay];
5564 /* Package Cell {{{ */
5565 @interface PackageCell : CYTableViewCell <
5570 NSString *description_;
5578 - (PackageCell *) init;
5579 - (void) setPackage:(Package *)package;
5581 - (void) drawContentRect:(CGRect)rect;
5585 @implementation PackageCell
5587 - (void) clearPackage {
5598 if (description_ != nil) {
5599 [description_ release];
5603 if (source_ != nil) {
5608 if (badge_ != nil) {
5613 if (placard_ != nil) {
5623 [self clearPackage];
5627 - (PackageCell *) init {
5628 CGRect frame(CGRectMake(0, 0, 320, 74));
5629 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5630 UIView *content([self contentView]);
5631 CGRect bounds([content bounds]);
5633 content_ = [[ContentView alloc] initWithFrame:bounds];
5634 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5635 [content addSubview:content_];
5637 [content_ setDelegate:self];
5638 [content_ setOpaque:YES];
5642 - (NSString *) accessibilityLabel {
5643 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5646 - (void) setPackage:(Package *)package {
5647 [self clearPackage];
5650 Source *source = [package source];
5652 icon_ = [[package icon] retain];
5653 name_ = [[package name] retain];
5656 description_ = [package longDescription];
5657 if (description_ == nil)
5658 description_ = [package shortDescription];
5659 if (description_ != nil)
5660 description_ = [description_ retain];
5662 commercial_ = [package isCommercial];
5664 package_ = [package retain];
5666 NSString *label = nil;
5667 bool trusted = false;
5669 if (source != nil) {
5670 label = [source label];
5671 trusted = [source trusted];
5672 } else if ([[package id] isEqualToString:@"firmware"])
5673 label = UCLocalize("APPLE");
5675 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5677 NSString *from(label);
5679 NSString *section = [package simpleSection];
5680 if (section != nil && ![section isEqualToString:label]) {
5681 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5682 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5685 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5686 source_ = [from retain];
5688 if (NSString *purpose = [package primaryPurpose])
5689 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5690 badge_ = [badge_ retain];
5695 if (NSString *mode = [package_ mode]) {
5696 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5697 color = RemovingColor_;
5698 //placard = @"removing";
5700 color = InstallingColor_;
5701 //placard = @"installing";
5704 // XXX: the removing/installing placards are not @2x
5707 color = [UIColor whiteColor];
5709 if ([package installed] != nil)
5710 placard = @"installed";
5715 [content_ setBackgroundColor:color];
5718 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5719 placard_ = [placard_ retain];
5721 [self setNeedsDisplay];
5722 [content_ setNeedsDisplay];
5725 - (void) drawContentRect:(CGRect)rect {
5726 bool highlighted(highlighted_);
5727 float width([self bounds].size.width);
5730 CGContextRef context(UIGraphicsGetCurrentContext());
5731 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5732 CGContextFillRect(context, rect);
5737 rect.size = [icon_ size];
5739 rect.size.width /= 2;
5740 rect.size.height /= 2;
5742 rect.origin.x = 25 - rect.size.width / 2;
5743 rect.origin.y = 25 - rect.size.height / 2;
5745 [icon_ drawInRect:rect];
5748 if (badge_ != nil) {
5750 rect.size = [badge_ size];
5752 rect.size.width /= 2;
5753 rect.size.height /= 2;
5755 rect.origin.x = 36 - rect.size.width / 2;
5756 rect.origin.y = 36 - rect.size.height / 2;
5758 [badge_ drawInRect:rect];
5765 UISetColor(commercial_ ? Purple_ : Black_);
5766 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5767 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5770 UISetColor(commercial_ ? Purplish_ : Gray_);
5771 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5773 if (placard_ != nil)
5774 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5779 /* Section Cell {{{ */
5780 @interface SectionCell : CYTableViewCell <
5792 - (void) setSection:(Section *)section editing:(BOOL)editing;
5796 @implementation SectionCell
5798 - (void) clearSection {
5799 if (basic_ != nil) {
5804 if (section_ != nil) {
5814 if (count_ != nil) {
5821 [self clearSection];
5827 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5828 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5829 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5830 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5831 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5833 UIView *content([self contentView]);
5834 CGRect bounds([content bounds]);
5836 content_ = [[ContentView alloc] initWithFrame:bounds];
5837 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5838 [content addSubview:content_];
5839 [content_ setBackgroundColor:[UIColor whiteColor]];
5841 [content_ setDelegate:self];
5845 - (void) onSwitch:(id)sender {
5846 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5847 if (metadata == nil) {
5848 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5849 [Sections_ setObject:metadata forKey:basic_];
5852 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5856 - (void) setSection:(Section *)section editing:(BOOL)editing {
5857 if (editing != editing_) {
5859 [switch_ removeFromSuperview];
5861 [self addSubview:switch_];
5865 [self clearSection];
5867 if (section == nil) {
5868 name_ = [UCLocalize("ALL_PACKAGES") retain];
5871 basic_ = [section name];
5873 basic_ = [basic_ retain];
5875 section_ = [section localized];
5876 if (section_ != nil)
5877 section_ = [section_ retain];
5879 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5880 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5883 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5886 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5887 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5889 [content_ setNeedsDisplay];
5892 - (void) setFrame:(CGRect)frame {
5893 [super setFrame:frame];
5895 CGRect rect([switch_ frame]);
5896 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5899 - (NSString *) accessibilityLabel {
5903 - (void) drawContentRect:(CGRect)rect {
5904 bool highlighted(highlighted_ && !editing_);
5906 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5911 float width(rect.size.width);
5917 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5919 CGSize size = [count_ sizeWithFont:Font14_];
5923 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5929 /* File Table {{{ */
5930 @interface FileTable : CYViewController <
5931 UITableViewDataSource,
5934 _transient Database *database_;
5937 NSMutableArray *files_;
5941 - (id) initWithDatabase:(Database *)database;
5942 - (void) setPackage:(Package *)package;
5946 @implementation FileTable
5949 [self releaseSubviews];
5958 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5959 return files_ == nil ? 0 : [files_ count];
5962 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5966 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5967 static NSString *reuseIdentifier = @"Cell";
5969 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5971 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5972 [cell setFont:[UIFont systemFontOfSize:16]];
5974 [cell setText:[files_ objectAtIndex:indexPath.row]];
5975 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5980 - (NSURL *) navigationURL {
5981 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5985 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5987 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5988 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5989 [list_ setRowHeight:24.0f];
5990 [list_ setDataSource:self];
5991 [list_ setDelegate:self];
5992 [[self view] addSubview:list_];
5995 - (void) viewDidLoad {
5996 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5999 - (void) releaseSubviews {
6004 - (id) initWithDatabase:(Database *)database {
6005 if ((self = [super init]) != nil) {
6006 database_ = database;
6008 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
6012 - (void) setPackage:(Package *)package {
6013 if (package_ != nil) {
6014 [package_ autorelease];
6023 [files_ removeAllObjects];
6025 if (package != nil) {
6026 package_ = [package retain];
6027 name_ = [[package id] retain];
6029 if (NSArray *files = [package files])
6030 [files_ addObjectsFromArray:files];
6032 if ([files_ count] != 0) {
6033 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6034 [files_ removeObjectAtIndex:0];
6035 [files_ sortUsingSelector:@selector(compareByPath:)];
6037 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6038 [stack addObject:@"/"];
6040 for (int i(0), e([files_ count]); i != e; ++i) {
6041 NSString *file = [files_ objectAtIndex:i];
6042 while (![file hasPrefix:[stack lastObject]])
6043 [stack removeLastObject];
6044 NSString *directory = [stack lastObject];
6045 [stack addObject:[file stringByAppendingString:@"/"]];
6046 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6047 ([stack count] - 2) * 3, "",
6048 [file substringFromIndex:[directory length]]
6057 - (void) reloadData {
6060 [self setPackage:[database_ packageWithName:name_]];
6065 /* Package Controller {{{ */
6066 @interface CYPackageController : CYBrowserController <
6067 UIActionSheetDelegate
6069 _transient Database *database_;
6070 _H<Package> package_;
6073 _H<NSMutableArray> buttons_;
6074 _H<UIBarButtonItem> button_;
6077 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
6081 @implementation CYPackageController
6083 - (NSURL *) navigationURL {
6084 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6087 /* XXX: this is not safe at all... localization of /fail/ */
6088 - (void) _clickButtonWithName:(NSString *)name {
6089 if ([name isEqualToString:UCLocalize("CLEAR")])
6090 [delegate_ clearPackage:package_];
6091 else if ([name isEqualToString:UCLocalize("INSTALL")])
6092 [delegate_ installPackage:package_];
6093 else if ([name isEqualToString:UCLocalize("REINSTALL")])
6094 [delegate_ installPackage:package_];
6095 else if ([name isEqualToString:UCLocalize("REMOVE")])
6096 [delegate_ removePackage:package_];
6097 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6098 [delegate_ installPackage:package_];
6099 else _assert(false);
6102 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6103 NSString *context([sheet context]);
6105 if ([context isEqualToString:@"modify"]) {
6106 if (button != [sheet cancelButtonIndex]) {
6107 NSString *buttonName = [buttons_ objectAtIndex:button];
6108 [self _clickButtonWithName:buttonName];
6111 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6115 - (bool) _allowJavaScriptPanel {
6120 - (void) _customButtonClicked {
6121 int count([buttons_ count]);
6126 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6128 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6129 [buttons addObjectsFromArray:buttons_];
6131 UIActionSheet *sheet = [[[UIActionSheet alloc]
6134 cancelButtonTitle:nil
6135 destructiveButtonTitle:nil
6136 otherButtonTitles:nil
6139 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6141 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6142 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6144 [sheet setContext:@"modify"];
6146 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6150 // We don't want to allow non-commercial packages to do custom things to the install button,
6151 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6152 - (void) customButtonClicked {
6154 [super customButtonClicked];
6156 [self _customButtonClicked];
6159 - (void) reloadButtonClicked {
6160 // Don't reload a commerical package by tapping the loading button,
6161 // but if it's not an Install button, we should forward it on.
6162 if (![package_ uninstalled])
6163 [self _customButtonClicked];
6166 - (void) applyLoadingTitle {
6167 // Don't show "Loading" as the title. Ever.
6170 - (UIBarButtonItem *) rightButton {
6175 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
6176 if ((self = [super init]) != nil) {
6177 database_ = database;
6178 buttons_ = [NSMutableArray arrayWithCapacity:4];
6179 name_ = [NSString stringWithString:name];
6180 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
6184 - (void) reloadData {
6187 package_ = [database_ packageWithName:name_];
6189 [buttons_ removeAllObjects];
6191 if (package_ != nil) {
6192 [(Package *) package_ parse];
6194 commercial_ = [package_ isCommercial];
6196 if ([package_ mode] != nil)
6197 [buttons_ addObject:UCLocalize("CLEAR")];
6198 if ([package_ source] == nil);
6199 else if ([package_ upgradableAndEssential:NO])
6200 [buttons_ addObject:UCLocalize("UPGRADE")];
6201 else if ([package_ uninstalled])
6202 [buttons_ addObject:UCLocalize("INSTALL")];
6204 [buttons_ addObject:UCLocalize("REINSTALL")];
6205 if (![package_ uninstalled])
6206 [buttons_ addObject:UCLocalize("REMOVE")];
6210 switch ([buttons_ count]) {
6211 case 0: title = nil; break;
6212 case 1: title = [buttons_ objectAtIndex:0]; break;
6213 default: title = UCLocalize("MODIFY"); break;
6216 button_ = [[[UIBarButtonItem alloc]
6218 style:UIBarButtonItemStylePlain
6220 action:@selector(customButtonClicked)
6224 - (bool) isLoading {
6225 return commercial_ ? [super isLoading] : false;
6231 /* Package List Controller {{{ */
6232 @interface PackageListController : CYViewController <
6233 UITableViewDataSource,
6236 _transient Database *database_;
6238 NSMutableArray *packages_;
6239 NSMutableArray *sections_;
6241 NSMutableArray *index_;
6242 NSMutableDictionary *indices_;
6246 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6247 - (void) setDelegate:(id)delegate;
6248 - (void) resetCursor;
6252 @implementation PackageListController
6255 [packages_ release];
6256 [sections_ release];
6265 - (void) deselectWithAnimation:(BOOL)animated {
6266 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6269 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6270 CGRect base = [[self view] bounds];
6271 base.size.height -= bounds.size.height;
6272 base.origin = [list_ frame].origin;
6274 [UIView beginAnimations:nil context:NULL];
6275 [UIView setAnimationBeginsFromCurrentState:YES];
6276 [UIView setAnimationCurve:curve];
6277 [UIView setAnimationDuration:duration];
6278 [list_ setFrame:base];
6279 [UIView commitAnimations];
6282 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6283 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6286 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6287 [self resizeForKeyboardBounds:bounds duration:0];
6290 - (void) keyboardWillShow:(NSNotification *)notification {
6293 NSTimeInterval duration;
6294 UIViewAnimationCurve curve;
6295 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6296 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6297 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6298 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6300 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);
6301 UIViewController *base = self;
6302 while ([base parentViewController] != nil)
6303 base = [base parentViewController];
6304 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6305 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6307 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6310 - (void) keyboardWillHide:(NSNotification *)notification {
6311 NSTimeInterval duration;
6312 UIViewAnimationCurve curve;
6313 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6314 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6316 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6319 - (void) viewWillAppear:(BOOL)animated {
6320 [super viewWillAppear:animated];
6322 [self resizeForKeyboardBounds:CGRectZero];
6323 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6324 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6327 - (void) viewWillDisappear:(BOOL)animated {
6328 [super viewWillDisappear:animated];
6330 [self resizeForKeyboardBounds:CGRectZero];
6331 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6332 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6335 - (void) viewDidAppear:(BOOL)animated {
6336 [super viewDidAppear:animated];
6337 [self deselectWithAnimation:animated];
6340 - (void) didSelectPackage:(Package *)package {
6341 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6342 [view setDelegate:delegate_];
6343 [[self navigationController] pushViewController:view animated:YES];
6346 #if TryIndexedCollation
6347 + (BOOL) hasIndexedCollation {
6348 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6352 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6353 NSInteger count([sections_ count]);
6354 return count == 0 ? 1 : count;
6357 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6358 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6360 return [[sections_ objectAtIndex:section] name];
6363 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6364 if ([sections_ count] == 0)
6366 return [[sections_ objectAtIndex:section] count];
6369 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6370 @synchronized (database_) {
6371 if ([database_ era] != era_)
6374 Section *section([sections_ objectAtIndex:[path section]]);
6375 NSInteger row([path row]);
6376 Package *package([packages_ objectAtIndex:([section row] + row)]);
6377 return [[package retain] autorelease];
6380 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6381 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6383 cell = [[[PackageCell alloc] init] autorelease];
6384 [cell setPackage:[self packageAtIndexPath:path]];
6388 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6389 Package *package([self packageAtIndexPath:path]);
6390 package = [database_ packageWithName:[package id]];
6391 [self didSelectPackage:package];
6394 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6395 // XXX: is 20 the most optimal number here?
6396 return [packages_ count] > 20 ? index_ : nil;
6399 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6400 #if TryIndexedCollation
6401 if ([[self class] hasIndexedCollation]) {
6402 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6409 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6410 if ((self = [super init]) != nil) {
6411 database_ = database;
6412 title_ = [title copy];
6413 [[self navigationItem] setTitle:title_];
6415 #if TryIndexedCollation
6416 if ([[self class] hasIndexedCollation])
6417 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6420 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6422 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6424 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6425 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6427 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6428 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6429 [list_ setRowHeight:73];
6430 [[self view] addSubview:list_];
6432 [list_ setDataSource:self];
6433 [list_ setDelegate:self];
6437 - (void) setDelegate:(id)delegate {
6438 delegate_ = delegate;
6441 - (bool) hasPackage:(Package *)package {
6445 - (void) reloadData {
6448 era_ = [database_ era];
6449 NSArray *packages = [database_ packages];
6451 [packages_ removeAllObjects];
6452 [sections_ removeAllObjects];
6454 _profile(PackageTable$reloadData$Filter)
6455 for (Package *package in packages)
6456 if ([self hasPackage:package])
6457 [packages_ addObject:package];
6460 [indices_ removeAllObjects];
6462 Section *section = nil;
6464 #if TryIndexedCollation
6465 if ([[self class] hasIndexedCollation]) {
6466 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6467 NSArray *titles = [collation sectionIndexTitles];
6470 _profile(PackageTable$reloadData$Section)
6471 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6475 _profile(PackageTable$reloadData$Section$Package)
6476 package = [packages_ objectAtIndex:offset];
6477 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6480 while (secidx < index) {
6483 _profile(PackageTable$reloadData$Section$Allocate)
6484 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6487 _profile(PackageTable$reloadData$Section$Add)
6488 [sections_ addObject:section];
6492 [section addToCount];
6498 [index_ removeAllObjects];
6500 _profile(PackageTable$reloadData$Section)
6501 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6505 _profile(PackageTable$reloadData$Section$Package)
6506 package = [packages_ objectAtIndex:offset];
6507 index = [package index];
6510 if (section == nil || [section index] != index) {
6511 _profile(PackageTable$reloadData$Section$Allocate)
6512 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6515 [index_ addObject:[section name]];
6516 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6518 _profile(PackageTable$reloadData$Section$Add)
6519 [sections_ addObject:section];
6523 [section addToCount];
6528 _profile(PackageTable$reloadData$List)
6533 - (void) resetCursor {
6534 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6539 /* Filtered Package List Controller {{{ */
6540 @interface FilteredPackageListController : PackageListController {
6546 - (void) setObject:(id)object;
6547 - (void) setObject:(id)object forFilter:(SEL)filter;
6549 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6553 @implementation FilteredPackageListController
6561 - (void) setFilter:(SEL)filter {
6564 /* XXX: this is an unsafe optimization of doomy hell */
6565 Method method(class_getInstanceMethod([Package class], filter));
6566 _assert(method != NULL);
6567 imp_ = method_getImplementation(method);
6568 _assert(imp_ != NULL);
6571 - (void) setObject:(id)object {
6577 object_ = [object retain];
6580 - (void) setObject:(id)object forFilter:(SEL)filter {
6581 [self setFilter:filter];
6582 [self setObject:object];
6585 - (bool) hasPackage:(Package *)package {
6586 _profile(FilteredPackageTable$hasPackage)
6587 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6591 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6592 if ((self = [super initWithDatabase:database title:title]) != nil) {
6593 [self setFilter:filter];
6594 [self setObject:object];
6601 /* Home Controller {{{ */
6602 @interface HomeController : CYBrowserController {
6607 @implementation HomeController
6610 if ((self = [super init]) != nil) {
6611 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6615 - (NSURL *) navigationURL {
6616 return [NSURL URLWithString:@"cydia://home"];
6619 - (void) aboutButtonClicked {
6620 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6622 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6623 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6624 [alert setCancelButtonIndex:0];
6627 @"Copyright (C) 2008-2011\n"
6628 "Jay Freeman (saurik)\n"
6629 "saurik@saurik.com\n"
6630 "http://www.saurik.com/"
6636 - (void) viewDidLoad {
6637 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6638 initWithTitle:UCLocalize("ABOUT")
6639 style:UIBarButtonItemStylePlain
6641 action:@selector(aboutButtonClicked)
6647 /* Manage Controller {{{ */
6648 @interface ManageController : CYBrowserController {
6651 - (void) queueStatusDidChange;
6655 @implementation ManageController
6658 if ((self = [super init]) != nil) {
6659 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6663 - (NSURL *) navigationURL {
6664 return [NSURL URLWithString:@"cydia://manage"];
6667 - (void) viewDidLoad {
6668 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6669 initWithTitle:UCLocalize("SETTINGS")
6670 style:UIBarButtonItemStylePlain
6672 action:@selector(settingsButtonClicked)
6675 [self queueStatusDidChange];
6678 - (void) settingsButtonClicked {
6679 [delegate_ showSettings];
6683 - (void) queueButtonClicked {
6687 - (void) applyLoadingTitle {
6688 // Disable "Loading" title.
6691 - (void) applyRightButton {
6692 // Disable right button.
6696 - (void) queueStatusDidChange {
6698 if (!IsWildcat_ && Queuing_) {
6699 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6700 initWithTitle:UCLocalize("QUEUE")
6701 style:UIBarButtonItemStyleDone
6703 action:@selector(queueButtonClicked)
6706 [[self navigationItem] setRightBarButtonItem:nil];
6711 - (bool) isLoading {
6712 // Never show as loading.
6719 /* Refresh Bar {{{ */
6720 @interface RefreshBar : UINavigationBar {
6721 UIProgressIndicator *indicator_;
6722 UITextLabel *prompt_;
6723 UIProgressBar *progress_;
6724 UINavigationButton *cancel_;
6729 @implementation RefreshBar
6732 [indicator_ release];
6734 [progress_ release];
6739 - (void) positionViews {
6740 CGRect frame = [cancel_ frame];
6741 frame.size = [cancel_ sizeThatFits:frame.size];
6742 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6743 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6744 [cancel_ setFrame:frame];
6746 CGSize prgsize = {75, 100};
6748 [self frame].size.width - prgsize.width - 10,
6749 ([self frame].size.height - prgsize.height) / 2
6751 [progress_ setFrame:prgrect];
6753 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6754 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6755 CGRect indrect = {{indoffset, indoffset}, indsize};
6756 [indicator_ setFrame:indrect];
6758 CGSize prmsize = {215, indsize.height + 4};
6760 indoffset * 2 + indsize.width,
6761 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6763 [prompt_ setFrame:prmrect];
6766 - (void) setFrame:(CGRect)frame {
6767 [super setFrame:frame];
6768 [self positionViews];
6771 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6772 if ((self = [super initWithFrame:frame]) != nil) {
6773 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6775 [self setBarStyle:UIBarStyleBlack];
6777 UIBarStyle barstyle([self _barStyle:NO]);
6778 bool ugly(barstyle == UIBarStyleDefault);
6780 UIProgressIndicatorStyle style = ugly ?
6781 UIProgressIndicatorStyleMediumBrown :
6782 UIProgressIndicatorStyleMediumWhite;
6784 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6785 [indicator_ setStyle:style];
6786 [indicator_ startAnimation];
6787 [self addSubview:indicator_];
6789 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6790 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6791 [prompt_ setBackgroundColor:[UIColor clearColor]];
6792 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6793 [self addSubview:prompt_];
6795 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6796 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6797 [progress_ setStyle:0];
6798 [self addSubview:progress_];
6800 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6801 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6802 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6803 [cancel_ setBarStyle:barstyle];
6805 [self positionViews];
6809 - (void) setCancellable:(bool)cancellable {
6811 [self addSubview:cancel_];
6813 [cancel_ removeFromSuperview];
6817 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6818 [progress_ setProgress:0];
6822 [self setCancellable:NO];
6825 - (void) setPrompt:(NSString *)prompt {
6826 [prompt_ setText:prompt];
6829 - (void) setProgress:(float)progress {
6830 [progress_ setProgress:progress];
6836 /* Cydia Navigation Controller Interface {{{ */
6837 @interface UINavigationController (Cydia)
6839 - (NSArray *) navigationURLCollection;
6840 - (void) unloadData;
6845 /* Cydia Tab Bar Controller {{{ */
6846 @interface CYTabBarController : UITabBarController <
6847 UITabBarControllerDelegate,
6850 _transient Database *database_;
6851 RefreshBar *refreshbar_;
6855 // XXX: ok, "updatedelegate_"?...
6856 _transient NSObject<CydiaDelegate> *updatedelegate_;
6859 UIViewController *remembered_;
6860 _transient UIViewController *transient_;
6863 - (NSArray *) navigationURLCollection;
6864 - (void) dropBar:(BOOL)animated;
6865 - (void) beginUpdate;
6866 - (void) raiseBar:(BOOL)animated;
6868 - (void) unloadData;
6872 @implementation CYTabBarController
6874 - (void) setUnselectedViewController:(UIViewController *)transient {
6875 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6876 if (transient != nil) {
6877 if (transient_ == nil)
6878 remembered_ = [[controllers objectAtIndex:0] retain];
6879 transient_ = transient;
6880 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6881 [controllers replaceObjectAtIndex:0 withObject:transient_];
6882 [self setSelectedIndex:0];
6883 [self setViewControllers:controllers];
6884 [self concealTabBarSelection];
6885 } else if (remembered_ != nil) {
6886 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6887 transient_ = transient;
6888 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6889 [remembered_ release];
6891 [self setViewControllers:controllers];
6892 [self revealTabBarSelection];
6896 - (UIViewController *) unselectedViewController {
6900 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6901 if ([self unselectedViewController])
6902 [self setUnselectedViewController:nil];
6905 - (NSArray *) navigationURLCollection {
6906 NSMutableArray *items([NSMutableArray array]);
6908 // XXX: Should this deal with transient view controllers?
6909 for (id navigation in [self viewControllers]) {
6910 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6912 [items addObject:stack];
6918 - (void) unloadData {
6919 UIViewController *selected([self selectedViewController]);
6920 for (UINavigationController *controller in [self viewControllers])
6921 [controller unloadData];
6923 [selected reloadData];
6925 if (UIViewController *unselected = [self unselectedViewController])
6926 [unselected reloadData];
6932 [refreshbar_ release];
6933 [[NSNotificationCenter defaultCenter] removeObserver:self];
6938 - (id) initWithDatabase:(Database *)database {
6939 if ((self = [super init]) != nil) {
6940 database_ = database;
6941 [self setDelegate:self];
6943 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6944 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6946 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6950 - (void) setUpdate:(NSDate *)date {
6954 - (void) beginUpdate {
6955 [refreshbar_ start];
6958 [updatedelegate_ retainNetworkActivityIndicator];
6962 detachNewThreadSelector:@selector(performUpdate)
6968 - (void) performUpdate { _pooled
6970 status.setDelegate(self);
6971 [database_ updateWithStatus:status];
6974 performSelectorOnMainThread:@selector(completeUpdate)
6980 - (void) stopUpdateWithSelector:(SEL)selector {
6982 [updatedelegate_ releaseNetworkActivityIndicator];
6984 [self raiseBar:YES];
6987 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6990 - (void) completeUpdate {
6993 [self stopUpdateWithSelector:@selector(reloadData)];
6996 - (void) cancelUpdate {
6997 [self stopUpdateWithSelector:@selector(updateData)];
7000 - (void) cancelPressed {
7001 [self cancelUpdate];
7008 - (void) addProgressEvent:(CydiaProgressEvent *)event {
7009 [refreshbar_ setPrompt:[event compoundMessage]];
7012 - (bool) isProgressCancelled {
7016 - (void) setProgressCancellable:(NSNumber *)cancellable {
7017 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
7020 - (void) setProgressPercent:(NSNumber *)percent {
7021 [refreshbar_ setProgress:[percent floatValue]];
7024 - (void) setProgressStatus:(NSDictionary *)status {
7026 [self setProgressPercent:[status objectForKey:@"Percent"]];
7029 - (void) setUpdateDelegate:(id)delegate {
7030 updatedelegate_ = delegate;
7033 - (CGFloat) statusBarHeight {
7034 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7035 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7037 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7041 - (UIView *) transitionView {
7042 if ([self respondsToSelector:@selector(_transitionView)])
7043 return [self _transitionView];
7045 return MSHookIvar<id>(self, "_viewControllerTransitionView");
7048 - (void) dropBar:(BOOL)animated {
7053 UIView *transition([self transitionView]);
7054 [[self view] addSubview:refreshbar_];
7056 CGRect barframe([refreshbar_ frame]);
7058 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
7059 barframe.origin.y = [self statusBarHeight];
7061 barframe.origin.y = 0;
7063 [refreshbar_ setFrame:barframe];
7066 [UIView beginAnimations:nil context:NULL];
7068 CGRect viewframe = [transition frame];
7069 viewframe.origin.y += barframe.size.height;
7070 viewframe.size.height -= barframe.size.height;
7071 [transition setFrame:viewframe];
7074 [UIView commitAnimations];
7076 // Ensure bar has the proper width for our view, it might have changed
7077 barframe.size.width = viewframe.size.width;
7078 [refreshbar_ setFrame:barframe];
7080 // XXX: fix Apple's layout bug
7081 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7084 - (void) raiseBar:(BOOL)animated {
7089 UIView *transition([self transitionView]);
7090 [refreshbar_ removeFromSuperview];
7092 CGRect barframe([refreshbar_ frame]);
7095 [UIView beginAnimations:nil context:NULL];
7097 CGRect viewframe = [transition frame];
7098 viewframe.origin.y -= barframe.size.height;
7099 viewframe.size.height += barframe.size.height;
7100 [transition setFrame:viewframe];
7103 [UIView commitAnimations];
7105 // XXX: fix Apple's layout bug
7106 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7110 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7111 // XXX: fix Apple's layout bug
7112 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7116 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7117 bool dropped(dropped_);
7122 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7127 // XXX: fix Apple's layout bug
7128 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7131 - (void) statusBarFrameChanged:(NSNotification *)notification {
7141 /* Cydia Navigation Controller Implementation {{{ */
7142 @implementation UINavigationController (Cydia)
7144 - (NSArray *) navigationURLCollection {
7145 NSMutableArray *stack([NSMutableArray array]);
7147 for (CYViewController *controller in [self viewControllers]) {
7148 NSString *url = [[controller navigationURL] absoluteString];
7150 [stack addObject:url];
7156 - (void) reloadData {
7159 if (UIViewController *visible = [self visibleViewController])
7160 [visible reloadData];
7163 - (void) unloadData {
7164 for (CYViewController *page in [self viewControllers])
7173 /* Cydia:// Protocol {{{ */
7174 @interface CydiaURLProtocol : NSURLProtocol {
7179 @implementation CydiaURLProtocol
7181 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7182 NSURL *url([request URL]);
7186 NSString *scheme([[url scheme] lowercaseString]);
7187 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7189 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7195 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7199 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7200 id<NSURLProtocolClient> client([self client]);
7202 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7204 NSData *data(UIImagePNGRepresentation(icon));
7206 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7207 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7208 [client URLProtocol:self didLoadData:data];
7209 [client URLProtocolDidFinishLoading:self];
7213 - (void) startLoading {
7214 id<NSURLProtocolClient> client([self client]);
7215 NSURLRequest *request([self request]);
7217 NSURL *url([request URL]);
7218 NSString *href([url absoluteString]);
7219 NSString *scheme([[url scheme] lowercaseString]);
7223 if ([scheme isEqualToString:@"cydia"])
7224 path = [href substringFromIndex:8];
7225 else if ([scheme isEqualToString:@"about"])
7226 path = [href substringFromIndex:12];
7227 else _assert(false);
7229 NSRange slash([path rangeOfString:@"/"]);
7232 if (slash.location == NSNotFound) {
7236 command = [path substringToIndex:slash.location];
7237 path = [path substringFromIndex:(slash.location + 1)];
7240 Database *database([Database sharedInstance]);
7242 if ([command isEqualToString:@"package-icon"]) {
7245 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7246 Package *package([database packageWithName:path]);
7249 UIImage *icon([package icon]);
7250 [self _returnPNGWithImage:icon forRequest:request];
7251 } else if ([command isEqualToString:@"source-icon"]) {
7254 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7255 NSString *source(Simplify(path));
7256 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7258 icon = [UIImage applicationImageNamed:@"unknown.png"];
7259 [self _returnPNGWithImage:icon forRequest:request];
7260 } else if ([command isEqualToString:@"uikit-image"]) {
7263 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7264 UIImage *icon(_UIImageWithName(path));
7265 [self _returnPNGWithImage:icon forRequest:request];
7266 } else if ([command isEqualToString:@"section-icon"]) {
7269 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7270 NSString *section(Simplify(path));
7271 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7273 icon = [UIImage applicationImageNamed:@"unknown.png"];
7274 [self _returnPNGWithImage:icon forRequest:request];
7276 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7280 - (void) stopLoading {
7286 /* Section Controller {{{ */
7287 @interface SectionController : FilteredPackageListController {
7288 _H<NSString> section_;
7291 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7295 @implementation SectionController
7297 - (NSURL *) navigationURL {
7298 NSString *name = section_;
7302 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7305 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7308 title = UCLocalize("ALL_PACKAGES");
7309 else if (![name isEqual:@""])
7310 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7312 title = UCLocalize("NO_SECTION");
7314 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7321 /* Sections Controller {{{ */
7322 @interface SectionsController : CYViewController <
7323 UITableViewDataSource,
7326 _transient Database *database_;
7327 NSMutableArray *sections_;
7328 NSMutableArray *filtered_;
7332 - (id) initWithDatabase:(Database *)database;
7333 - (void) editButtonClicked;
7337 @implementation SectionsController
7340 [self releaseSubviews];
7341 [sections_ release];
7342 [filtered_ release];
7347 - (NSURL *) navigationURL {
7348 return [NSURL URLWithString:@"cydia://sections"];
7351 - (void) updateNavigationItem {
7352 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7353 if ([sections_ count] == 0) {
7354 [[self navigationItem] setRightBarButtonItem:nil];
7356 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7357 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7359 action:@selector(editButtonClicked)
7360 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7364 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7365 [super setEditing:editing animated:animated];
7370 [delegate_ updateData];
7372 [self updateNavigationItem];
7375 - (void) viewDidAppear:(BOOL)animated {
7376 [super viewDidAppear:animated];
7377 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7380 - (void) viewWillDisappear:(BOOL)animated {
7381 [super viewWillDisappear:animated];
7382 if ([self isEditing]) [self setEditing:NO];
7385 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7386 Section *section = nil;
7387 int index = [indexPath row];
7388 if (![self isEditing]) {
7391 section = [filtered_ objectAtIndex:index];
7393 section = [sections_ objectAtIndex:index];
7398 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7399 if ([self isEditing])
7400 return [sections_ count];
7402 return [filtered_ count] + 1;
7405 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7409 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7410 static NSString *reuseIdentifier = @"SectionCell";
7412 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7414 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7416 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7421 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7422 if ([self isEditing])
7425 Section *section = [self sectionAtIndexPath:indexPath];
7427 SectionController *controller = [[[SectionController alloc]
7428 initWithDatabase:database_
7429 section:[section name]
7431 [controller setDelegate:delegate_];
7433 [[self navigationController] pushViewController:controller animated:YES];
7437 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7439 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7440 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7441 [list_ setRowHeight:45.0f];
7442 [list_ setDataSource:self];
7443 [list_ setDelegate:self];
7444 [[self view] addSubview:list_];
7447 - (void) viewDidLoad {
7448 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7451 - (void) releaseSubviews {
7456 - (id) initWithDatabase:(Database *)database {
7457 if ((self = [super init]) != nil) {
7458 database_ = database;
7460 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7461 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7465 - (void) reloadData {
7468 NSArray *packages = [database_ packages];
7470 [sections_ removeAllObjects];
7471 [filtered_ removeAllObjects];
7473 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7476 for (Package *package in packages) {
7477 NSString *name([package section]);
7478 NSString *key(name == nil ? @"" : name);
7482 _profile(SectionsView$reloadData$Section)
7483 section = [sections objectForKey:key];
7484 if (section == nil) {
7485 _profile(SectionsView$reloadData$Section$Allocate)
7486 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7487 [sections setObject:section forKey:key];
7492 [section addToCount];
7494 _profile(SectionsView$reloadData$Filter)
7495 if (![package valid] || ![package visible])
7503 [sections_ addObjectsFromArray:[sections allValues]];
7505 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7507 for (Section *section in sections_) {
7508 size_t count([section row]);
7512 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7513 [section setCount:count];
7514 [filtered_ addObject:section];
7517 [self updateNavigationItem];
7522 - (void) editButtonClicked {
7523 [self setEditing:![self isEditing] animated:YES];
7529 /* Changes Controller {{{ */
7530 @interface ChangesController : CYViewController <
7531 UITableViewDataSource,
7534 _transient Database *database_;
7536 CFMutableArrayRef packages_;
7537 NSMutableArray *sections_;
7542 - (id) initWithDatabase:(Database *)database;
7546 @implementation ChangesController
7549 [self releaseSubviews];
7550 CFRelease(packages_);
7551 [sections_ release];
7556 - (NSURL *) navigationURL {
7557 return [NSURL URLWithString:@"cydia://changes"];
7560 - (void) viewDidAppear:(BOOL)animated {
7561 [super viewDidAppear:animated];
7562 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7565 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7566 NSInteger count([sections_ count]);
7567 return count == 0 ? 1 : count;
7570 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7571 if ([sections_ count] == 0)
7573 return [[sections_ objectAtIndex:section] name];
7576 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7577 if ([sections_ count] == 0)
7579 return [[sections_ objectAtIndex:section] count];
7582 - (Package *) packageAtIndex:(NSUInteger)index {
7583 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7586 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7587 @synchronized (database_) {
7588 if ([database_ era] != era_)
7591 NSUInteger sectionIndex([path section]);
7592 if (sectionIndex >= [sections_ count])
7594 Section *section([sections_ objectAtIndex:sectionIndex]);
7595 NSInteger row([path row]);
7596 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7599 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7600 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7602 cell = [[[PackageCell alloc] init] autorelease];
7603 [cell setPackage:[self packageAtIndexPath:path]];
7607 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7608 Package *package([self packageAtIndexPath:path]);
7609 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7610 [view setDelegate:delegate_];
7611 [[self navigationController] pushViewController:view animated:YES];
7615 - (void) refreshButtonClicked {
7616 [delegate_ beginUpdate];
7617 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7620 - (void) upgradeButtonClicked {
7621 [delegate_ distUpgrade];
7625 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7627 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7628 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7629 [list_ setRowHeight:73];
7630 [list_ setDataSource:self];
7631 [list_ setDelegate:self];
7632 [[self view] addSubview:list_];
7635 - (void) viewDidLoad {
7636 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7639 - (void) releaseSubviews {
7644 - (id) initWithDatabase:(Database *)database {
7645 if ((self = [super init]) != nil) {
7646 database_ = database;
7648 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7649 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7653 // this mostly works because reloadData (below) is @synchronized (database_)
7654 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7655 - (void) _reloadPackages:(NSArray *)packages {
7656 CFRelease(packages_);
7657 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7660 _profile(ChangesController$_reloadPackages$Filter)
7661 for (Package *package in packages)
7662 if ([package upgradableAndEssential:YES] || [package visible])
7663 CFArrayAppendValue(packages_, package);
7666 _profile(ChangesController$_reloadPackages$radixSort)
7667 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7672 - (void) _reloadData {
7673 @synchronized (database_) {
7674 era_ = [database_ era];
7675 NSArray *packages = [database_ packages];
7677 [sections_ removeAllObjects];
7680 UIProgressHUD *hud([delegate_ addProgressHUD]);
7681 [hud setText:UCLocalize("LOADING")];
7682 //NSLog(@"HUD:%@::%@", delegate_, hud);
7683 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7684 [delegate_ removeProgressHUD:hud];
7686 [self _reloadPackages:packages];
7689 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7690 Section *ignored = nil;
7691 Section *section = nil;
7695 bool unseens = false;
7697 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7699 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7700 Package *package = [self packageAtIndex:offset];
7702 BOOL uae = [package upgradableAndEssential:YES];
7706 time_t seen([package seen]);
7708 if (section == nil || last != seen) {
7712 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7715 _profile(ChangesController$reloadData$Allocate)
7716 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7717 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7718 [sections_ addObject:section];
7722 [section addToCount];
7723 } else if ([package ignored]) {
7724 if (ignored == nil) {
7725 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7727 [ignored addToCount];
7730 [upgradable addToCount];
7735 CFRelease(formatter);
7738 Section *last = [sections_ lastObject];
7739 size_t count = [last count];
7740 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7741 [sections_ removeLastObject];
7744 if ([ignored count] != 0)
7745 [sections_ insertObject:ignored atIndex:0];
7747 [sections_ insertObject:upgradable atIndex:0];
7752 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7753 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7754 style:UIBarButtonItemStylePlain
7756 action:@selector(upgradeButtonClicked)
7759 if (![delegate_ updating])
7760 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7761 initWithTitle:UCLocalize("REFRESH")
7762 style:UIBarButtonItemStylePlain
7764 action:@selector(refreshButtonClicked)
7770 - (void) reloadData {
7772 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7777 /* Search Controller {{{ */
7778 @interface SearchController : FilteredPackageListController <
7781 _H<UISearchBar> search_;
7785 - (id) initWithDatabase:(Database *)database;
7786 - (void) setSearchTerm:(NSString *)term;
7787 - (void) reloadData;
7791 @implementation SearchController
7794 [search_ setDelegate:nil];
7798 - (NSURL *) navigationURL {
7799 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7800 return [NSURL URLWithString:@"cydia://search"];
7802 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7805 - (void) setSearchTerm:(NSString *)searchTerm {
7806 [search_ setText:searchTerm];
7810 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7811 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7812 [search_ resignFirstResponder];
7816 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7817 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7821 - (id) initWithDatabase:(Database *)database {
7822 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7823 search_ = [[[UISearchBar alloc] init] autorelease];
7824 [search_ setDelegate:self];
7828 - (void) viewDidAppear:(BOOL)animated {
7829 [super viewDidAppear:animated];
7831 if (!searchloaded_) {
7832 searchloaded_ = YES;
7833 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7834 [search_ layoutSubviews];
7835 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7837 UITextField *textField;
7838 if ([search_ respondsToSelector:@selector(searchField)])
7839 textField = [search_ searchField];
7841 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7843 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7844 [textField setEnablesReturnKeyAutomatically:NO];
7845 [[self navigationItem] setTitleView:textField];
7849 - (void) reloadData {
7850 [self setObject:[search_ text]];
7856 - (void) didSelectPackage:(Package *)package {
7857 [search_ resignFirstResponder];
7858 [super didSelectPackage:package];
7863 /* Package Settings Controller {{{ */
7864 @interface PackageSettingsController : CYViewController <
7865 UITableViewDataSource,
7868 _transient Database *database_;
7871 UITableView *table_;
7872 UISwitch *subscribedSwitch_;
7873 UISwitch *ignoredSwitch_;
7874 UITableViewCell *subscribedCell_;
7875 UITableViewCell *ignoredCell_;
7878 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7882 @implementation PackageSettingsController
7885 [self releaseSubviews];
7892 - (NSURL *) navigationURL {
7893 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7896 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7897 if (package_ == nil)
7900 if ([package_ installed] == nil)
7906 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7907 if (package_ == nil)
7910 // both sections contain just one item right now.
7914 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7918 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7920 return UCLocalize("SHOW_ALL_CHANGES_EX");
7922 return UCLocalize("IGNORE_UPGRADES_EX");
7925 - (void) onSubscribed:(id)control {
7926 bool value([control isOn]);
7927 if (package_ == nil)
7929 if ([package_ setSubscribed:value])
7930 [delegate_ updateData];
7933 - (void) _updateIgnored {
7934 const char *package([name_ UTF8String]);
7935 bool on([ignoredSwitch_ isOn]);
7937 pid_t pid(ExecFork());
7939 FILE *dpkg(popen("dpkg --set-selections", "w"));
7940 fwrite(package, strlen(package), 1, dpkg);
7943 fwrite(" hold\n", 6, 1, dpkg);
7945 fwrite(" install\n", 9, 1, dpkg);
7955 int result(waitpid(pid, &status, 0));
7958 _assert(result == pid);
7964 - (void) onIgnored:(id)control {
7965 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7966 [invocation setTarget:self];
7967 [invocation setSelector:@selector(_updateIgnored)];
7969 [delegate_ reloadDataWithInvocation:invocation];
7972 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7973 if (package_ == nil)
7976 switch ([indexPath section]) {
7977 case 0: return subscribedCell_;
7978 case 1: return ignoredCell_;
7987 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7989 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7990 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7991 [table_ setDataSource:self];
7992 [table_ setDelegate:self];
7993 [[self view] addSubview:table_];
7995 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7996 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7997 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7999 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
8000 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8001 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8003 subscribedCell_ = [[UITableViewCell alloc] init];
8004 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8005 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8006 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8008 ignoredCell_ = [[UITableViewCell alloc] init];
8009 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8010 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8011 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8014 - (void) viewDidLoad {
8015 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8018 - (void) releaseSubviews {
8019 [ignoredCell_ release];
8022 [subscribedCell_ release];
8023 subscribedCell_ = nil;
8028 [ignoredSwitch_ release];
8029 ignoredSwitch_ = nil;
8031 [subscribedSwitch_ release];
8032 subscribedSwitch_ = nil;
8035 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8036 if ((self = [super init]) != nil) {
8037 database_ = database;
8038 name_ = [package retain];
8042 - (void) reloadData {
8045 if (package_ != nil)
8046 [package_ autorelease];
8047 package_ = [database_ packageWithName:name_];
8049 if (package_ != nil) {
8050 package_ = [package_ retain];
8051 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8052 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8053 } // XXX: what now, G?
8055 [table_ reloadData];
8061 /* Installed Controller {{{ */
8062 @interface InstalledController : FilteredPackageListController {
8066 - (id) initWithDatabase:(Database *)database;
8068 - (void) updateRoleButton;
8069 - (void) queueStatusDidChange;
8073 @implementation InstalledController
8079 - (NSURL *) navigationURL {
8080 return [NSURL URLWithString:@"cydia://installed"];
8083 - (id) initWithDatabase:(Database *)database {
8084 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8085 [self updateRoleButton];
8086 [self queueStatusDidChange];
8091 - (void) queueButtonClicked {
8096 - (void) queueStatusDidChange {
8100 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8101 initWithTitle:UCLocalize("QUEUE")
8102 style:UIBarButtonItemStyleDone
8104 action:@selector(queueButtonClicked)
8107 [[self navigationItem] setLeftBarButtonItem:nil];
8113 - (void) updateRoleButton {
8114 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8115 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8116 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8117 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8119 action:@selector(roleButtonClicked)
8123 - (void) roleButtonClicked {
8124 [self setObject:[NSNumber numberWithBool:expert_]];
8128 [self updateRoleButton];
8134 /* Source Cell {{{ */
8135 @interface SourceCell : CYTableViewCell <
8143 - (void) setSource:(Source *)source;
8147 @implementation SourceCell
8149 - (void) clearSource {
8159 - (void) setSource:(Source *)source {
8163 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
8165 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8166 icon_ = [icon_ retain];
8168 origin_ = [[source name] retain];
8169 label_ = [[source uri] retain];
8171 [content_ setNeedsDisplay];
8179 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8180 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8181 UIView *content([self contentView]);
8182 CGRect bounds([content bounds]);
8184 content_ = [[ContentView alloc] initWithFrame:bounds];
8185 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8186 [content_ setBackgroundColor:[UIColor whiteColor]];
8187 [content addSubview:content_];
8189 [content_ setDelegate:self];
8190 [content_ setOpaque:YES];
8194 - (NSString *) accessibilityLabel {
8198 - (void) drawContentRect:(CGRect)rect {
8199 bool highlighted(highlighted_);
8200 float width(rect.size.width);
8203 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8210 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8214 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8219 /* Source Controller {{{ */
8220 @interface SourceController : FilteredPackageListController {
8221 _transient Source *source_;
8225 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8229 @implementation SourceController
8231 - (NSURL *) navigationURL {
8232 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8235 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8236 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8238 key_ = [[source key] retain];
8242 - (void) reloadData {
8243 source_ = [database_ sourceWithKey:key_];
8245 key_ = [[source_ key] retain];
8246 [self setObject:source_];
8248 [[self navigationItem] setTitle:[source_ label]];
8255 /* Sources Controller {{{ */
8256 @interface SourcesController : CYViewController <
8257 UITableViewDataSource,
8260 _transient Database *database_;
8262 NSMutableArray *sources_;
8266 UIProgressHUD *hud_;
8269 //NSURLConnection *installer_;
8270 NSURLConnection *trivial_;
8271 NSURLConnection *trivial_bz2_;
8272 NSURLConnection *trivial_gz_;
8273 //NSURLConnection *automatic_;
8278 - (id) initWithDatabase:(Database *)database;
8279 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8283 @implementation SourcesController
8285 - (void) _releaseConnection:(NSURLConnection *)connection {
8286 if (connection != nil) {
8287 [connection cancel];
8288 //[connection setDelegate:nil];
8289 [connection release];
8294 [self releaseSubviews];
8300 //[self _releaseConnection:installer_];
8301 [self _releaseConnection:trivial_];
8302 [self _releaseConnection:trivial_gz_];
8303 [self _releaseConnection:trivial_bz2_];
8304 //[self _releaseConnection:automatic_];
8310 - (NSURL *) navigationURL {
8311 return [NSURL URLWithString:@"cydia://sources"];
8314 - (void) viewDidAppear:(BOOL)animated {
8315 [super viewDidAppear:animated];
8316 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8319 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8320 return offset_ == 0 ? 1 : 2;
8323 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8324 switch (section + (offset_ == 0 ? 1 : 0)) {
8325 case 0: return UCLocalize("ENTERED_BY_USER");
8326 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8332 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8333 int count = [sources_ count];
8335 case 0: return (offset_ == 0 ? count : offset_);
8336 case 1: return count - offset_;
8342 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8344 switch (indexPath.section) {
8345 case 0: idx = indexPath.row; break;
8346 case 1: idx = indexPath.row + offset_; break;
8350 return [sources_ objectAtIndex:idx];
8353 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8354 static NSString *cellIdentifier = @"SourceCell";
8356 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8357 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8358 [cell setSource:[self sourceAtIndexPath:indexPath]];
8359 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8364 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8365 Source *source = [self sourceAtIndexPath:indexPath];
8367 SourceController *controller = [[[SourceController alloc]
8368 initWithDatabase:database_
8372 [controller setDelegate:delegate_];
8374 [[self navigationController] pushViewController:controller animated:YES];
8377 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8378 Source *source = [self sourceAtIndexPath:indexPath];
8379 return [source record] != nil;
8382 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8383 Source *source = [self sourceAtIndexPath:indexPath];
8384 [Sources_ removeObjectForKey:[source key]];
8385 [delegate_ syncData];
8389 [delegate_ addTrivialSource:href_];
8390 [delegate_ syncData];
8393 - (NSString *) getWarning {
8394 NSString *href(href_);
8395 NSRange colon([href rangeOfString:@"://"]);
8396 if (colon.location != NSNotFound)
8397 href = [href substringFromIndex:(colon.location + 3)];
8398 href = [href stringByAddingPercentEscapes];
8399 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8400 href = [href stringByCachingURLWithCurrentCDN];
8402 NSURL *url([NSURL URLWithString:href]);
8404 NSStringEncoding encoding;
8405 NSError *error(nil);
8407 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8408 return [warning length] == 0 ? nil : warning;
8412 - (void) _endConnection:(NSURLConnection *)connection {
8413 // XXX: the memory management in this method is horribly awkward
8415 NSURLConnection **field = NULL;
8416 if (connection == trivial_)
8418 else if (connection == trivial_bz2_)
8419 field = &trivial_bz2_;
8420 else if (connection == trivial_gz_)
8421 field = &trivial_gz_;
8422 _assert(field != NULL);
8423 [connection release];
8428 trivial_bz2_ == nil &&
8434 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8437 UIAlertView *alert = [[[UIAlertView alloc]
8438 initWithTitle:UCLocalize("SOURCE_WARNING")
8441 cancelButtonTitle:UCLocalize("CANCEL")
8443 UCLocalize("ADD_ANYWAY"),
8447 [alert setContext:@"warning"];
8448 [alert setNumberOfRows:1];
8452 } else if (error_ != nil) {
8453 UIAlertView *alert = [[[UIAlertView alloc]
8454 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8455 message:[error_ localizedDescription]
8457 cancelButtonTitle:UCLocalize("OK")
8458 otherButtonTitles:nil
8461 [alert setContext:@"urlerror"];
8464 UIAlertView *alert = [[[UIAlertView alloc]
8465 initWithTitle:UCLocalize("NOT_REPOSITORY")
8466 message:UCLocalize("NOT_REPOSITORY_EX")
8468 cancelButtonTitle:UCLocalize("OK")
8469 otherButtonTitles:nil
8472 [alert setContext:@"trivial"];
8476 [delegate_ releaseNetworkActivityIndicator];
8478 [delegate_ removeProgressHUD:hud_];
8487 if (error_ != nil) {
8494 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8495 switch ([response statusCode]) {
8501 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8502 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8504 error_ = [error retain];
8505 [self _endConnection:connection];
8508 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8509 [self _endConnection:connection];
8512 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8513 NSMutableURLRequest *request = [NSMutableURLRequest
8514 requestWithURL:[NSURL URLWithString:href]
8515 cachePolicy:NSURLRequestUseProtocolCachePolicy
8516 timeoutInterval:120.0
8519 [request setHTTPMethod:method];
8521 if (Machine_ != NULL)
8522 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8523 if (UniqueID_ != nil)
8524 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8526 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8529 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8530 NSString *context([alert context]);
8532 if ([context isEqualToString:@"source"]) {
8535 NSString *href = [[alert textField] text];
8537 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8539 if (![href hasSuffix:@"/"])
8540 href_ = [href stringByAppendingString:@"/"];
8543 href_ = [href_ retain];
8545 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8546 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8547 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8548 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8552 // XXX: this is stupid
8553 hud_ = [[delegate_ addProgressHUD] retain];
8554 [hud_ setText:UCLocalize("VERIFYING_URL")];
8555 [delegate_ retainNetworkActivityIndicator];
8564 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8565 } else if ([context isEqualToString:@"trivial"])
8566 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8567 else if ([context isEqualToString:@"urlerror"])
8568 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8569 else if ([context isEqualToString:@"warning"]) {
8584 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8589 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8591 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8592 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8593 [list_ setRowHeight:56];
8594 [list_ setDataSource:self];
8595 [list_ setDelegate:self];
8596 [[self view] addSubview:list_];
8599 - (void) viewDidLoad {
8600 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8601 [self updateButtonsForEditingStatus:NO animated:NO];
8604 - (void) releaseSubviews {
8609 - (id) initWithDatabase:(Database *)database {
8610 if ((self = [super init]) != nil) {
8611 database_ = database;
8612 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8616 - (void) reloadData {
8620 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8623 [sources_ removeAllObjects];
8624 [sources_ addObjectsFromArray:[database_ sources]];
8626 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8629 int count([sources_ count]);
8631 for (int i = 0; i != count; i++) {
8632 if ([[sources_ objectAtIndex:i] record] == nil)
8637 [list_ setEditing:NO];
8638 [self updateButtonsForEditingStatus:NO animated:NO];
8642 - (void) showAddSourcePrompt {
8643 UIAlertView *alert = [[[UIAlertView alloc]
8644 initWithTitle:UCLocalize("ENTER_APT_URL")
8647 cancelButtonTitle:UCLocalize("CANCEL")
8649 UCLocalize("ADD_SOURCE"),
8653 [alert setContext:@"source"];
8654 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8656 [alert setNumberOfRows:1];
8657 [alert addTextFieldWithValue:@"http://" label:@""];
8659 UITextInputTraits *traits = [[alert textField] textInputTraits];
8660 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8661 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8662 [traits setKeyboardType:UIKeyboardTypeURL];
8663 // XXX: UIReturnKeyDone
8664 [traits setReturnKeyType:UIReturnKeyNext];
8669 - (void) addButtonClicked {
8670 [self showAddSourcePrompt];
8673 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8674 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8675 initWithTitle:UCLocalize("ADD")
8676 style:UIBarButtonItemStylePlain
8678 action:@selector(addButtonClicked)
8679 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8681 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8682 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8683 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8685 action:@selector(editButtonClicked)
8686 ] autorelease] animated:animated];
8688 if (IsWildcat_ && !editing)
8689 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8690 initWithTitle:UCLocalize("SETTINGS")
8691 style:UIBarButtonItemStylePlain
8693 action:@selector(settingsButtonClicked)
8697 - (void) settingsButtonClicked {
8698 [delegate_ showSettings];
8701 - (void) editButtonClicked {
8702 [list_ setEditing:![list_ isEditing] animated:YES];
8704 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8710 /* Settings Controller {{{ */
8711 @interface SettingsController : CYViewController <
8712 UITableViewDataSource,
8715 _transient Database *database_;
8716 // XXX: ok, "roledelegate_"?...
8717 _transient id roledelegate_;
8718 UITableView *table_;
8719 UISegmentedControl *segment_;
8723 - (void) showDoneButton;
8724 - (void) resizeSegmentedControl;
8728 @implementation SettingsController
8731 [self releaseSubviews];
8737 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8739 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8740 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8741 [table_ setDelegate:self];
8742 [table_ setDataSource:self];
8743 [[self view] addSubview:table_];
8745 NSArray *items = [NSArray arrayWithObjects:
8747 UCLocalize("HACKER"),
8748 UCLocalize("DEVELOPER"),
8750 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8751 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8752 [container_ addSubview:segment_];
8755 - (void) viewDidLoad {
8756 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8759 if ([Role_ isEqualToString:@"User"]) index = 0;
8760 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8761 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8763 [segment_ setSelectedSegmentIndex:index];
8764 [self showDoneButton];
8767 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8768 [self resizeSegmentedControl];
8771 - (void) releaseSubviews {
8778 [container_ release];
8782 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8783 if ((self = [super init]) != nil) {
8784 database_ = database;
8785 roledelegate_ = delegate;
8789 - (void) resizeSegmentedControl {
8790 CGFloat width = [[self view] frame].size.width;
8791 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8794 - (void) viewWillAppear:(BOOL)animated {
8795 [super viewWillAppear:animated];
8797 [self resizeSegmentedControl];
8800 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8801 [self resizeSegmentedControl];
8804 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8805 [self resizeSegmentedControl];
8809 NSString *role(nil);
8811 switch ([segment_ selectedSegmentIndex]) {
8812 case 0: role = @"User"; break;
8813 case 1: role = @"Hacker"; break;
8814 case 2: role = @"Developer"; break;
8819 if (![role isEqualToString:Role_]) {
8820 bool rolling(Role_ == nil);
8823 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8827 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8831 [roledelegate_ loadData];
8833 [roledelegate_ updateData];
8837 - (void) segmentChanged:(UISegmentedControl *)control {
8838 [self showDoneButton];
8841 - (void) saveAndClose {
8844 [[self navigationItem] setRightBarButtonItem:nil];
8845 [[self navigationController] dismissModalViewControllerAnimated:YES];
8848 - (void) doneButtonClicked {
8849 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8850 [spinner startAnimating];
8851 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8852 [[self navigationItem] setRightBarButtonItem:spinItem];
8854 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8857 - (void) showDoneButton {
8858 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8859 initWithTitle:UCLocalize("DONE")
8860 style:UIBarButtonItemStyleDone
8862 action:@selector(doneButtonClicked)
8863 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8866 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8867 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8871 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8875 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8876 return nil; // This method is required by the protocol.
8879 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8881 return UCLocalize("ROLE_EX");
8883 return [NSString stringWithFormat:
8884 @"%@: %@\n%@: %@\n%@: %@",
8885 UCLocalize("USER"), UCLocalize("USER_EX"),
8886 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8887 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8892 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8893 return section == 3 ? 44.0f : 0;
8896 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8897 return section == 3 ? container_ : nil;
8900 - (void) reloadData {
8903 [table_ reloadData];
8908 /* Stash Controller {{{ */
8909 @interface StashController : CYViewController {
8910 UIActivityIndicatorView *spinner_;
8917 @implementation StashController
8920 [self releaseSubviews];
8926 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8927 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8929 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8930 CGRect spinrect = [spinner_ frame];
8931 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8932 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8933 [spinner_ setFrame:spinrect];
8934 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8935 [[self view] addSubview:spinner_];
8936 [spinner_ startAnimating];
8939 captrect.size.width = [[self view] frame].size.width;
8940 captrect.size.height = 40.0f;
8941 captrect.origin.x = 0;
8942 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8943 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8944 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8945 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8946 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8947 [caption_ setTextColor:[UIColor whiteColor]];
8948 [caption_ setBackgroundColor:[UIColor clearColor]];
8949 [caption_ setShadowColor:[UIColor blackColor]];
8950 [caption_ setTextAlignment:UITextAlignmentCenter];
8951 [[self view] addSubview:caption_];
8954 statusrect.size.width = [[self view] frame].size.width;
8955 statusrect.size.height = 30.0f;
8956 statusrect.origin.x = 0;
8957 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8958 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8959 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8960 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8961 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8962 [status_ setTextColor:[UIColor whiteColor]];
8963 [status_ setBackgroundColor:[UIColor clearColor]];
8964 [status_ setShadowColor:[UIColor blackColor]];
8965 [status_ setTextAlignment:UITextAlignmentCenter];
8966 [[self view] addSubview:status_];
8969 - (void) releaseSubviews {
8983 @interface Cydia : UIApplication <
8984 ConfirmationControllerDelegate,
8987 UINavigationControllerDelegate,
8988 UITabBarControllerDelegate
8990 // XXX: evaluate all fields for _transient
8993 CYTabBarController *tabbar_;
8994 CYEmulatedLoadingController *emulated_;
8996 NSMutableArray *essential_;
8997 NSMutableArray *broken_;
8999 Database *database_;
9006 StashController *stash_;
9015 @implementation Cydia
9017 - (void) beginUpdate {
9018 [tabbar_ beginUpdate];
9022 return [tabbar_ updating];
9026 if ([broken_ count] != 0) {
9027 int count = [broken_ count];
9029 UIAlertView *alert = [[[UIAlertView alloc]
9030 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9031 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9033 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
9035 UCLocalize("TEMPORARY_IGNORE"),
9039 [alert setContext:@"fixhalf"];
9040 [alert setNumberOfRows:2];
9042 } else if (!Ignored_ && [essential_ count] != 0) {
9043 int count = [essential_ count];
9045 UIAlertView *alert = [[[UIAlertView alloc]
9046 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9047 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9049 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9051 UCLocalize("UPGRADE_ESSENTIAL"),
9052 UCLocalize("COMPLETE_UPGRADE"),
9056 [alert setContext:@"upgrade"];
9061 - (void) _saveConfig {
9067 NSString *error(nil);
9069 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9071 NSError *error(nil);
9072 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9073 NSLog(@"failure to save metadata data: %@", error);
9078 NSLog(@"failure to serialize metadata: %@", error);
9083 // Navigation controller for the queuing badge.
9084 - (UINavigationController *) queueNavigationController {
9085 NSArray *controllers = [tabbar_ viewControllers];
9086 return [controllers objectAtIndex:3];
9089 - (void) _updateData {
9092 [tabbar_ unloadData];
9094 UINavigationController *navigation = [self queueNavigationController];
9096 id queuedelegate = nil;
9097 if ([[navigation viewControllers] count] > 0)
9098 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9100 [queuedelegate queueStatusDidChange];
9101 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9104 - (void) _refreshIfPossible:(NSDate *)update {
9105 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9107 bool recently = false;
9108 if (update != nil) {
9109 NSTimeInterval interval([update timeIntervalSinceNow]);
9110 if (interval <= 0 && interval > -(15*60))
9114 // Don't automatic refresh if:
9115 // - We already refreshed recently.
9116 // - We already auto-refreshed this launch.
9117 // - Auto-refresh is disabled.
9118 if (recently || loaded_ || ManualRefresh) {
9119 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9121 // If we are cancelling, we need to make sure it knows it's already loaded.
9125 // We are going to load, so remember that.
9129 SCNetworkReachabilityFlags flags; {
9130 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9131 SCNetworkReachabilityGetFlags(reachability, &flags);
9132 CFRelease(reachability);
9135 // XXX: this elaborate mess is what Apple is using to determine this? :(
9136 // XXX: do we care if the user has to intervene? maybe that's ok?
9138 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9139 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9140 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9141 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9142 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9143 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9147 // If we can reach the server, auto-refresh!
9149 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9154 - (void) refreshIfPossible {
9155 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9158 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
9159 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9160 [hud setText:UCLocalize("RELOADING_DATA")];
9162 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9165 [self removeProgressHUD:hud];
9169 [essential_ removeAllObjects];
9170 [broken_ removeAllObjects];
9172 NSArray *packages([database_ packages]);
9173 for (Package *package in packages) {
9175 [broken_ addObject:package];
9176 if ([package upgradableAndEssential:NO]) {
9177 if ([package essential])
9178 [essential_ addObject:package];
9183 NSLog(@"changes:#%u", changes);
9185 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9188 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9189 [changesItem setBadgeValue:badge];
9190 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9191 [self setApplicationIconBadgeNumber:changes];
9194 [changesItem setBadgeValue:nil];
9195 [changesItem setAnimatedBadge:NO];
9196 [self setApplicationIconBadgeNumber:0];
9201 [self refreshIfPossible];
9204 - (void) updateData {
9213 @synchronized (self) {
9214 [self _reloadDataWithInvocation:nil];
9218 - (void) disemulate {
9219 if (emulated_ == nil)
9222 [window_ addSubview:[tabbar_ view]];
9223 [[emulated_ view] removeFromSuperview];
9224 [emulated_ release];
9226 [window_ setUserInteractionEnabled:YES];
9229 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9230 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9232 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9234 UIViewController *parent;
9235 if (emulated_ == nil)
9244 [parent presentModalViewController:navigation animated:YES];
9247 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9248 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9250 if (navigation != nil)
9251 [navigation pushViewController:progress animated:YES];
9253 [self presentModalViewController:progress force:YES];
9255 [progress invoke:invocation withTitle:title];
9259 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9260 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9263 - (void) repairWithInvocation:(NSInvocation *)invocation {
9265 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9269 - (void) repairWithSelector:(SEL)selector {
9270 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9276 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
9277 _assert(file != NULL);
9279 for (NSString *key in [Sources_ allKeys]) {
9280 NSDictionary *source([Sources_ objectForKey:key]);
9282 fprintf(file, "%s %s %s\n",
9283 [[source objectForKey:@"Type"] UTF8String],
9284 [[source objectForKey:@"URI"] UTF8String],
9285 [[source objectForKey:@"Distribution"] UTF8String]
9291 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9296 - (void) addTrivialSource:(NSString *)href {
9297 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
9300 @"./", @"Distribution",
9301 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
9306 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9307 @synchronized (self) {
9308 [self _reloadDataWithInvocation:invocation];
9312 - (void) reloadData {
9313 [self reloadDataWithInvocation:nil];
9317 pkgProblemResolver *resolver = [database_ resolver];
9319 resolver->InstallProtect();
9320 if (!resolver->Resolve(true))
9325 // XXX: this is a really crappy way of doing this.
9326 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9327 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9328 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9329 if ([tabbar_ updating])
9330 [tabbar_ cancelUpdate];
9332 if (![database_ prepare])
9335 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9336 [page setDelegate:self];
9337 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9340 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9341 [tabbar_ presentModalViewController:confirm_ animated:YES];
9347 @synchronized (self) {
9352 - (void) clearPackage:(Package *)package {
9353 @synchronized (self) {
9360 - (void) installPackages:(NSArray *)packages {
9361 @synchronized (self) {
9362 for (Package *package in packages)
9369 - (void) installPackage:(Package *)package {
9370 @synchronized (self) {
9377 - (void) removePackage:(Package *)package {
9378 @synchronized (self) {
9385 - (void) distUpgrade {
9386 @synchronized (self) {
9387 if (![database_ upgrade])
9393 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9396 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
9401 - (void) showSettings {
9402 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9405 - (void) retainNetworkActivityIndicator {
9406 if (activity_++ == 0)
9407 [self setNetworkActivityIndicatorVisible:YES];
9410 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9414 - (void) releaseNetworkActivityIndicator {
9415 if (--activity_ == 0)
9416 [self setNetworkActivityIndicatorVisible:NO];
9419 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9424 - (void) cancelAndClear:(bool)clear {
9425 @synchronized (self) {
9437 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9438 NSString *context([alert context]);
9440 if ([context isEqualToString:@"conffile"]) {
9441 FILE *input = [database_ input];
9442 if (button == [alert cancelButtonIndex])
9443 fprintf(input, "N\n");
9444 else if (button == [alert firstOtherButtonIndex])
9445 fprintf(input, "Y\n");
9448 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9449 } else if ([context isEqualToString:@"fixhalf"]) {
9450 if (button == [alert cancelButtonIndex]) {
9451 @synchronized (self) {
9452 for (Package *broken in broken_) {
9455 NSString *id = [broken id];
9456 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9457 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9458 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9459 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9465 } else if (button == [alert firstOtherButtonIndex]) {
9466 [broken_ removeAllObjects];
9470 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9471 } else if ([context isEqualToString:@"upgrade"]) {
9472 if (button == [alert firstOtherButtonIndex]) {
9473 @synchronized (self) {
9474 for (Package *essential in essential_)
9475 [essential install];
9480 } else if (button == [alert firstOtherButtonIndex] + 1) {
9482 } else if (button == [alert cancelButtonIndex]) {
9486 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9490 - (void) system:(NSString *)command { _pooled
9492 system([command UTF8String]);
9496 - (void) applicationWillSuspend {
9498 [super applicationWillSuspend];
9501 - (BOOL) isSafeToSuspend {
9504 NSLog(@"isSafeToSuspend: locked_ != 0");
9509 // Use external process status API internally.
9510 // This is probably a really bad idea.
9511 // XXX: what is the point of this? does this solve anything at all?
9512 uint64_t status = 0;
9514 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9515 notify_get_state(notify_token, &status);
9516 notify_cancel(notify_token);
9521 NSLog(@"isSafeToSuspend: status != 0");
9527 NSLog(@"isSafeToSuspend: -> true");
9532 - (void) applicationSuspend:(__GSEvent *)event {
9533 if ([self isSafeToSuspend])
9534 [super applicationSuspend:event];
9537 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9538 if ([self isSafeToSuspend])
9539 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9542 - (void) _setSuspended:(BOOL)value {
9543 if ([self isSafeToSuspend])
9544 [super _setSuspended:value];
9547 - (UIProgressHUD *) addProgressHUD {
9548 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9549 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9551 [window_ setUserInteractionEnabled:NO];
9553 UIViewController *target(tabbar_);
9554 if (UIViewController *modal = [target modalViewController])
9557 UIView *view([target view]);
9558 [view addSubview:hud];
9566 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9569 [hud removeFromSuperview];
9570 [window_ setUserInteractionEnabled:YES];
9573 - (CYViewController *) pageForPackage:(NSString *)name {
9574 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9577 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9578 NSString *scheme([[url scheme] lowercaseString]);
9579 if ([[url absoluteString] length] <= [scheme length] + 3)
9581 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9582 NSArray *components([path pathComponents]);
9584 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9585 return [self pageForPackage:[components objectAtIndex:1]];
9587 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9590 NSString *base([components objectAtIndex:0]);
9592 CYViewController *controller = nil;
9594 if ([base isEqualToString:@"url"]) {
9595 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9596 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9597 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9598 } else if (!external && [components count] == 1) {
9599 if ([base isEqualToString:@"manage"]) {
9600 controller = [[[ManageController alloc] init] autorelease];
9603 if ([base isEqualToString:@"sources"]) {
9604 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9607 if ([base isEqualToString:@"home"]) {
9608 controller = [[[HomeController alloc] init] autorelease];
9611 if ([base isEqualToString:@"sections"]) {
9612 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9615 if ([base isEqualToString:@"search"]) {
9616 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9619 if ([base isEqualToString:@"changes"]) {
9620 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9623 if ([base isEqualToString:@"installed"]) {
9624 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9626 } else if ([components count] == 2) {
9627 NSString *argument = [components objectAtIndex:1];
9629 if ([base isEqualToString:@"package"]) {
9630 controller = [self pageForPackage:argument];
9633 if (!external && [base isEqualToString:@"search"]) {
9634 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9635 [(SearchController *)controller setSearchTerm:argument];
9638 if (!external && [base isEqualToString:@"sections"]) {
9639 if ([argument isEqualToString:@"all"])
9641 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9644 if (!external && [base isEqualToString:@"sources"]) {
9645 if ([argument isEqualToString:@"add"]) {
9646 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9647 [(SourcesController *)controller showAddSourcePrompt];
9649 Source *source = [database_ sourceWithKey:argument];
9650 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9654 if (!external && [base isEqualToString:@"launch"]) {
9655 [self launchApplicationWithIdentifier:argument suspended:NO];
9658 } else if (!external && [components count] == 3) {
9659 NSString *arg1 = [components objectAtIndex:1];
9660 NSString *arg2 = [components objectAtIndex:2];
9662 if ([base isEqualToString:@"package"]) {
9663 if ([arg2 isEqualToString:@"settings"]) {
9664 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9665 } else if ([arg2 isEqualToString:@"files"]) {
9666 if (Package *package = [database_ packageWithName:arg1]) {
9667 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9668 [(FileTable *)controller setPackage:package];
9674 [controller setDelegate:self];
9678 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9679 CYViewController *page([self pageForURL:url forExternal:external]);
9682 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9683 [nav setViewControllers:[NSArray arrayWithObject:page]];
9684 [tabbar_ setUnselectedViewController:nav];
9690 - (void) applicationOpenURL:(NSURL *)url {
9691 [super applicationOpenURL:url];
9693 if (!loaded_) starturl_ = [url retain];
9694 else [self openCydiaURL:url forExternal:YES];
9697 - (void) applicationWillResignActive:(UIApplication *)application {
9698 // Stop refreshing if you get a phone call or lock the device.
9699 if ([tabbar_ updating])
9700 [tabbar_ cancelUpdate];
9702 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9703 [super applicationWillResignActive:application];
9706 - (void) applicationWillTerminate:(UIApplication *)application {
9708 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9709 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9710 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9715 - (void) setConfigurationData:(NSString *)data {
9716 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9718 if (!conffile_r(data)) {
9719 lprintf("E:invalid conffile\n");
9723 NSString *ofile = conffile_r[1];
9724 //NSString *nfile = conffile_r[2];
9726 UIAlertView *alert = [[[UIAlertView alloc]
9727 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9728 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9730 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9732 UCLocalize("ACCEPT_NEW_COPY"),
9733 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9737 [alert setContext:@"conffile"];
9738 [alert setNumberOfRows:2];
9742 - (void) addStashController {
9744 stash_ = [[StashController alloc] init];
9745 [window_ addSubview:[stash_ view]];
9748 - (void) removeStashController {
9749 [[stash_ view] removeFromSuperview];
9755 [self setIdleTimerDisabled:YES];
9757 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9758 UpdateExternalStatus(1);
9759 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9760 UpdateExternalStatus(0);
9762 [self removeStashController];
9764 if (ExecFork() == 0) {
9765 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9766 perror("launchctl stop");
9770 - (void) setupViewControllers {
9771 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9773 NSMutableArray *items([NSMutableArray arrayWithObjects:
9774 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9775 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9776 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9777 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9781 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9782 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9784 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9787 NSMutableArray *controllers([NSMutableArray array]);
9788 for (UITabBarItem *item in items) {
9789 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9790 [controller setTabBarItem:item];
9791 [controllers addObject:controller];
9793 [tabbar_ setViewControllers:controllers];
9795 [tabbar_ setUpdateDelegate:self];
9798 - (void) applicationDidFinishLaunching:(id)unused {
9800 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9801 [self setApplicationSupportsShakeToEdit:NO];
9803 @synchronized (HostConfig_) {
9804 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9807 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9808 initWithMemoryCapacity:524288
9809 diskCapacity:10485760
9810 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9813 [CYBrowserController _initialize];
9815 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9817 Font12_ = [[UIFont systemFontOfSize:12] retain];
9818 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9819 Font14_ = [[UIFont systemFontOfSize:14] retain];
9820 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9821 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9823 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9824 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9826 // XXX: I really need this thing... like, seriously... I'm sorry
9827 [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9829 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9830 [window_ orderFront:self];
9831 [window_ makeKey:self];
9832 [window_ setHidden:NO];
9835 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9836 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9837 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9838 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9839 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9840 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9841 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9842 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9843 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9846 [self addStashController];
9847 // XXX: this would be much cleaner as a yieldToSelector:
9848 // that way the removeStashController could happen right here inline
9849 // we also could no longer require the useless stash_ field anymore
9850 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9854 database_ = [Database sharedInstance];
9855 [database_ setDelegate:self];
9857 [window_ setUserInteractionEnabled:NO];
9858 [self setupViewControllers];
9860 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9861 [window_ addSubview:[emulated_ view]];
9863 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9867 - (NSArray *) defaultStartPages {
9868 NSMutableArray *standard = [NSMutableArray array];
9869 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9870 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9871 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9873 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9875 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9876 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9878 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9885 [window_ setUserInteractionEnabled:YES];
9886 [self showSettings];
9889 if ([emulated_ modalViewController] != nil)
9890 [emulated_ dismissModalViewControllerAnimated:YES];
9891 [window_ setUserInteractionEnabled:NO];
9899 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9900 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9901 int standardIndex = 0;
9902 NSArray *standard = [self defaultStartPages];
9909 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9910 if (valid && closed != nil) {
9911 NSTimeInterval interval([closed timeIntervalSinceNow]);
9912 // XXX: Is 15 minutes the optimal time here?
9913 if (interval > 0 && interval <= -(15*60))
9917 if (valid && [saved count] != [standard count])
9921 for (unsigned int i = 0; i < [standard count]; i++) {
9922 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9923 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9924 // but it's good enough for now.
9925 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9932 NSArray *items = nil;
9934 [tabbar_ setSelectedIndex:savedIndex];
9937 [tabbar_ setSelectedIndex:standardIndex];
9941 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9942 NSArray *stack = [items objectAtIndex:tab];
9943 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9944 NSMutableArray *current = [NSMutableArray array];
9946 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9947 NSString *addr = [stack objectAtIndex:nav];
9948 NSURL *url = [NSURL URLWithString:addr];
9949 CYViewController *page = [self pageForURL:url forExternal:NO];
9951 [current addObject:page];
9954 [navigation setViewControllers:current];
9957 // (Try to) show the startup URL.
9958 if (starturl_ != nil) {
9959 [self openCydiaURL:starturl_ forExternal:NO];
9960 [starturl_ release];
9965 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9966 if (item != nil && IsWildcat_) {
9967 [sheet showFromBarButtonItem:item animated:YES];
9969 [sheet showInView:window_];
9973 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9974 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9975 [progress setTitle:task];
9976 [progress addProgressEvent:event];
9979 - (void) addProgressEventForTask:(NSArray *)data {
9980 CydiaProgressEvent *event([data objectAtIndex:0]);
9981 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9982 [self addProgressEvent:event forTask:task];
9985 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9986 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9992 id Alloc_(id self, SEL selector) {
9993 id object = alloc_(self, selector);
9994 lprintf("[%s]A-%p\n", self->isa->name, object);
9999 id Dealloc_(id self, SEL selector) {
10000 id object = dealloc_(self, selector);
10001 lprintf("[%s]D-%p\n", self->isa->name, object);
10005 Class $WebDefaultUIKitDelegate;
10007 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
10008 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
10009 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
10010 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
10013 static NSSet *MobilizedFiles_;
10015 static NSURL *MobilizeURL(NSURL *url) {
10016 NSString *path([url path]);
10017 if ([path hasPrefix:@"/var/root/"]) {
10018 NSString *file([path substringFromIndex:10]);
10019 if ([MobilizedFiles_ containsObject:file])
10020 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10026 Class $CFXPreferencesPropertyListSource;
10027 @class CFXPreferencesPropertyListSource;
10029 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10030 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10031 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10032 url = MobilizeURL(url);
10033 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
10034 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
10040 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10041 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10042 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10043 url = MobilizeURL(url);
10044 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10045 //NSLog(@"%@ %@", [url absoluteString], value);
10051 Class $NSURLConnection;
10053 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10054 NSMutableURLRequest *copy([request mutableCopy]);
10056 NSURL *url([copy URL]);
10057 NSString *host([url host]);
10058 NSString *scheme([[url scheme] lowercaseString]);
10060 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10062 @synchronized (HostConfig_) {
10063 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10064 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10065 [copy setHTTPShouldUsePipelining:YES];
10068 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10072 int main(int argc, char *argv[]) { _pooled
10075 UpdateExternalStatus(0);
10077 if (Class $UIDevice = objc_getClass("UIDevice")) {
10078 UIDevice *device([$UIDevice currentDevice]);
10079 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10081 IsWildcat_ = false;
10083 UIScreen *screen([UIScreen mainScreen]);
10084 if ([screen respondsToSelector:@selector(scale)])
10085 ScreenScale_ = [screen scale];
10089 UIDevice *device([UIDevice currentDevice]);
10090 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10091 Idiom_ = @"iphone";
10093 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10094 if (idiom == UIUserInterfaceIdiomPhone)
10095 Idiom_ = @"iphone";
10096 else if (idiom == UIUserInterfaceIdiomPad)
10099 NSLog(@"unknown UIUserInterfaceIdiom!");
10102 SessionData_ = [[NSMutableDictionary alloc] initWithCapacity:4];
10104 HostConfig_ = [[NSObject alloc] init];
10105 @synchronized (HostConfig_) {
10106 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10107 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10110 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
10112 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10114 MobilizedFiles_ = [NSMutableSet setWithObjects:
10115 @"Library/Preferences/com.apple.Accessibility.plist",
10116 @"Library/Preferences/com.apple.preferences.sounds.plist",
10119 /* Library Hacks {{{ */
10120 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10122 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10124 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10125 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10126 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10127 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10130 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10131 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10132 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10133 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10136 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10137 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10138 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10139 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10140 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10143 $NSURLConnection = objc_getClass("NSURLConnection");
10144 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10145 if (NSURLConnection$init$ != NULL) {
10146 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10147 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10150 /* Set Locale {{{ */
10151 Locale_ = CFLocaleCopyCurrent();
10152 Languages_ = [NSLocale preferredLanguages];
10154 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10155 //NSLog(@"%@", [Languages_ description]);
10158 if (Locale_ != NULL)
10159 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10160 else if (Languages_ != nil && [Languages_ count] != 0)
10161 lang = [[Languages_ objectAtIndex:0] UTF8String];
10163 // XXX: consider just setting to C and then falling through?
10166 if (lang != NULL) {
10167 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10168 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10171 NSLog(@"Setting Language: %s", lang);
10173 if (lang != NULL) {
10174 setenv("LANG", lang, true);
10175 std::setlocale(LC_ALL, lang);
10179 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10181 /* Parse Arguments {{{ */
10182 bool substrate(false);
10188 for (int argi(1); argi != argc; ++argi)
10189 if (strcmp(argv[argi], "--") == 0) {
10191 argv[argi] = argv[0];
10197 for (int argi(1); argi != arge; ++argi)
10198 if (strcmp(args[argi], "--substrate") == 0)
10201 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10205 App_ = [[NSBundle mainBundle] bundlePath];
10211 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10212 alloc_ = alloc->method_imp;
10213 alloc->method_imp = (IMP) &Alloc_;*/
10215 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10216 dealloc_ = dealloc->method_imp;
10217 dealloc->method_imp = (IMP) &Dealloc_;*/
10219 /* System Information {{{ */
10223 size = sizeof(maxproc);
10224 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10225 perror("sysctlbyname(\"kern.maxproc\", ?)");
10226 else if (maxproc < 64) {
10228 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10229 perror("sysctlbyname(\"kern.maxproc\", #)");
10232 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10233 char *osversion = new char[size];
10234 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10235 perror("sysctlbyname(\"kern.osversion\", ?)");
10237 System_ = [NSString stringWithUTF8String:osversion];
10239 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10240 char *machine = new char[size];
10241 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10242 perror("sysctlbyname(\"hw.machine\", ?)");
10244 Machine_ = machine;
10246 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
10247 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
10248 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
10249 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
10253 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
10254 NSData *data((NSData *) ecid);
10255 size_t length([data length]);
10256 uint8_t bytes[length];
10257 [data getBytes:bytes];
10258 char string[length * 2 + 1];
10259 for (size_t i(0); i != length; ++i)
10260 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
10261 ChipID_ = [NSString stringWithUTF8String:string];
10265 IOObjectRelease(service);
10269 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
10271 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10272 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10273 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10275 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10276 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10277 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10279 if (mcc != NULL && mnc != NULL)
10280 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10287 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10288 Build_ = [system objectForKey:@"ProductBuildVersion"];
10289 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10290 Product_ = [info objectForKey:@"SafariProductVersion"];
10291 Safari_ = [info objectForKey:@"CFBundleVersion"];
10294 /* Load Database {{{ */
10296 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10298 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10300 if (Metadata_ == NULL)
10301 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10303 Settings_ = [Metadata_ objectForKey:@"Settings"];
10305 Packages_ = [Metadata_ objectForKey:@"Packages"];
10306 Sections_ = [Metadata_ objectForKey:@"Sections"];
10307 Sources_ = [Metadata_ objectForKey:@"Sources"];
10309 Token_ = [Metadata_ objectForKey:@"Token"];
10312 if (Settings_ != nil)
10313 Role_ = [Settings_ objectForKey:@"Role"];
10315 if (Sections_ == nil) {
10316 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10317 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10320 if (Sources_ == nil) {
10321 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10322 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10327 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10330 if (Packages_ != nil) {
10332 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10336 [Metadata_ removeObjectForKey:@"Packages"];
10342 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10344 #define MobileSubstrate_(name) \
10345 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10346 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10347 if (handle == NULL) \
10348 NSLog(@"%s", dlerror()); \
10351 MobileSubstrate_(Activator)
10352 MobileSubstrate_(libstatusbar)
10353 MobileSubstrate_(SimulatedKeyEvents)
10354 MobileSubstrate_(WinterBoard)
10356 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10357 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10359 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10361 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10362 unlink("/tmp/.cydia.fw");
10364 } else if (access("/User", F_OK) != 0 || version < 4) {
10367 system("/usr/libexec/cydia/firmware.sh");
10371 _assert([[NSFileManager defaultManager]
10372 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10373 withIntermediateDirectories:YES
10378 if (access("/tmp/cydia.chk", F_OK) == 0) {
10379 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10380 _assert(errno == ENOENT);
10381 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10382 _assert(errno == ENOENT);
10385 /* APT Initialization {{{ */
10386 _assert(pkgInitConfig(*_config));
10387 _assert(pkgInitSystem(*_config, _system));
10390 _config->Set("APT::Acquire::Translation", lang);
10392 // XXX: this timeout might be important :(
10393 //_config->Set("Acquire::http::Timeout", 15);
10395 _config->Set("Acquire::http::MaxParallel", 3);
10397 /* Color Choices {{{ */
10398 space_ = CGColorSpaceCreateDeviceRGB();
10400 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10401 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10402 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10403 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10404 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10405 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10406 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10407 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10408 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10410 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10411 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10413 /* UIKit Configuration {{{ */
10414 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10415 if ($GSFontSetUseLegacyFontMetrics != NULL)
10416 $GSFontSetUseLegacyFontMetrics(YES);
10418 // XXX: I have a feeling this was important
10419 //UIKeyboardDisableAutomaticAppearance();
10422 Colon_ = UCLocalize("COLON_DELIMITED");
10423 Elision_ = UCLocalize("ELISION");
10424 Error_ = UCLocalize("ERROR");
10425 Warning_ = UCLocalize("WARNING");
10428 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10430 CGColorSpaceRelease(space_);
10431 CFRelease(Locale_);