1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "UICaboodle/UCPlatform.h"
45 #include "UICaboodle/UCLocalize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
105 #include <sys/reboot.h>
112 #include <mach-o/nlist.h>
122 #include <Cytore.hpp>
124 #include "UICaboodle/BrowserView.h"
125 #include "SDURLCache/SDURLCache.h"
127 #include "substrate.h"
134 #define _timestamp ({ \
136 gettimeofday(&tv, NULL); \
137 tv.tv_sec * 1000000 + tv.tv_usec; \
140 typedef std::vector<class ProfileTime *> TimeList;
150 ProfileTime(const char *name) :
154 times_.push_back(this);
157 void AddTime(uint64_t time) {
164 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
176 ProfileTimer(ProfileTime &time) :
183 time_.AddTime(_timestamp - start_);
188 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
190 std::cerr << "========" << std::endl;
193 #define _profile(name) { \
194 static ProfileTime name(#name); \
195 ProfileTimer _ ## name(name);
200 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
202 #define CYPoolStart() \
203 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
205 #define CYPoolEnd() \
209 #define Cydia_ CYDIA_VERSION
211 #define lprintf(args...) fprintf(stderr, args)
214 #define TraceLogging (1 && !ForRelease)
215 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
216 #define ProfileTimes (0 && !ForRelease)
217 #define ForSaurik (0 && !ForRelease)
218 #define LogBrowser (0 && !ForRelease)
219 #define TrackResize (0 && !ForRelease)
220 #define ManualRefresh (1 && !ForRelease)
221 #define ShowInternals (0 && !ForRelease)
222 #define AlwaysReload (0 && !ForRelease)
223 #define TryIndexedCollation (0 && !ForRelease)
227 #define _trace(args...)
232 #define _profile(name) {
235 #define PrintTimes() do {} while (false)
238 // Hash Functions/Structures {{{
239 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
247 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
249 static _finline NSString *CydiaURL(NSString *path) {
251 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
252 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
253 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
254 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
255 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
257 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
260 static _finline void UpdateExternalStatus(uint64_t newStatus) {
262 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
263 notify_set_state(notify_token, newStatus);
264 notify_cancel(notify_token);
266 notify_post("com.saurik.Cydia.status");
269 /* [NSObject yieldToSelector:(withObject:)] {{{*/
270 @interface NSObject (Cydia)
271 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
272 - (id) yieldToSelector:(SEL)selector;
275 @implementation NSObject (Cydia)
280 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
281 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
282 id object([[context objectAtIndex:1] nonretainedObjectValue]);
283 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
285 /* XXX: deal with exceptions */
286 id value([self performSelector:selector withObject:object]);
288 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
289 [context removeAllObjects];
290 if ([signature methodReturnLength] != 0 && value != nil)
291 [context addObject:value];
296 performSelectorOnMainThread:@selector(doNothing)
302 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
303 volatile bool stopped(false);
305 NSMutableArray *context([NSMutableArray arrayWithObjects:
306 [NSValue valueWithPointer:selector],
307 [NSValue valueWithNonretainedObject:object],
308 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
311 NSThread *thread([[[NSThread alloc]
313 selector:@selector(_yieldToContext:)
319 NSRunLoop *loop([NSRunLoop currentRunLoop]);
320 NSDate *future([NSDate distantFuture]);
321 NSString *mode([loop currentMode] ?: NSDefaultRunLoopMode);
324 while (!stopped && [loop runMode:mode beforeDate:future]);
327 return [context count] == 0 ? nil : [context objectAtIndex:0];
330 - (id) yieldToSelector:(SEL)selector {
331 return [self yieldToSelector:selector withObject:nil];
337 /* Cydia Alert View {{{ */
338 @interface CYAlertView : UIAlertView {
342 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
346 @implementation CYAlertView
348 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
349 if ((self = [super init]) != nil) {
350 [self setTitle:title];
351 [self setDelegate:self];
352 for (NSString *button in buttons) [self addButtonWithTitle:button];
353 [self setCancelButtonIndex:index];
357 - (void) _updateFrameForDisplay {
358 [super _updateFrameForDisplay];
359 if ([self cancelButtonIndex] == -1) {
360 NSArray *buttons = [self buttons];
361 if ([buttons count]) {
362 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
363 for (UIThreePartButton *button in buttons)
364 [button setBackground:background forState:0];
369 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
370 button_ = buttonIndex + 1;
374 [self dismissWithClickedButtonIndex:-1 animated:YES];
377 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
378 [self setRunsModal:YES];
387 /* NSForcedOrderingSearch doesn't work on the iPhone */
388 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
389 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
390 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
393 typedef uint32_t (*SKRadixFunction)(id, void *);
395 @interface NSMutableArray (Radix)
396 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
404 @implementation NSMutableArray (Radix)
406 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
407 size_t count([self count]);
408 struct RadixItem_ *swap(new RadixItem_[count * 2]);
410 for (size_t i(0); i != count; ++i) {
411 RadixItem_ &item(swap[i]);
414 id object([self objectAtIndex:i]);
415 item.key = function(object, argument);
418 struct RadixItem_ *lhs(swap), *rhs(swap + count);
420 static const size_t width = 32;
421 static const size_t bits = 11;
422 static const size_t slots = 1 << bits;
423 static const size_t passes = (width + (bits - 1)) / bits;
425 size_t *hist(new size_t[slots]);
427 for (size_t pass(0); pass != passes; ++pass) {
428 memset(hist, 0, sizeof(size_t) * slots);
430 for (size_t i(0); i != count; ++i) {
431 uint32_t key(lhs[i].key);
433 key &= _not(uint32_t) >> width - bits;
438 for (size_t i(0); i != slots; ++i) {
439 size_t local(offset);
444 for (size_t i(0); i != count; ++i) {
445 uint32_t key(lhs[i].key);
447 key &= _not(uint32_t) >> width - bits;
448 rhs[hist[key]++] = lhs[i];
451 RadixItem_ *tmp(lhs);
458 const void **values(new const void *[count]);
459 for (size_t i(0); i != count; ++i)
460 values[i] = [self objectAtIndex:lhs[i].index];
461 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
469 /* Insertion Sort {{{ */
471 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
472 const char *ptr = (const char *)list;
474 CFIndex half = count / 2;
475 const char *probe = ptr + elementSize * half;
476 CFComparisonResult cr = comparator(element, probe, context);
477 if (0 == cr) return (probe - (const char *)list) / elementSize;
478 ptr = (cr < 0) ? ptr : probe + elementSize;
479 count = (cr < 0) ? half : (half + (count & 1) - 1);
481 return (ptr - (const char *)list) / elementSize;
484 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
485 const char *ptr = (const char *)list;
487 CFIndex half = count / 2;
488 const char *probe = ptr + elementSize * half;
489 CFComparisonResult cr = comparator(element, probe, context);
490 if (0 == cr) return (probe - (const char *)list) / elementSize;
491 ptr = (cr < 0) ? ptr : probe + elementSize;
492 count = (cr < 0) ? half : (half + (count & 1) - 1);
494 return (ptr - (const char *)list) / elementSize;
497 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
498 if (range.length == 0)
500 const void **values(new const void *[range.length]);
501 CFArrayGetValues(array, range, values);
503 #if HistogramInsertionSort > 0
504 uint32_t total(0), *offsets(new uint32_t[range.length]);
507 for (CFIndex index(1); index != range.length; ++index) {
508 const void *value(values[index]);
509 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
510 CFIndex correct(index);
511 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
512 #if HistogramInsertionSort > 1
513 NSLog(@"%@ < %@", value, values[correct - 1]);
518 if (correct != index) {
519 size_t offset(index - correct);
520 #if HistogramInsertionSort
524 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
526 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
527 values[correct] = value;
531 CFArrayReplaceValues(array, range, values, range.length);
534 #if HistogramInsertionSort > 0
535 for (CFIndex index(0); index != range.length; ++index)
536 if (offsets[index] != 0)
537 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
538 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
545 /* Apple Bug Fixes {{{ */
546 @implementation UIWebDocumentView (Cydia)
548 - (void) _setScrollerOffset:(CGPoint)offset {
549 UIScroller *scroller([self _scroller]);
551 CGSize size([scroller contentSize]);
552 CGSize bounds([scroller bounds].size);
555 max.x = size.width - bounds.width;
556 max.y = size.height - bounds.height;
564 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
565 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
567 [scroller setOffset:offset];
573 @interface NSInvocation (Cydia)
574 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target;
577 @implementation NSInvocation (Cydia)
579 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target {
580 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[target methodSignatureForSelector:selector]]);
581 [invocation setTarget:target];
582 [invocation setSelector:selector];
588 @implementation WebScriptObject (NSFastEnumeration)
590 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
591 size_t length([self count] - state->state);
594 else if (length > count)
596 for (size_t i(0); i != length; ++i)
597 objects[i] = [self objectAtIndex:state->state++];
598 state->itemsPtr = objects;
599 state->mutationsPtr = (unsigned long *) self;
605 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
606 size_t length([self length] - state->state);
609 else if (length > count)
611 for (size_t i(0); i != length; ++i)
612 objects[i] = [self item:state->state++];
613 state->itemsPtr = objects;
614 state->mutationsPtr = (unsigned long *) self;
618 /* Cydia NSString Additions {{{ */
619 @interface NSString (Cydia)
620 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
621 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
622 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
623 - (NSComparisonResult) compareByPath:(NSString *)other;
624 - (NSString *) stringByCachingURLWithCurrentCDN;
625 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
628 @implementation NSString (Cydia)
630 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
631 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
634 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
635 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
636 memcpy(data, bytes, length);
637 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
640 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
641 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
644 - (NSComparisonResult) compareByPath:(NSString *)other {
645 NSString *prefix = [self commonPrefixWithString:other options:0];
646 size_t length = [prefix length];
648 NSRange lrange = NSMakeRange(length, [self length] - length);
649 NSRange rrange = NSMakeRange(length, [other length] - length);
651 lrange = [self rangeOfString:@"/" options:0 range:lrange];
652 rrange = [other rangeOfString:@"/" options:0 range:rrange];
654 NSComparisonResult value;
656 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
657 value = NSOrderedSame;
658 else if (lrange.location == NSNotFound)
659 value = NSOrderedAscending;
660 else if (rrange.location == NSNotFound)
661 value = NSOrderedDescending;
663 value = NSOrderedSame;
665 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
666 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
667 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
668 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
670 NSComparisonResult result = [lpath compare:rpath];
671 return result == NSOrderedSame ? value : result;
674 - (NSString *) stringByCachingURLWithCurrentCDN {
676 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
677 withString:@"://cache.cydia.saurik.com/"
681 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
682 return [(id)CFURLCreateStringByAddingPercentEscapes(
687 kCFStringEncodingUTF8
694 /* C++ NSString Wrapper Cache {{{ */
695 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
696 return size == 0 ? NULL :
697 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
698 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
701 static _finline CFStringRef CYStringCreate(const char *data) {
702 return CYStringCreate(data, strlen(data));
711 _finline void clear_() {
712 if (cache_ != NULL) {
719 _finline bool empty() const {
723 _finline size_t size() const {
727 _finline char *data() const {
731 _finline void clear() {
736 _finline CYString() :
743 _finline ~CYString() {
747 void operator =(const CYString &rhs) {
751 if (rhs.cache_ == nil)
754 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
757 void copy(apr_pool_t *pool) {
758 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
759 memcpy(temp, data_, size_);
764 void set(apr_pool_t *pool, const char *data, size_t size) {
770 data_ = const_cast<char *>(data);
778 _finline void set(apr_pool_t *pool, const char *data) {
779 set(pool, data, data == NULL ? 0 : strlen(data));
782 _finline void set(apr_pool_t *pool, const std::string &rhs) {
783 set(pool, rhs.data(), rhs.size());
786 bool operator ==(const CYString &rhs) const {
787 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
790 _finline operator CFStringRef() {
792 cache_ = CYStringCreate(data_, size_);
796 _finline operator id() {
797 return (NSString *) static_cast<CFStringRef>(*this);
800 _finline operator const char *() {
801 return reinterpret_cast<const char *>(data_);
805 /* C++ NSString Algorithm Adapters {{{ */
807 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
810 struct NSStringMapHash :
811 std::unary_function<NSString *, size_t>
813 _finline size_t operator ()(NSString *value) const {
814 return CFStringHashNSString((CFStringRef) value);
818 struct NSStringMapLess :
819 std::binary_function<NSString *, NSString *, bool>
821 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
822 return [lhs compare:rhs] == NSOrderedAscending;
826 struct NSStringMapEqual :
827 std::binary_function<NSString *, NSString *, bool>
829 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
830 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
831 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
832 //[lhs isEqualToString:rhs];
837 /* Perl-Compatible RegEx {{{ */
853 Pcre(const char *regex) :
857 this->operator =(regex);
860 void operator =(const char *regex) {
861 _assert(code_ == NULL);
865 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
868 lprintf("%d:%s\n", offset, error);
872 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
873 matches_ = new int[(capture_ + 1) * 3];
881 NSString *operator [](size_t match) {
882 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
885 bool operator ()(NSString *data) {
886 // XXX: length is for characters, not for bytes
887 return operator ()([data UTF8String], [data length]);
890 bool operator ()(const char *data, size_t size) {
892 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
895 _finline size_t size() const {
900 /* Mime Addresses {{{ */
901 @interface Address : NSObject {
907 - (NSString *) address;
909 - (void) setAddress:(NSString *)address;
911 + (Address *) addressWithString:(NSString *)string;
912 - (Address *) initWithString:(NSString *)string;
916 @implementation Address
925 - (NSString *) name {
929 - (NSString *) address {
933 - (void) setAddress:(NSString *)address {
935 [address_ autorelease];
939 address_ = [address retain];
942 + (Address *) addressWithString:(NSString *)string {
943 return [[[Address alloc] initWithString:string] autorelease];
946 + (NSArray *) _attributeKeys {
947 return [NSArray arrayWithObjects:
953 - (NSArray *) attributeKeys {
954 return [[self class] _attributeKeys];
957 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
958 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
961 - (Address *) initWithString:(NSString *)string {
962 if ((self = [super init]) != nil) {
963 const char *data = [string UTF8String];
964 size_t size = [string length];
966 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
968 if (address_r(data, size)) {
969 name_ = [address_r[1] retain];
970 address_ = [address_r[2] retain];
972 name_ = [string retain];
980 /* CoreGraphics Primitives {{{ */
985 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
986 CGFloat color[] = {red, green, blue, alpha};
987 return CGColorCreate(space, color);
996 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
997 color_(Create_(space, red, green, blue, alpha))
999 Set(space, red, green, blue, alpha);
1004 CGColorRelease(color_);
1011 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1013 color_ = Create_(space, red, green, blue, alpha);
1016 operator CGColorRef() {
1022 /* Random Global Variables {{{ */
1023 static const int PulseInterval_ = 50000;
1025 static const NSString *UI_;
1028 static bool RestartSubstrate_;
1029 static NSArray *Finishes_;
1031 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1032 #define NotifyConfig_ "/etc/notify.conf"
1034 static bool Queuing_;
1036 static CYColor Blue_;
1037 static CYColor Blueish_;
1038 static CYColor Black_;
1039 static CYColor Off_;
1040 static CYColor White_;
1041 static CYColor Gray_;
1042 static CYColor Green_;
1043 static CYColor Purple_;
1044 static CYColor Purplish_;
1046 static UIColor *InstallingColor_;
1047 static UIColor *RemovingColor_;
1049 static NSString *App_;
1051 static BOOL Advanced_;
1052 static BOOL Ignored_;
1054 static UIFont *Font12_;
1055 static UIFont *Font12Bold_;
1056 static UIFont *Font14_;
1057 static UIFont *Font18Bold_;
1058 static UIFont *Font22Bold_;
1060 static const char *Machine_ = NULL;
1061 static NSString *System_ = nil;
1062 static NSString *SerialNumber_ = nil;
1063 static NSString *ChipID_ = nil;
1064 static _H<NSString> Token_;
1065 static NSString *UniqueID_ = nil;
1066 static NSString *PLMN_ = nil;
1067 static NSString *Build_ = nil;
1068 static NSString *Product_ = nil;
1069 static NSString *Safari_ = nil;
1071 static CFLocaleRef Locale_;
1072 static NSArray *Languages_;
1073 static CGColorSpaceRef space_;
1075 static NSDictionary *SectionMap_;
1076 static NSMutableDictionary *Metadata_;
1077 static _transient NSMutableDictionary *Settings_;
1078 static _transient NSString *Role_;
1079 static _transient NSMutableDictionary *Packages_;
1080 static _transient NSMutableDictionary *Sections_;
1081 static _transient NSMutableDictionary *Sources_;
1082 static bool Changed_;
1086 static CGFloat ScreenScale_;
1087 static NSString *Idiom_;
1089 static NSObject *HostConfig_;
1090 static NSMutableSet *BridgedHosts_;
1091 static NSMutableSet *PipelinedHosts_;
1093 static NSString *kCydiaProgressEventTypeError = @"Error";
1094 static NSString *kCydiaProgressEventTypeInformation = @"Information";
1095 static NSString *kCydiaProgressEventTypeStatus = @"Status";
1096 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
1099 /* Display Helpers {{{ */
1100 inline float Interpolate(float begin, float end, float fraction) {
1101 return (end - begin) * fraction + begin;
1104 static _finline const char *StripVersion_(const char *version) {
1105 const char *colon(strchr(version, ':'));
1106 return colon == NULL ? version : colon + 1;
1109 NSString *LocalizeSection(NSString *section) {
1110 static Pcre title_r("^(.*?) \\((.*)\\)$");
1111 if (title_r(section)) {
1112 NSString *parent(title_r[1]);
1113 NSString *child(title_r[2]);
1115 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1116 LocalizeSection(parent),
1117 LocalizeSection(child)
1121 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1124 NSString *Simplify(NSString *title) {
1125 const char *data = [title UTF8String];
1126 size_t size = [title length];
1128 static Pcre square_r("^\\[(.*)\\]$");
1129 if (square_r(data, size))
1130 return Simplify(square_r[1]);
1132 static Pcre paren_r("^\\((.*)\\)$");
1133 if (paren_r(data, size))
1134 return Simplify(paren_r[1]);
1136 static Pcre title_r("^(.*?) \\((.*)\\)$");
1137 if (title_r(data, size))
1138 return Simplify(title_r[1]);
1144 NSString *GetLastUpdate() {
1145 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1148 return UCLocalize("NEVER_OR_UNKNOWN");
1150 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1151 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1153 CFRelease(formatter);
1155 return [(NSString *) formatted autorelease];
1158 bool isSectionVisible(NSString *section) {
1159 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1160 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1161 return hidden == nil || ![hidden boolValue];
1166 /* Delegate Prototypes {{{ */
1169 @class CydiaProgressEvent;
1171 @protocol DatabaseDelegate
1172 - (void) repairWithSelector:(SEL)selector;
1173 - (void) setConfigurationData:(NSString *)data;
1174 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
1177 @class CYPackageController;
1179 @protocol CydiaDelegate
1180 - (void) retainNetworkActivityIndicator;
1181 - (void) releaseNetworkActivityIndicator;
1182 - (void) clearPackage:(Package *)package;
1183 - (void) installPackage:(Package *)package;
1184 - (void) installPackages:(NSArray *)packages;
1185 - (void) removePackage:(Package *)package;
1186 - (void) beginUpdate;
1188 - (void) distUpgrade;
1190 - (void) updateData;
1192 - (void) addTrivialSource:(NSString *)href;
1193 - (void) showSettings;
1194 - (UIProgressHUD *) addProgressHUD;
1195 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1196 - (CYViewController *) pageForPackage:(NSString *)name;
1197 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1198 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1202 /* ProgressEvent Interface/Delegate {{{ */
1203 @interface CydiaProgressEvent : NSObject {
1204 _H<NSString> message_;
1208 _H<NSString> package_;
1210 _H<NSString> version_;
1213 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type;
1214 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package;
1215 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item;
1217 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type;
1219 - (NSString *) message;
1220 - (NSString *) type;
1223 - (NSString *) package;
1225 - (NSString *) version;
1227 - (void) setItem:(NSArray *)item;
1228 - (void) setPackage:(NSString *)package;
1229 - (void) setURL:(NSString *)url;
1230 - (void) setVersion:(NSString *)version;
1232 - (NSString *) compound:(NSString *)value;
1233 - (NSString *) compoundMessage;
1234 - (NSString *) compoundTitle;
1238 @protocol ProgressDelegate
1239 - (void) addProgressEvent:(CydiaProgressEvent *)event;
1240 - (void) setProgressPercent:(NSNumber *)percent;
1241 - (void) setProgressStatus:(NSDictionary *)status;
1242 - (void) setProgressCancellable:(NSNumber *)cancellable;
1243 - (bool) isProgressCancelled;
1244 - (void) setTitle:(NSString *)title;
1247 /* Status Delegation {{{ */
1249 public pkgAcquireStatus
1252 _transient NSObject<ProgressDelegate> *delegate_;
1262 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1263 delegate_ = delegate;
1266 NSObject<ProgressDelegate> *getDelegate() const {
1270 virtual bool MediaChange(std::string media, std::string drive) {
1274 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1277 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1278 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1279 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
1280 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1283 virtual void Done(pkgAcquire::ItemDesc &item) {
1286 virtual void Fail(pkgAcquire::ItemDesc &item) {
1288 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1289 item.Owner->Status == pkgAcquire::Item::StatDone
1293 std::string &error(item.Owner->ErrorText);
1297 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
1298 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1301 virtual bool Pulse(pkgAcquire *Owner) {
1302 bool value = pkgAcquireStatus::Pulse(Owner);
1305 double(CurrentBytes + CurrentItems) /
1306 double(TotalBytes + TotalItems)
1309 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1310 [NSNumber numberWithDouble:percent], @"Percent",
1312 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1313 [NSNumber numberWithDouble:TotalBytes], @"Total",
1314 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1315 nil] waitUntilDone:YES];
1317 if (value && ![delegate_ isProgressCancelled])
1325 _finline bool WasCancelled() const {
1329 virtual void Start() {
1330 pkgAcquireStatus::Start();
1331 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1334 virtual void Stop() {
1335 pkgAcquireStatus::Stop();
1336 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1337 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1341 /* Database Interface {{{ */
1342 typedef std::map< unsigned long, _H<Source> > SourceMap;
1344 @interface Database : NSObject {
1350 pkgCacheFile cache_;
1351 pkgDepCache::Policy *policy_;
1352 pkgRecords *records_;
1353 pkgProblemResolver *resolver_;
1354 pkgAcquire *fetcher_;
1356 SPtr<pkgPackageManager> manager_;
1357 pkgSourceList *list_;
1359 SourceMap sourceMap_;
1360 NSMutableArray *sourceList_;
1362 CFMutableArrayRef packages_;
1364 _transient NSObject<DatabaseDelegate> *delegate_;
1365 _transient NSObject<ProgressDelegate> *progress_;
1373 std::map<const char *, _H<NSString> > sections_;
1376 + (Database *) sharedInstance;
1379 - (void) _readCydia:(NSNumber *)fd;
1380 - (void) _readStatus:(NSNumber *)fd;
1381 - (void) _readOutput:(NSNumber *)fd;
1385 - (Package *) packageWithName:(NSString *)name;
1387 - (pkgCacheFile &) cache;
1388 - (pkgDepCache::Policy *) policy;
1389 - (pkgRecords *) records;
1390 - (pkgProblemResolver *) resolver;
1391 - (pkgAcquire &) fetcher;
1392 - (pkgSourceList &) list;
1393 - (NSArray *) packages;
1394 - (NSArray *) sources;
1395 - (Source *) sourceWithKey:(NSString *)key;
1396 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1404 - (void) updateWithStatus:(Status &)status;
1406 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1408 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1409 - (NSObject<ProgressDelegate> *) progressDelegate;
1411 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1413 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1417 /* ProgressEvent Implementation {{{ */
1418 @implementation CydiaProgressEvent
1420 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1421 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1424 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1425 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1426 [event setPackage:package];
1430 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1431 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1433 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1434 NSArray *fields([description componentsSeparatedByString:@" "]);
1435 [event setItem:fields];
1437 if ([fields count] > 3) {
1438 [event setPackage:[fields objectAtIndex:2]];
1439 [event setVersion:[fields objectAtIndex:3]];
1442 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1447 + (NSArray *) _attributeKeys {
1448 return [NSArray arrayWithObjects:
1458 - (NSArray *) attributeKeys {
1459 return [[self class] _attributeKeys];
1462 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1463 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1466 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1467 if ((self = [super init]) != nil) {
1473 - (NSString *) message {
1477 - (NSString *) type {
1481 - (NSArray *) item {
1482 return (id) item_ ?: [NSNull null];
1485 - (void) setItem:(NSArray *)item {
1489 - (NSString *) package {
1490 return (id) package_ ?: [NSNull null];
1493 - (void) setPackage:(NSString *)package {
1497 - (NSString *) url {
1498 return (id) url_ ?: [NSNull null];
1501 - (void) setURL:(NSString *)url {
1505 - (void) setVersion:(NSString *)version {
1509 - (NSString *) version {
1510 return (id) version_ ?: [NSNull null];
1513 - (NSString *) compound:(NSString *)value {
1515 NSString *mode(nil); {
1516 NSString *type([self type]);
1517 if ([type isEqualToString:kCydiaProgressEventTypeError])
1518 mode = UCLocalize("ERROR");
1519 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1520 mode = UCLocalize("WARNING");
1524 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1530 - (NSString *) compoundMessage {
1531 return [self compound:[self message]];
1534 - (NSString *) compoundTitle {
1537 if (package_ == nil)
1539 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1540 title = [package name];
1544 return [self compound:title];
1550 // Cytore Definitions {{{
1551 struct PackageValue :
1554 Cytore::Offset<PackageValue> next_;
1556 uint32_t index_ : 23;
1557 uint32_t subscribed_ : 1;
1574 Cytore::Offset<PackageValue> packages_[1 << 16];
1577 static Cytore::File<MetaValue> MetaFile_;
1579 // Cytore Helper Functions {{{
1580 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1581 SplitHash nhash = { hashlittle(name, length) };
1583 PackageValue *metadata;
1585 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1586 offset: if (offset->IsNull()) {
1587 *offset = MetaFile_.New<PackageValue>(length + 1);
1588 metadata = &MetaFile_.Get(*offset);
1590 if (metadata == NULL) {
1594 metadata = new PackageValue();
1595 memset(metadata, 0, sizeof(*metadata));
1598 memcpy(metadata->name_, name, length + 1);
1599 metadata->nhash_ = nhash.u16[1];
1601 metadata = &MetaFile_.Get(*offset);
1603 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1604 offset = &metadata->next_;
1612 static void PackageImport(const void *key, const void *value, void *context) {
1613 bool &fail(*reinterpret_cast<bool *>(context));
1616 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1617 NSLog(@"failed to import package %@", key);
1621 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1622 NSDictionary *package((NSDictionary *) value);
1624 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1625 if ([subscribed boolValue] && !metadata->subscribed_)
1626 metadata->subscribed_ = true;
1628 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1629 time_t time([date timeIntervalSince1970]);
1630 if (metadata->first_ > time || metadata->first_ == 0)
1631 metadata->first_ = time;
1634 NSDate *date([package objectForKey:@"LastSeen"]);
1635 NSString *version([package objectForKey:@"LastVersion"]);
1637 if (date != nil && version != nil) {
1638 time_t time([date timeIntervalSince1970]);
1639 if (metadata->last_ < time || metadata->last_ == 0)
1640 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1641 size_t length(strlen(buffer));
1642 uint16_t vhash(hashlittle(buffer, length));
1644 size_t capped(std::min<size_t>(8, length));
1645 char *latest(buffer + length - capped);
1647 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1648 metadata->vhash_ = vhash;
1650 metadata->last_ = time;
1656 /* Source Class {{{ */
1657 @interface Source : NSObject {
1658 CYString depiction_;
1659 CYString description_;
1665 CYString distribution_;
1670 _H<NSString> authority_;
1672 CYString defaultIcon_;
1674 _H<NSDictionary> record_;
1678 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1680 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1682 - (NSString *) depictionForPackage:(NSString *)package;
1683 - (NSString *) supportForPackage:(NSString *)package;
1685 - (NSDictionary *) record;
1689 - (NSString *) distribution;
1690 - (NSString *) type;
1692 - (NSString *) host;
1694 - (NSString *) name;
1695 - (NSString *) description;
1696 - (NSString *) label;
1697 - (NSString *) origin;
1698 - (NSString *) version;
1700 - (NSString *) defaultIcon;
1704 @implementation Source
1708 distribution_.clear();
1711 description_.clear();
1717 defaultIcon_.clear();
1725 // XXX: this is a very inefficient way to call these deconstructors
1730 + (NSArray *) _attributeKeys {
1731 return [NSArray arrayWithObjects:
1746 - (NSArray *) attributeKeys {
1747 return [[self class] _attributeKeys];
1750 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1751 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1754 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1757 trusted_ = index->IsTrusted();
1759 uri_.set(pool, index->GetURI());
1760 distribution_.set(pool, index->GetDist());
1761 type_.set(pool, index->GetType());
1763 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1764 if (dindex != NULL) {
1766 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1769 pkgTagFile tags(&fd);
1771 pkgTagSection section;
1778 {"default-icon", &defaultIcon_},
1779 {"depiction", &depiction_},
1780 {"description", &description_},
1782 {"origin", &origin_},
1783 {"support", &support_},
1784 {"version", &version_},
1787 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1788 const char *start, *end;
1790 if (section.Find(names[i].name_, start, end)) {
1791 CYString &value(*names[i].value_);
1792 value.set(pool, start, end - start);
1798 record_ = [Sources_ objectForKey:[self key]];
1800 NSURL *url([NSURL URLWithString:uri_]);
1804 host_ = [host_ lowercaseString];
1807 // XXX: this is due to a bug in _H<>
1808 authority_ = (id) host_;
1810 authority_ = [url path];
1813 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1814 if ((self = [super init]) != nil) {
1815 [self setMetaIndex:index inPool:pool];
1819 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1820 NSDictionary *lhr = [self record];
1821 NSDictionary *rhr = [source record];
1824 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1826 NSString *lhs = [self name];
1827 NSString *rhs = [source name];
1829 if ([lhs length] != 0 && [rhs length] != 0) {
1830 unichar lhc = [lhs characterAtIndex:0];
1831 unichar rhc = [rhs characterAtIndex:0];
1833 if (isalpha(lhc) && !isalpha(rhc))
1834 return NSOrderedAscending;
1835 else if (!isalpha(lhc) && isalpha(rhc))
1836 return NSOrderedDescending;
1839 return [lhs compare:rhs options:LaxCompareOptions_];
1842 - (NSString *) depictionForPackage:(NSString *)package {
1843 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1846 - (NSString *) supportForPackage:(NSString *)package {
1847 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1850 - (NSDictionary *) record {
1858 - (NSString *) uri {
1862 - (NSString *) distribution {
1863 return distribution_;
1866 - (NSString *) type {
1870 - (NSString *) key {
1871 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1874 - (NSString *) host {
1878 - (NSString *) name {
1879 return origin_.empty() ? (id) authority_ : origin_;
1882 - (NSString *) description {
1883 return description_;
1886 - (NSString *) label {
1887 return label_.empty() ? (id) authority_ : label_;
1890 - (NSString *) origin {
1894 - (NSString *) version {
1898 - (NSString *) defaultIcon {
1899 return defaultIcon_;
1904 /* CydiaOperation Class {{{ */
1905 @interface CydiaOperation : NSObject {
1906 NSString *operator_;
1910 - (NSString *) operator;
1911 - (NSString *) value;
1915 @implementation CydiaOperation
1918 [operator_ release];
1923 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1924 if ((self = [super init]) != nil) {
1925 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1926 value_ = [[NSString alloc] initWithUTF8String:value];
1930 + (NSArray *) _attributeKeys {
1931 return [NSArray arrayWithObjects:
1937 - (NSArray *) attributeKeys {
1938 return [[self class] _attributeKeys];
1941 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1942 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1945 - (NSString *) operator {
1949 - (NSString *) value {
1955 /* CydiaClause Class {{{ */
1956 @interface CydiaClause : NSObject {
1958 CydiaOperation *version_;
1961 - (NSString *) package;
1962 - (CydiaOperation *) version;
1966 @implementation CydiaClause
1974 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1975 if ((self = [super init]) != nil) {
1976 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1978 if (const char *version = dep.TargetVer())
1979 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1981 version_ = [[NSNull null] retain];
1985 + (NSArray *) _attributeKeys {
1986 return [NSArray arrayWithObjects:
1992 - (NSArray *) attributeKeys {
1993 return [[self class] _attributeKeys];
1996 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1997 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2000 - (NSString *) package {
2004 - (CydiaOperation *) version {
2010 /* CydiaRelation Class {{{ */
2011 @interface CydiaRelation : NSObject {
2012 NSString *relationship_;
2013 NSMutableArray *clauses_;
2016 - (NSString *) relationship;
2017 - (NSArray *) clauses;
2021 @implementation CydiaRelation
2024 [relationship_ release];
2029 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2030 if ((self = [super init]) != nil) {
2031 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
2032 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
2034 pkgCache::DepIterator start;
2035 pkgCache::DepIterator end;
2036 dep.GlobOr(start, end); // ++dep
2039 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2041 // yes, seriously. (wtf?)
2049 + (NSArray *) _attributeKeys {
2050 return [NSArray arrayWithObjects:
2056 - (NSArray *) attributeKeys {
2057 return [[self class] _attributeKeys];
2060 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2061 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2064 - (NSString *) relationship {
2065 return relationship_;
2068 - (NSArray *) clauses {
2072 - (void) addClause:(CydiaClause *)clause {
2073 [clauses_ addObject:clause];
2078 /* Package Class {{{ */
2079 struct ParsedPackage {
2084 CYString depiction_;
2094 @interface Package : NSObject {
2097 uint32_t essential_ : 1;
2098 uint32_t obsolete_ : 1;
2099 uint32_t ignored_ : 1;
2103 _transient Database *database_;
2105 pkgCache::VerIterator version_;
2106 pkgCache::PkgIterator iterator_;
2107 pkgCache::VerFileIterator file_;
2113 CYString installed_;
2115 const char *section_;
2116 _transient NSString *section$_;
2120 PackageValue *metadata_;
2121 ParsedPackage *parsed_;
2123 NSMutableArray *tags_;
2126 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2127 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2129 - (pkgCache::PkgIterator) iterator;
2132 - (NSString *) section;
2133 - (NSString *) simpleSection;
2135 - (NSString *) longSection;
2136 - (NSString *) shortSection;
2140 - (Address *) maintainer;
2142 - (NSString *) longDescription;
2143 - (NSString *) shortDescription;
2146 - (PackageValue *) metadata;
2149 - (bool) subscribed;
2150 - (bool) setSubscribed:(bool)subscribed;
2154 - (NSString *) latest;
2155 - (NSString *) installed;
2156 - (BOOL) uninstalled;
2159 - (BOOL) upgradableAndEssential:(BOOL)essential;
2162 - (BOOL) unfiltered;
2166 - (BOOL) halfConfigured;
2167 - (BOOL) halfInstalled;
2169 - (NSString *) mode;
2172 - (NSString *) name;
2174 - (NSString *) homepage;
2175 - (NSString *) depiction;
2176 - (Address *) author;
2178 - (NSString *) support;
2180 - (NSArray *) files;
2181 - (NSArray *) warnings;
2182 - (NSArray *) applications;
2184 - (Source *) source;
2186 - (BOOL) matches:(NSString *)text;
2188 - (bool) hasSupportingRole;
2189 - (BOOL) hasTag:(NSString *)tag;
2190 - (NSString *) primaryPurpose;
2191 - (NSArray *) purposes;
2192 - (bool) isCommercial;
2194 - (void) setIndex:(size_t)index;
2196 - (CYString &) cyname;
2198 - (uint32_t) compareBySection:(NSArray *)sections;
2203 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2204 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2205 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2206 - (bool) isVisibleInSection:(NSString *)section;
2207 - (bool) isVisibleInSource:(Source *)source;
2211 uint32_t PackageChangesRadix(Package *self, void *) {
2216 uint32_t timestamp : 30;
2217 uint32_t ignored : 1;
2218 uint32_t upgradable : 1;
2222 bool upgradable([self upgradableAndEssential:YES]);
2223 value.bits.upgradable = upgradable ? 1 : 0;
2226 value.bits.timestamp = 0;
2227 value.bits.ignored = [self ignored] ? 0 : 1;
2228 value.bits.upgradable = 1;
2230 value.bits.timestamp = [self seen] >> 2;
2231 value.bits.ignored = 0;
2232 value.bits.upgradable = 0;
2235 return _not(uint32_t) - value.key;
2238 uint32_t PackagePrefixRadix(Package *self, void *context) {
2239 size_t offset(reinterpret_cast<size_t>(context));
2240 CYString &name([self cyname]);
2242 size_t size(name.size());
2245 char *text(name.data());
2248 if (!isdigit(text[0]))
2252 while (size != digits && isdigit(text[digits]))
2260 if (offset == 0 && zeros != 0) {
2261 memset(data, '0', zeros);
2262 memcpy(data + zeros, text, 4 - zeros);
2264 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2265 if (size <= offset - zeros)
2268 text += offset - zeros;
2269 size -= offset - zeros;
2272 memcpy(data, text, 4);
2274 memcpy(data, text, size);
2275 memset(data + size, 0, 4 - size);
2278 for (size_t i(0); i != 4; ++i)
2279 if (isalpha(data[i]))
2287 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2289 /* XXX: ntohl may be more honest */
2290 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2293 CYString &(*PackageName)(Package *self, SEL sel);
2295 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2296 _profile(PackageNameCompare)
2297 CYString &lhi(PackageName(lhs, @selector(cyname)));
2298 CYString &rhi(PackageName(rhs, @selector(cyname)));
2299 CFStringRef lhn(lhi), rhn(rhi);
2302 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2303 else if (rhn == NULL)
2304 return NSOrderedDescending;
2306 _profile(PackageNameCompare$NumbersLast)
2307 if (!lhi.empty() && !rhi.empty()) {
2308 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2309 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2310 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2311 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2312 return lha ? NSOrderedAscending : NSOrderedDescending;
2316 CFIndex length = CFStringGetLength(lhn);
2318 _profile(PackageNameCompare$Compare)
2319 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2324 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2325 return PackageNameCompare(*lhs, *rhs, context);
2328 struct PackageNameOrdering :
2329 std::binary_function<Package *, Package *, bool>
2331 _finline bool operator ()(Package *lhs, Package *rhs) const {
2332 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2336 @implementation Package
2338 - (NSString *) description {
2339 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2343 if (parsed_ != NULL)
2352 + (NSString *) webScriptNameForSelector:(SEL)selector {
2354 else if (selector == @selector(clear))
2356 else if (selector == @selector(getField:))
2358 else if (selector == @selector(hasTag:))
2360 else if (selector == @selector(install))
2362 else if (selector == @selector(remove))
2368 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2369 return [self webScriptNameForSelector:selector] == nil;
2372 + (NSArray *) _attributeKeys {
2373 return [NSArray arrayWithObjects:
2392 @"shortDescription",
2405 - (NSArray *) attributeKeys {
2406 return [[self class] _attributeKeys];
2409 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2410 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2413 - (NSArray *) relations {
2414 @synchronized (database_) {
2415 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2416 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2417 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2421 - (NSString *) getField:(NSString *)name {
2422 @synchronized (database_) {
2423 if ([database_ era] != era_ || file_.end())
2426 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2428 const char *start, *end;
2429 if (!parser.Find([name UTF8String], start, end))
2430 return (NSString *) [NSNull null];
2432 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2436 if (parsed_ != NULL)
2438 @synchronized (database_) {
2439 if ([database_ era] != era_ || file_.end())
2442 ParsedPackage *parsed(new ParsedPackage);
2445 _profile(Package$parse)
2446 pkgRecords::Parser *parser;
2448 _profile(Package$parse$Lookup)
2449 parser = &[database_ records]->Lookup(file_);
2454 _profile(Package$parse$Find)
2459 {"icon", &parsed->icon_},
2460 {"depiction", &parsed->depiction_},
2461 {"homepage", &parsed->homepage_},
2462 {"website", &website},
2463 {"bugs", &parsed->bugs_},
2464 {"support", &parsed->support_},
2465 {"sponsor", &parsed->sponsor_},
2466 {"author", &parsed->author_},
2469 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2470 const char *start, *end;
2472 if (parser->Find(names[i].name_, start, end)) {
2473 CYString &value(*names[i].value_);
2474 _profile(Package$parse$Value)
2475 value.set(pool_, start, end - start);
2481 _profile(Package$parse$Tagline)
2482 const char *start, *end;
2483 if (parser->ShortDesc(start, end)) {
2484 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2487 while (stop != start && stop[-1] == '\r')
2489 parsed->tagline_.set(pool_, start, stop - start);
2493 _profile(Package$parse$Retain)
2494 if (parsed->homepage_.empty())
2495 parsed->homepage_ = website;
2496 if (parsed->homepage_ == parsed->depiction_)
2497 parsed->homepage_.clear();
2502 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2503 if ((self = [super init]) != nil) {
2504 _profile(Package$initWithVersion)
2507 database_ = database;
2508 era_ = [database era];
2512 pkgCache::PkgIterator iterator(version.ParentPkg());
2513 iterator_ = iterator;
2515 _profile(Package$initWithVersion$Version)
2516 if (!version_.end())
2517 file_ = version_.FileList();
2519 pkgCache &cache([database_ cache]);
2520 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2524 _profile(Package$initWithVersion$Cache)
2525 name_.set(NULL, iterator.Display());
2527 latest_.set(NULL, StripVersion_(version_.VerStr()));
2529 pkgCache::VerIterator current(iterator.CurrentVer());
2531 installed_.set(NULL, StripVersion_(current.VerStr()));
2534 _profile(Package$initWithVersion$Tags)
2535 pkgCache::TagIterator tag(iterator.TagList());
2537 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2539 const char *name(tag.Name());
2540 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2542 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2543 if (strcmp(name + 6, "enduser") == 0)
2545 else if (strcmp(name + 6, "hacker") == 0)
2547 else if (strcmp(name + 6, "developer") == 0)
2549 else if (strcmp(name + 6, "cydia") == 0)
2555 if (strncmp(name, "cydia::", 7) == 0) {
2556 if (strcmp(name + 7, "essential") == 0)
2558 else if (strcmp(name + 7, "obsolete") == 0)
2563 } while (!tag.end());
2567 _profile(Package$initWithVersion$Metadata)
2568 const char *mixed(iterator.Name());
2569 size_t size(strlen(mixed));
2570 char lower[size + 1];
2572 for (size_t i(0); i != size; ++i)
2573 lower[i] = mixed[i] | 0x20;
2576 PackageValue *metadata(PackageFind(lower, size));
2577 metadata_ = metadata;
2579 id_.set(NULL, metadata->name_, size);
2581 const char *latest(version_.VerStr());
2582 size_t length(strlen(latest));
2584 uint16_t vhash(hashlittle(latest, length));
2586 size_t capped(std::min<size_t>(8, length));
2587 latest = latest + length - capped;
2589 if (metadata->first_ == 0)
2590 metadata->first_ = now_;
2592 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2593 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2594 metadata->vhash_ = vhash;
2595 metadata->last_ = now_;
2596 } else if (metadata->last_ == 0)
2597 metadata->last_ = metadata->first_;
2600 _profile(Package$initWithVersion$Section)
2601 section_ = iterator.Section();
2604 _profile(Package$initWithVersion$Flags)
2605 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2606 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2611 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2612 pkgCache::VerIterator version;
2614 _profile(Package$packageWithIterator$GetCandidateVer)
2615 version = [database policy]->GetCandidateVer(iterator);
2623 _profile(Package$packageWithIterator$Allocate)
2624 package = [Package allocWithZone:zone];
2627 _profile(Package$packageWithIterator$Initialize)
2629 initWithVersion:version
2636 _profile(Package$packageWithIterator$Autorelease)
2637 package = [package autorelease];
2643 - (pkgCache::PkgIterator) iterator {
2647 - (NSString *) section {
2648 if (section$_ == nil) {
2649 if (section_ == NULL)
2652 _profile(Package$section$mappedSectionForPointer)
2653 section$_ = [database_ mappedSectionForPointer:section_];
2658 - (NSString *) simpleSection {
2659 if (NSString *section = [self section])
2660 return Simplify(section);
2665 - (NSString *) longSection {
2666 return LocalizeSection([self section]);
2669 - (NSString *) shortSection {
2670 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2673 - (NSString *) uri {
2676 pkgIndexFile *index;
2677 pkgCache::PkgFileIterator file(file_.File());
2678 if (![database_ list].FindIndex(file, index))
2680 return [NSString stringWithUTF8String:iterator_->Path];
2681 //return [NSString stringWithUTF8String:file.Site()];
2682 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2686 - (Address *) maintainer {
2687 @synchronized (database_) {
2688 if ([database_ era] != era_ || file_.end())
2691 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2692 const std::string &maintainer(parser->Maintainer());
2693 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2697 @synchronized (database_) {
2698 if ([database_ era] != era_ || version_.end())
2701 return version_->InstalledSize;
2704 - (NSString *) longDescription {
2705 @synchronized (database_) {
2706 if ([database_ era] != era_ || file_.end())
2709 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2710 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2712 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2713 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2714 if ([lines count] < 2)
2717 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2718 for (size_t i(1), e([lines count]); i != e; ++i) {
2719 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2720 [trimmed addObject:trim];
2723 return [trimmed componentsJoinedByString:@"\n"];
2726 - (NSString *) shortDescription {
2727 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2731 _profile(Package$index)
2732 CFStringRef name((CFStringRef) [self name]);
2733 if (CFStringGetLength(name) == 0)
2735 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2736 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2738 return toupper(character);
2742 - (PackageValue *) metadata {
2747 PackageValue *metadata([self metadata]);
2748 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2751 - (bool) subscribed {
2752 return [self metadata]->subscribed_;
2755 - (bool) setSubscribed:(bool)subscribed {
2756 PackageValue *metadata([self metadata]);
2757 if (metadata->subscribed_ == subscribed)
2759 metadata->subscribed_ = subscribed;
2767 - (NSString *) latest {
2771 - (NSString *) installed {
2775 - (BOOL) uninstalled {
2776 return installed_.empty();
2780 return !version_.end();
2783 - (BOOL) upgradableAndEssential:(BOOL)essential {
2784 _profile(Package$upgradableAndEssential)
2785 pkgCache::VerIterator current(iterator_.CurrentVer());
2787 return essential && essential_;
2789 return !version_.end() && version_ != current;
2793 - (BOOL) essential {
2798 return [database_ cache][iterator_].InstBroken();
2801 - (BOOL) unfiltered {
2802 _profile(Package$unfiltered$obsolete)
2803 if (_unlikely(obsolete_))
2807 _profile(Package$unfiltered$hasSupportingRole)
2808 if (_unlikely(![self hasSupportingRole]))
2816 if (![self unfiltered])
2821 _profile(Package$visible$section)
2822 section = [self section];
2825 _profile(Package$visible$isSectionVisible)
2826 if (!isSectionVisible(section))
2834 unsigned char current(iterator_->CurrentState);
2835 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2838 - (BOOL) halfConfigured {
2839 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2842 - (BOOL) halfInstalled {
2843 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2847 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2848 return state.Mode != pkgDepCache::ModeKeep;
2851 - (NSString *) mode {
2852 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2854 switch (state.Mode) {
2855 case pkgDepCache::ModeDelete:
2856 if ((state.iFlags & pkgDepCache::Purge) != 0)
2860 case pkgDepCache::ModeKeep:
2861 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2862 return @"REINSTALL";
2863 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2867 case pkgDepCache::ModeInstall:
2868 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2869 return @"REINSTALL";
2870 else*/ switch (state.Status) {
2872 return @"DOWNGRADE";
2878 return @"NEW_INSTALL";
2889 - (NSString *) name {
2890 return name_.empty() ? id_ : name_;
2893 - (UIImage *) icon {
2894 NSString *section = [self simpleSection];
2897 if (parsed_ != NULL)
2898 if (NSString *href = parsed_->icon_)
2899 if ([href hasPrefix:@"file:///"])
2900 // XXX: correct escaping
2901 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2902 if (icon == nil) if (section != nil)
2903 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2904 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2905 if ([dicon hasPrefix:@"file:///"])
2906 // XXX: correct escaping
2907 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2909 icon = [UIImage applicationImageNamed:@"unknown.png"];
2913 - (NSString *) homepage {
2914 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2917 - (NSString *) depiction {
2918 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2921 - (Address *) sponsor {
2922 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2925 - (Address *) author {
2926 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2929 - (NSString *) support {
2930 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2933 - (NSArray *) files {
2934 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2935 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2938 fin.open([path UTF8String]);
2943 while (std::getline(fin, line))
2944 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2949 - (NSString *) state {
2950 @synchronized (database_) {
2951 if ([database_ era] != era_ || file_.end())
2954 switch (iterator_->CurrentState) {
2955 case pkgCache::State::NotInstalled:
2956 return @"NotInstalled";
2957 case pkgCache::State::UnPacked:
2959 case pkgCache::State::HalfConfigured:
2960 return @"HalfConfigured";
2961 case pkgCache::State::HalfInstalled:
2962 return @"HalfInstalled";
2963 case pkgCache::State::ConfigFiles:
2964 return @"ConfigFiles";
2965 case pkgCache::State::Installed:
2966 return @"Installed";
2967 case pkgCache::State::TriggersAwaited:
2968 return @"TriggersAwaited";
2969 case pkgCache::State::TriggersPending:
2970 return @"TriggersPending";
2973 return (NSString *) [NSNull null];
2976 - (NSString *) selection {
2977 @synchronized (database_) {
2978 if ([database_ era] != era_ || file_.end())
2981 switch (iterator_->SelectedState) {
2982 case pkgCache::State::Unknown:
2984 case pkgCache::State::Install:
2986 case pkgCache::State::Hold:
2988 case pkgCache::State::DeInstall:
2989 return @"DeInstall";
2990 case pkgCache::State::Purge:
2994 return (NSString *) [NSNull null];
2997 - (NSArray *) warnings {
2998 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2999 const char *name(iterator_.Name());
3001 size_t length(strlen(name));
3002 if (length < 2) invalid:
3003 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3004 else for (size_t i(0); i != length; ++i)
3006 /* XXX: technically this is not allowed */
3007 (name[i] < 'A' || name[i] > 'Z') &&
3008 (name[i] < 'a' || name[i] > 'z') &&
3009 (name[i] < '0' || name[i] > '9') &&
3010 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3013 if (strcmp(name, "cydia") != 0) {
3016 bool _private = false;
3019 bool repository = [[self section] isEqualToString:@"Repositories"];
3021 if (NSArray *files = [self files])
3022 for (NSString *file in files)
3023 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3025 else if (!user && [file isEqualToString:@"/User"])
3027 else if (!_private && [file isEqualToString:@"/private"])
3029 else if (!stash && [file isEqualToString:@"/var/stash"])
3032 /* XXX: this is not sensitive enough. only some folders are valid. */
3033 if (cydia && !repository)
3034 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3036 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3038 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3040 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3043 return [warnings count] == 0 ? nil : warnings;
3046 - (NSArray *) applications {
3047 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3049 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3051 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
3052 if (NSArray *files = [self files])
3053 for (NSString *file in files)
3054 if (application_r(file)) {
3055 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3056 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3057 if ([id isEqualToString:me])
3060 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3062 display = application_r[1];
3064 NSString *bundle([file stringByDeletingLastPathComponent]);
3065 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3066 if (icon == nil || [icon length] == 0)
3068 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3070 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3071 [applications addObject:application];
3073 [application addObject:id];
3074 [application addObject:display];
3075 [application addObject:url];
3078 return [applications count] == 0 ? nil : applications;
3081 - (Source *) source {
3082 if (source_ == nil) {
3083 @synchronized (database_) {
3084 if ([database_ era] != era_ || file_.end())
3085 source_ = (Source *) [NSNull null];
3087 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
3091 return source_ == (Source *) [NSNull null] ? nil : source_;
3094 - (BOOL) matches:(NSString *)text {
3100 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
3101 if (range.location != NSNotFound)
3104 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
3105 if (range.location != NSNotFound)
3110 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
3111 if (range.location != NSNotFound)
3117 - (bool) hasSupportingRole {
3122 if ([Role_ isEqualToString:@"User"])
3126 if ([Role_ isEqualToString:@"Hacker"])
3130 if ([Role_ isEqualToString:@"Developer"])
3135 - (NSArray *) tags {
3139 - (BOOL) hasTag:(NSString *)tag {
3140 return tags_ == nil ? NO : [tags_ containsObject:tag];
3143 - (NSString *) primaryPurpose {
3144 for (NSString *tag in tags_)
3145 if ([tag hasPrefix:@"purpose::"])
3146 return [tag substringFromIndex:9];
3150 - (NSArray *) purposes {
3151 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3152 for (NSString *tag in tags_)
3153 if ([tag hasPrefix:@"purpose::"])
3154 [purposes addObject:[tag substringFromIndex:9]];
3155 return [purposes count] == 0 ? nil : purposes;
3158 - (bool) isCommercial {
3159 return [self hasTag:@"cydia::commercial"];
3162 - (void) setIndex:(size_t)index {
3163 if (metadata_->index_ != index)
3164 metadata_->index_ = index;
3167 - (CYString &) cyname {
3168 return name_.empty() ? id_ : name_;
3171 - (uint32_t) compareBySection:(NSArray *)sections {
3172 NSString *section([self section]);
3173 for (size_t i(0), e([sections count]); i != e; ++i) {
3174 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3178 return _not(uint32_t);
3182 @synchronized (database_) {
3183 pkgProblemResolver *resolver = [database_ resolver];
3184 resolver->Clear(iterator_);
3186 pkgCacheFile &cache([database_ cache]);
3187 cache->SetReInstall(iterator_, false);
3188 cache->MarkKeep(iterator_, false);
3192 @synchronized (database_) {
3193 pkgProblemResolver *resolver = [database_ resolver];
3194 resolver->Clear(iterator_);
3195 resolver->Protect(iterator_);
3197 pkgCacheFile &cache([database_ cache]);
3198 cache->SetReInstall(iterator_, false);
3199 cache->MarkInstall(iterator_, false);
3201 pkgDepCache::StateCache &state((*cache)[iterator_]);
3202 if (!state.Install())
3203 cache->SetReInstall(iterator_, true);
3207 @synchronized (database_) {
3208 pkgProblemResolver *resolver = [database_ resolver];
3209 resolver->Clear(iterator_);
3210 resolver->Remove(iterator_);
3211 resolver->Protect(iterator_);
3213 pkgCacheFile &cache([database_ cache]);
3214 cache->SetReInstall(iterator_, false);
3215 cache->MarkDelete(iterator_, true);
3218 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3219 _profile(Package$isUnfilteredAndSearchedForBy)
3222 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3223 value &= [self unfiltered];
3226 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3227 value &= [self matches:search];
3234 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3235 if ([search length] == 0)
3238 _profile(Package$isUnfilteredAndSelectedForBy)
3241 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3242 value &= [self unfiltered];
3245 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3246 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3253 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3254 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3257 - (bool) isVisibleInSection:(NSString *)name {
3258 NSString *section([self section]);
3262 section == nil && [name length] == 0 ||
3263 [name isEqualToString:section]
3264 ) && [self visible];
3267 - (bool) isVisibleInSource:(Source *)source {
3268 return [self source] == source && [self visible];
3273 /* Section Class {{{ */
3274 @interface Section : NSObject {
3279 NSString *localized_;
3282 - (NSComparisonResult) compareByLocalized:(Section *)section;
3283 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3284 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3285 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3286 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3287 - (NSString *) name;
3294 - (void) addToCount;
3296 - (void) setCount:(size_t)count;
3297 - (NSString *) localized;
3301 @implementation Section
3305 if (localized_ != nil)
3306 [localized_ release];
3310 - (NSComparisonResult) compareByLocalized:(Section *)section {
3311 NSString *lhs(localized_);
3312 NSString *rhs([section localized]);
3314 /*if ([lhs length] != 0 && [rhs length] != 0) {
3315 unichar lhc = [lhs characterAtIndex:0];
3316 unichar rhc = [rhs characterAtIndex:0];
3318 if (isalpha(lhc) && !isalpha(rhc))
3319 return NSOrderedAscending;
3320 else if (!isalpha(lhc) && isalpha(rhc))
3321 return NSOrderedDescending;
3324 return [lhs compare:rhs options:LaxCompareOptions_];
3327 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3328 if ((self = [self initWithName:name localize:NO]) != nil) {
3329 if (localized != nil)
3330 localized_ = [localized retain];
3334 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3335 return [self initWithName:name row:0 localize:localize];
3338 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3339 if ((self = [super init]) != nil) {
3340 name_ = [name retain];
3344 localized_ = [LocalizeSection(name_) retain];
3348 /* XXX: localize the index thingees */
3349 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3350 if ((self = [super init]) != nil) {
3351 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3357 - (NSString *) name {
3377 - (void) addToCount {
3381 - (void) setCount:(size_t)count {
3385 - (NSString *) localized {
3392 static NSString *Colon_;
3393 static NSString *Elision_;
3394 static NSString *Error_;
3395 static NSString *Warning_;
3397 /* Database Implementation {{{ */
3398 @implementation Database
3400 + (Database *) sharedInstance {
3401 static Database *instance;
3402 if (instance == nil)
3403 instance = [[Database alloc] init];
3411 - (void) releasePackages {
3412 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3413 CFArrayRemoveAllValues(packages_);
3417 // XXX: actually implement this thing
3419 [sourceList_ release];
3420 [self releasePackages];
3421 apr_pool_destroy(pool_);
3422 NSRecycleZone(zone_);
3426 - (void) _readCydia:(NSNumber *)fd { _pooled
3427 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3428 std::istream is(&ib);
3431 static Pcre finish_r("^finish:([^:]*)$");
3433 while (std::getline(is, line)) {
3434 const char *data(line.c_str());
3435 size_t size = line.size();
3436 lprintf("C:%s\n", data);
3438 if (finish_r(data, size)) {
3439 NSString *finish = finish_r[1];
3440 int index = [Finishes_ indexOfObject:finish];
3441 if (index != INT_MAX && index > Finish_)
3449 - (void) _readStatus:(NSNumber *)fd { _pooled
3450 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3451 std::istream is(&ib);
3454 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3455 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3457 while (std::getline(is, line)) {
3458 const char *data(line.c_str());
3459 size_t size(line.size());
3460 lprintf("S:%s\n", data);
3462 if (conffile_r(data, size)) {
3463 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3464 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3465 } else if (strncmp(data, "status: ", 8) == 0) {
3466 // status: <package>: {unpacked,half-configured,installed}
3467 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3468 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3469 } else if (strncmp(data, "processing: ", 12) == 0) {
3470 // processing: configure: config-test
3471 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3472 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3473 } else if (pmstatus_r(data, size)) {
3474 std::string type([pmstatus_r[1] UTF8String]);
3476 NSString *package = pmstatus_r[2];
3477 if ([package isEqualToString:@"dpkg-exec"])
3480 float percent([pmstatus_r[3] floatValue]);
3481 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3483 NSString *string = pmstatus_r[4];
3485 if (type == "pmerror") {
3486 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3487 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3488 } else if (type == "pmstatus") {
3489 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3490 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3491 } else if (type == "pmconffile")
3492 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3494 lprintf("E:unknown pmstatus\n");
3496 lprintf("E:unknown status\n");
3502 - (void) _readOutput:(NSNumber *)fd { _pooled
3503 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3504 std::istream is(&ib);
3507 while (std::getline(is, line)) {
3508 lprintf("O:%s\n", line.c_str());
3510 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3511 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3521 - (Package *) packageWithName:(NSString *)name {
3522 @synchronized (self) {
3523 if (static_cast<pkgDepCache *>(cache_) == NULL)
3525 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3526 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3530 if ((self = [super init]) != nil) {
3537 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3538 apr_pool_create(&pool_, NULL);
3540 size_t capacity(MetaFile_->active_);
3546 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3547 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3551 _assert(pipe(fds) != -1);
3554 _config->Set("APT::Keep-Fds::", cydiafd_);
3555 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3558 detachNewThreadSelector:@selector(_readCydia:)
3560 withObject:[NSNumber numberWithInt:fds[0]]
3563 _assert(pipe(fds) != -1);
3567 detachNewThreadSelector:@selector(_readStatus:)
3569 withObject:[NSNumber numberWithInt:fds[0]]
3572 _assert(pipe(fds) != -1);
3573 _assert(dup2(fds[0], 0) != -1);
3574 _assert(close(fds[0]) != -1);
3576 input_ = fdopen(fds[1], "a");
3578 _assert(pipe(fds) != -1);
3579 _assert(dup2(fds[1], 1) != -1);
3580 _assert(close(fds[1]) != -1);
3583 detachNewThreadSelector:@selector(_readOutput:)
3585 withObject:[NSNumber numberWithInt:fds[0]]
3590 - (pkgCacheFile &) cache {
3594 - (pkgDepCache::Policy *) policy {
3598 - (pkgRecords *) records {
3602 - (pkgProblemResolver *) resolver {
3606 - (pkgAcquire &) fetcher {
3610 - (pkgSourceList &) list {
3614 - (NSArray *) packages {
3615 return (NSArray *) packages_;
3618 - (NSArray *) sources {
3622 - (Source *) sourceWithKey:(NSString *)key {
3623 for (Source *source in [self sources]) {
3624 if ([[source key] isEqualToString:key])
3629 - (bool) popErrorWithTitle:(NSString *)title {
3632 while (!_error->empty()) {
3634 bool warning(!_error->PopMessage(error));
3639 size_t size(error.size());
3640 if (size == 0 || error[size - 1] != '\n')
3642 error.resize(size - 1);
3645 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3647 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3653 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3654 return [self popErrorWithTitle:title] || !success;
3657 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3658 @synchronized (self) {
3661 [self releasePackages];
3664 [sourceList_ removeAllObjects];
3684 apr_pool_clear(pool_);
3686 NSRecycleZone(zone_);
3687 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3689 int chk(creat("/tmp/cydia.chk", 0644));
3693 if (invocation != nil)
3694 [invocation invoke];
3696 NSString *title(UCLocalize("DATABASE"));
3699 OpProgress progress;
3700 while (!cache_.Open(progress, true)) { pop:
3702 bool warning(!_error->PopMessage(error));
3703 lprintf("cache_.Open():[%s]\n", error.c_str());
3705 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3706 [delegate_ repairWithSelector:@selector(configure)];
3707 else if (error == "The package lists or status file could not be parsed or opened.")
3708 [delegate_ repairWithSelector:@selector(update)];
3709 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3710 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3711 // else if (error == "Malformed Status line")
3712 // else if (error == "The list of sources could not be read.")
3714 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3724 unlink("/tmp/cydia.chk");
3726 now_ = [[NSDate date] timeIntervalSince1970];
3728 policy_ = new pkgDepCache::Policy();
3729 records_ = new pkgRecords(cache_);
3730 resolver_ = new pkgProblemResolver(cache_);
3731 fetcher_ = new pkgAcquire(&status_);
3734 list_ = new pkgSourceList();
3735 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3738 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3739 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3743 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3746 if (cache_->BrokenCount() != 0) {
3747 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3750 if (cache_->BrokenCount() != 0) {
3751 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3755 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3759 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3760 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3761 [sourceList_ addObject:object];
3763 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3764 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3765 // XXX: this could be more intelligent
3766 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3767 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3769 sourceMap_[cached->ID] = object;
3774 /*std::vector<Package *> packages;
3775 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3776 [packages_ release];
3781 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3782 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3783 //packages.push_back(package);
3784 CFArrayAppendValue(packages_, [package retain]);
3788 /*if (packages.empty())
3789 packages_ = [[NSArray alloc] init];
3791 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3794 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3795 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3796 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3804 /*if (!packages.empty())
3805 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3806 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3808 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3810 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3812 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3816 size_t count(CFArrayGetCount(packages_));
3817 MetaFile_->active_ = count;
3819 for (size_t index(0); index != count; ++index)
3820 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3824 } } CYPoolEnd() _trace(); }
3827 @synchronized (self) {
3829 resolver_ = new pkgProblemResolver(cache_);
3831 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3832 if (!cache_[iterator].Keep())
3833 cache_->MarkKeep(iterator, false);
3834 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3835 cache_->SetReInstall(iterator, false);
3838 - (void) configure {
3839 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3841 system([dpkg UTF8String]);
3846 // XXX: I don't remember this condition
3851 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3853 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3855 if ([self popErrorWithTitle:title])
3859 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3862 public pkgArchiveCleaner
3865 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3870 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3877 fetcher_->Shutdown();
3879 pkgRecords records(cache_);
3881 lock_ = new FileFd();
3882 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3884 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3886 if ([self popErrorWithTitle:title])
3890 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3893 manager_ = (_system->CreatePM(cache_));
3894 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3901 bool substrate(RestartSubstrate_);
3902 RestartSubstrate_ = false;
3904 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3906 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3908 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3910 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3911 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3914 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3916 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3918 [self popErrorWithTitle:title];
3922 bool failed = false;
3923 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3924 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3926 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3932 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3940 RestartSubstrate_ = true;
3943 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3945 if (_error->PendingError()) {
3950 if (result == pkgPackageManager::Failed) {
3955 if (result != pkgPackageManager::Completed) {
3960 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3962 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3964 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3965 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3968 if (![before isEqualToArray:after])
3973 NSString *title(UCLocalize("UPGRADE"));
3974 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3980 [self updateWithStatus:status_];
3983 - (void) updateWithStatus:(Status &)status {
3984 NSString *title(UCLocalize("REFRESHING_DATA"));
3987 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3991 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3992 if ([self popErrorWithTitle:title])
3995 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3997 bool success(ListUpdate(status, list, PulseInterval_));
3998 if (status.WasCancelled())
4001 [self popErrorWithTitle:title forOperation:success];
4003 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4005 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
4009 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4010 delegate_ = delegate;
4013 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4014 progress_ = delegate;
4015 status_.setDelegate(delegate);
4018 - (NSObject<ProgressDelegate> *) progressDelegate {
4022 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4023 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4024 return i == sourceMap_.end() ? nil : i->second;
4027 - (NSString *) mappedSectionForPointer:(const char *)section {
4028 _H<NSString> *mapped;
4030 _profile(Database$mappedSectionForPointer$Cache)
4031 mapped = §ions_[section];
4034 if (*mapped == NULL) {
4035 size_t length(strlen(section));
4036 char spaced[length + 1];
4038 _profile(Database$mappedSectionForPointer$Replace)
4039 for (size_t index(0); index != length; ++index)
4040 spaced[index] = section[index] == '_' ? ' ' : section[index];
4041 spaced[length] = '\0';
4046 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4047 string = [NSString stringWithUTF8String:spaced];
4050 _profile(Database$mappedSectionForPointer$Map)
4051 string = [SectionMap_ objectForKey:string] ?: string;
4061 @interface Diversion : NSObject {
4064 _H<NSString> format_;
4069 @implementation Diversion
4071 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4072 if ((self = [super init]) != nil) {
4073 pattern_ = [from UTF8String];
4079 - (NSString *) divert:(NSString *)url {
4083 size_t count(pattern_.size());
4085 for (size_t i(0); i != count; ++i)
4086 values[i] = pattern_[i + 1];
4088 return [[[NSString alloc] initWithFormat:format_ arguments:reinterpret_cast<va_list>(values)] autorelease];
4091 - (NSString *) key {
4095 - (NSUInteger) hash {
4099 - (BOOL) isEqual:(Diversion *)object {
4100 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4105 @interface CydiaObject : NSObject {
4107 _transient id delegate_;
4110 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4114 @interface CYBrowserController : BrowserController {
4115 CydiaObject *cydia_;
4118 + (void) addDiversion:(Diversion *)diversion;
4122 static NSMutableSet *Diversions_;
4124 /* Web Scripting {{{ */
4125 @implementation CydiaObject
4128 [indirect_ release];
4132 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4133 if ((self = [super init]) != nil) {
4134 indirect_ = [indirect retain];
4138 - (void) setDelegate:(id)delegate {
4139 delegate_ = delegate;
4142 + (NSArray *) _attributeKeys {
4143 return [NSArray arrayWithObjects:
4158 - (NSArray *) attributeKeys {
4159 return [[self class] _attributeKeys];
4162 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4163 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4166 - (NSString *) version {
4170 - (NSString *) device {
4171 return [[UIDevice currentDevice] uniqueIdentifier];
4174 - (NSString *) firmware {
4175 return [[UIDevice currentDevice] systemVersion];
4178 - (NSString *) hostname {
4179 return [[UIDevice currentDevice] name];
4182 - (NSString *) idiom {
4183 return (id) Idiom_ ?: [NSNull null];
4186 - (NSString *) plmn {
4187 return (id) PLMN_ ?: [NSNull null];
4190 - (NSString *) ecid {
4191 return (id) ChipID_ ?: [NSNull null];
4194 - (NSString *) serial {
4195 return SerialNumber_;
4198 - (NSString *) role {
4199 return (id) Role_ ?: [NSNull null];
4202 - (NSString *) model {
4203 return [NSString stringWithUTF8String:Machine_];
4206 - (NSString *) token {
4207 return (id) Token_ ?: [NSNull null];
4210 + (NSString *) webScriptNameForSelector:(SEL)selector {
4212 else if (selector == @selector(addBridgedHost:))
4213 return @"addBridgedHost";
4214 else if (selector == @selector(addPipelinedHost:scheme:))
4215 return @"addPipelinedHost";
4216 else if (selector == @selector(addTrivialSource:))
4217 return @"addTrivialSource";
4218 else if (selector == @selector(close))
4220 else if (selector == @selector(divert::))
4222 else if (selector == @selector(du:))
4224 else if (selector == @selector(stringWithFormat:arguments:))
4226 else if (selector == @selector(getAllSources))
4227 return @"getAllSourcs";
4228 else if (selector == @selector(getKernelNumber:))
4229 return @"getKernelNumber";
4230 else if (selector == @selector(getKernelString:))
4231 return @"getKernelString";
4232 else if (selector == @selector(getInstalledPackages))
4233 return @"getInstalledPackages";
4234 else if (selector == @selector(getPackageById:))
4235 return @"getPackageById";
4236 else if (selector == @selector(installPackages:))
4237 return @"installPackages";
4238 else if (selector == @selector(localizedStringForKey:value:table:))
4240 else if (selector == @selector(popViewController:))
4241 return @"popViewController";
4242 else if (selector == @selector(refreshSources))
4243 return @"refreshSources";
4244 else if (selector == @selector(removeButton))
4245 return @"removeButton";
4246 else if (selector == @selector(substitutePackageNames:))
4247 return @"substitutePackageNames";
4248 else if (selector == @selector(scrollToBottom:))
4249 return @"scrollToBottom";
4250 else if (selector == @selector(setAllowsNavigationAction:))
4251 return @"setAllowsNavigationAction";
4252 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4253 return @"setButtonImage";
4254 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4255 return @"setButtonTitle";
4256 else if (selector == @selector(setHidesBackButton:))
4257 return @"setHidesBackButton";
4258 else if (selector == @selector(setHidesNavigationBar:))
4259 return @"setHidesNavigationBar";
4260 else if (selector == @selector(setNavigationBarStyle:))
4261 return @"setNavigationBarStyle";
4262 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4263 return @"setNavigationBarTintColor";
4264 else if (selector == @selector(setPopupHook:))
4265 return @"setPopupHook";
4266 else if (selector == @selector(setToken:))
4268 else if (selector == @selector(setViewportWidth:))
4269 return @"setViewportWidth";
4270 else if (selector == @selector(statfs:))
4272 else if (selector == @selector(supports:))
4278 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4279 return [self webScriptNameForSelector:selector] == nil;
4282 - (BOOL) supports:(NSString *)feature {
4283 return [feature isEqualToString:@"window.open"];
4286 - (void) divert:(NSString *)from :(NSString *)to {
4287 [CYBrowserController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4290 - (NSNumber *) getKernelNumber:(NSString *)name {
4291 const char *string([name UTF8String]);
4294 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4295 return (id) [NSNull null];
4297 if (size != sizeof(int))
4298 return (id) [NSNull null];
4301 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4302 return (id) [NSNull null];
4304 return [NSNumber numberWithInt:value];
4307 - (NSString *) getKernelString:(NSString *)name {
4308 const char *string([name UTF8String]);
4311 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4312 return (id) [NSNull null];
4314 char value[size + 1];
4315 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4316 return (id) [NSNull null];
4318 // XXX: just in case you request something ludicrous
4321 return [NSString stringWithCString:value];
4324 - (void) addBridgedHost:(NSString *)host {
4325 @synchronized (HostConfig_) {
4326 [BridgedHosts_ addObject:host];
4329 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4330 @synchronized (HostConfig_) {
4331 if (scheme != (id) [WebUndefined undefined])
4332 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4334 [PipelinedHosts_ addObject:host];
4337 - (void) popViewController:(NSNumber *)value {
4338 if (value == (id) [WebUndefined undefined])
4339 value = [NSNumber numberWithBool:YES];
4340 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4343 - (void) addTrivialSource:(NSString *)href {
4344 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4347 - (void) refreshSources {
4348 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4351 - (NSArray *) getAllSources {
4352 return [[Database sharedInstance] sources];
4355 - (NSArray *) getInstalledPackages {
4356 Database *database([Database sharedInstance]);
4357 @synchronized (database) {
4358 NSArray *packages([database packages]);
4359 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4360 for (Package *package in packages)
4361 if (![package uninstalled])
4362 [installed addObject:package];
4366 - (Package *) getPackageById:(NSString *)id {
4367 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4371 return (Package *) [NSNull null];
4374 - (NSArray *) statfs:(NSString *)path {
4377 if (path == nil || statfs([path UTF8String], &stat) == -1)
4380 return [NSArray arrayWithObjects:
4381 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4382 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4383 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4387 - (NSNumber *) du:(NSString *)path {
4388 NSNumber *value(nil);
4391 _assert(pipe(fds) != -1);
4393 pid_t pid(ExecFork());
4395 _assert(dup2(fds[1], 1) != -1);
4396 _assert(close(fds[0]) != -1);
4397 _assert(close(fds[1]) != -1);
4398 /* XXX: this should probably not use du */
4399 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4404 _assert(close(fds[1]) != -1);
4406 if (FILE *du = fdopen(fds[0], "r")) {
4408 while (fgets(line, sizeof(line), du) != NULL) {
4409 size_t length(strlen(line));
4410 while (length != 0 && line[length - 1] == '\n')
4411 line[--length] = '\0';
4412 if (char *tab = strchr(line, '\t')) {
4414 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4419 } else _assert(close(fds[0]));
4423 if (waitpid(pid, &status, 0) == -1)
4426 else _assert(false);
4432 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4435 - (void) installPackages:(NSArray *)packages {
4436 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4439 - (NSString *) substitutePackageNames:(NSString *)message {
4440 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4441 for (size_t i(0), e([words count]); i != e; ++i) {
4442 NSString *word([words objectAtIndex:i]);
4443 if (Package *package = [[Database sharedInstance] packageWithName:word])
4444 [words replaceObjectAtIndex:i withObject:[package name]];
4447 return [words componentsJoinedByString:@" "];
4450 - (void) removeButton {
4451 [indirect_ removeButton];
4454 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4455 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4458 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4459 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4462 - (void) setAllowsNavigationAction:(NSString *)value {
4463 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4466 - (void) setHidesBackButton:(NSString *)value {
4467 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4470 - (void) setHidesNavigationBar:(NSString *)value {
4471 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4474 - (void) setNavigationBarStyle:(NSString *)value {
4475 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4478 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4479 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4480 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4481 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4484 - (void) _setToken:(NSString *)token {
4488 [Metadata_ removeObjectForKey:@"Token"];
4490 [Metadata_ setObject:Token_ forKey:@"Token"];
4495 - (void) setToken:(NSString *)token {
4496 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4499 - (void) setPopupHook:(id)function {
4500 [indirect_ setPopupHook:function];
4503 - (void) scrollToBottom:(NSNumber *)animated {
4504 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4507 - (void) setViewportWidth:(float)width {
4508 [indirect_ setViewportWidthOnMainThread:width];
4511 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4512 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4513 unsigned count([arguments count]);
4515 for (unsigned i(0); i != count; ++i)
4516 values[i] = [arguments objectAtIndex:i];
4517 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4520 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4521 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4523 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4525 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4531 /* @ Loading... Indicator {{{ */
4532 @interface CYLoadingIndicator : UIView {
4533 _H<UIActivityIndicatorView> spinner_;
4535 _H<UIView> container_;
4538 @property (readonly, nonatomic) UILabel *label;
4539 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4543 @implementation CYLoadingIndicator
4545 - (id) initWithFrame:(CGRect)frame {
4546 if ((self = [super initWithFrame:frame]) != nil) {
4547 container_ = [[[UIView alloc] init] autorelease];
4548 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4550 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4551 [spinner_ startAnimating];
4552 [container_ addSubview:spinner_];
4554 label_ = [[[UILabel alloc] init] autorelease];
4555 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4556 [label_ setBackgroundColor:[UIColor clearColor]];
4557 [label_ setTextColor:[UIColor blackColor]];
4558 [label_ setShadowColor:[UIColor whiteColor]];
4559 [label_ setShadowOffset:CGSizeMake(0, 1)];
4560 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4561 [container_ addSubview:label_];
4563 CGSize viewsize = frame.size;
4564 CGSize spinnersize = [spinner_ bounds].size;
4565 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4566 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4568 CGRect containrect = {
4569 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4570 CGSizeMake(bothwidth, spinnersize.height)
4573 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4581 [container_ setFrame:containrect];
4582 [spinner_ setFrame:spinrect];
4583 [label_ setFrame:textrect];
4584 [self addSubview:container_];
4588 - (UILabel *) label {
4592 - (UIActivityIndicatorView *) activityIndicatorView {
4598 /* Emulated Loading Controller {{{ */
4599 @interface CYEmulatedLoadingController : CYViewController {
4600 _transient Database *database_;
4601 _H<CYLoadingIndicator> indicator_;
4602 _H<UITabBar> tabbar_;
4603 _H<UINavigationBar> navbar_;
4608 @implementation CYEmulatedLoadingController
4610 - (id) initWithDatabase:(Database *)database {
4611 if ((self = [super init]) != nil) {
4612 database_ = database;
4617 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4619 UITableView *table([[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]);
4620 [table setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4621 [[self view] addSubview:table];
4623 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4624 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4625 [[self view] addSubview:indicator_];
4627 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4628 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4629 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4630 [[self view] addSubview:tabbar_];
4632 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4633 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4634 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4635 [[self view] addSubview:navbar_];
4638 - (void) releaseSubviews {
4647 /* Cydia Browser Controller {{{ */
4648 @implementation CYBrowserController
4655 - (NSURL *) navigationURL {
4656 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4659 + (void) initialize {
4660 Diversions_ = [[NSMutableSet alloc] initWithCapacity:0];
4663 + (void) addDiversion:(Diversion *)diversion {
4664 [Diversions_ addObject:diversion];
4667 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4668 [super webView:view didClearWindowObject:window forFrame:frame];
4670 WebDataSource *source([frame dataSource]);
4671 NSURLResponse *response([source response]);
4672 NSURL *url([response URL]);
4674 @synchronized (HostConfig_) {
4675 if ([[[url scheme] lowercaseString] isEqualToString:@"https"])
4676 if ([BridgedHosts_ containsObject:[url host]])
4677 [window setValue:cydia_ forKey:@"cydia"];
4681 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4682 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4685 NSURL *url([copy URL]);
4686 NSString *href([url absoluteString]);
4688 for (Diversion *diversion in Diversions_)
4689 if (NSString *diverted = [diversion divert:href]) {
4690 [copy setURL:[NSURL URLWithString:diverted]];
4694 if (System_ != NULL)
4695 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4696 if (Machine_ != NULL)
4697 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4699 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4704 - (void) setDelegate:(id)delegate {
4705 [super setDelegate:delegate];
4706 [cydia_ setDelegate:delegate];
4710 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4711 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4713 WebView *webview([[webview_ _documentView] webView]);
4715 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4718 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4720 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4721 if (Product_ != nil)
4722 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4724 [webview setApplicationNameForUserAgent:application];
4732 @interface NSObject (CydiaScript)
4733 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4736 @implementation NSObject (CydiaScript)
4738 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4744 @implementation NSArray (CydiaScript)
4746 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4747 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4748 for (size_t i(0), e([self count]); i != e; ++i)
4749 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4755 @implementation NSDictionary (CydiaScript)
4757 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4758 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4760 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4767 /* Confirmation Controller {{{ */
4768 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4769 if (!iterator.end())
4770 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4771 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4773 pkgCache::PkgIterator package(dep.TargetPkg());
4776 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4783 @protocol ConfirmationControllerDelegate
4784 - (void) cancelAndClear:(bool)clear;
4785 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4789 @interface ConfirmationController : CYBrowserController {
4790 _transient Database *database_;
4792 UIAlertView *essential_;
4794 NSDictionary *changes_;
4795 NSMutableArray *issues_;
4796 NSDictionary *sizes_;
4801 - (id) initWithDatabase:(Database *)database;
4805 @implementation ConfirmationController
4812 if (essential_ != nil)
4813 [essential_ release];
4820 RestartSubstrate_ = true;
4821 [delegate_ confirmWithNavigationController:[self navigationController]];
4824 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4825 NSString *context([alert context]);
4827 if ([context isEqualToString:@"remove"]) {
4828 if (button == [alert cancelButtonIndex])
4829 [self dismissModalViewControllerAnimated:YES];
4830 else if (button == [alert firstOtherButtonIndex]) {
4834 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4835 } else if ([context isEqualToString:@"unable"]) {
4836 [self dismissModalViewControllerAnimated:YES];
4837 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4839 [super alertView:alert clickedButtonAtIndex:button];
4843 - (void) _doContinue {
4844 [self dismissModalViewControllerAnimated:YES];
4845 [delegate_ cancelAndClear:NO];
4848 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4849 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4853 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4854 [super webView:view didClearWindowObject:window forFrame:frame];
4856 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4857 changes_, @"changes",
4861 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4864 - (id) initWithDatabase:(Database *)database {
4865 if ((self = [super init]) != nil) {
4866 database_ = database;
4868 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4869 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4870 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4871 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4872 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4876 pkgCacheFile &cache([database_ cache]);
4877 NSArray *packages([database_ packages]);
4878 pkgDepCache::Policy *policy([database_ policy]);
4880 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4882 for (Package *package in packages) {
4883 pkgCache::PkgIterator iterator([package iterator]);
4884 NSString *name([package id]);
4886 if ([package broken]) {
4887 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4889 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4891 reasons, @"reasons",
4894 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4898 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4899 pkgCache::DepIterator start;
4900 pkgCache::DepIterator end;
4901 dep.GlobOr(start, end); // ++dep
4903 if (!cache->IsImportantDep(end))
4905 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4908 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4910 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4911 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4912 clauses, @"clauses",
4916 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4918 pkgCache::PkgIterator target(start.TargetPkg());
4919 if (target->ProvidesList != 0)
4920 reason = @"missing";
4922 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4924 reason = @"installed";
4925 installed = [NSString stringWithUTF8String:ver.VerStr()];
4926 } else if (!cache[target].CandidateVerIter(cache).end())
4927 reason = @"uninstalled";
4928 else if (target->ProvidesList == 0)
4929 reason = @"uninstallable";
4931 reason = @"virtual";
4934 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4935 [NSString stringWithUTF8String:start.CompType()], @"operator",
4936 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4939 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4940 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4941 version, @"version",
4943 installed, @"installed",
4946 // yes, seriously. (wtf?)
4954 pkgDepCache::StateCache &state(cache[iterator]);
4956 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4958 if (state.NewInstall())
4959 [installs addObject:name];
4960 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4961 [reinstalls addObject:name];
4962 else if (state.Upgrade())
4963 [upgrades addObject:name];
4964 else if (state.Downgrade())
4965 [downgrades addObject:name];
4966 else if (!state.Delete())
4968 else if (special_r(name))
4969 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4970 [NSNull null], @"package",
4971 [NSArray arrayWithObjects:
4972 [NSDictionary dictionaryWithObjectsAndKeys:
4973 @"Conflicts", @"relationship",
4974 [NSArray arrayWithObjects:
4975 [NSDictionary dictionaryWithObjectsAndKeys:
4977 [NSNull null], @"version",
4978 @"installed", @"reason",
4985 if ([package essential])
4987 [removes addObject:name];
4990 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4991 substrate_ |= DepSubstrate(iterator.CurrentVer());
4996 else if (Advanced_) {
4997 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4999 essential_ = [[UIAlertView alloc]
5000 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5001 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5003 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5005 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5009 [essential_ setContext:@"remove"];
5011 essential_ = [[UIAlertView alloc]
5012 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5013 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5015 cancelButtonTitle:UCLocalize("OKAY")
5016 otherButtonTitles:nil
5019 [essential_ setContext:@"unable"];
5022 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
5023 installs, @"installs",
5024 reinstalls, @"reinstalls",
5025 upgrades, @"upgrades",
5026 downgrades, @"downgrades",
5027 removes, @"removes",
5030 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
5031 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5032 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5035 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5037 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
5038 initWithTitle:UCLocalize("CANCEL")
5039 style:UIBarButtonItemStylePlain
5041 action:@selector(cancelButtonClicked)
5047 - (void) applyRightButton {
5048 if ([issues_ count] == 0 && ![self isLoading])
5049 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5050 initWithTitle:UCLocalize("CONFIRM")
5051 style:UIBarButtonItemStyleDone
5053 action:@selector(confirmButtonClicked)
5056 [[self navigationItem] setRightBarButtonItem:nil];
5060 - (void) cancelButtonClicked {
5061 [self dismissModalViewControllerAnimated:YES];
5062 [delegate_ cancelAndClear:YES];
5066 - (void) confirmButtonClicked {
5067 if (essential_ != nil)
5077 /* Progress Data {{{ */
5078 @interface CydiaProgressData : NSObject {
5079 _transient id delegate_;
5088 _H<NSMutableArray> events_;
5089 _H<NSString> title_;
5091 _H<NSString> status_;
5092 _H<NSString> finish_;
5097 @implementation CydiaProgressData
5099 + (NSArray *) _attributeKeys {
5100 return [NSArray arrayWithObjects:
5112 - (NSArray *) attributeKeys {
5113 return [[self class] _attributeKeys];
5116 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5117 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5121 if ((self = [super init]) != nil) {
5122 events_ = [NSMutableArray arrayWithCapacity:32];
5126 - (void) setDelegate:(id)delegate {
5127 delegate_ = delegate;
5130 - (void) setPercent:(float)value {
5134 - (NSNumber *) percent {
5135 return [NSNumber numberWithFloat:percent_];
5138 - (void) setCurrent:(float)value {
5142 - (NSNumber *) current {
5143 return [NSNumber numberWithFloat:current_];
5146 - (void) setTotal:(float)value {
5150 - (NSNumber *) total {
5151 return [NSNumber numberWithFloat:total_];
5154 - (void) setSpeed:(float)value {
5158 - (NSNumber *) speed {
5159 return [NSNumber numberWithFloat:speed_];
5162 - (NSArray *) events {
5166 - (void) removeAllEvents {
5167 [events_ removeAllObjects];
5170 - (void) addEvent:(CydiaProgressEvent *)event {
5171 [events_ addObject:event];
5174 - (void) setTitle:(NSString *)text {
5178 - (NSString *) title {
5182 - (void) setFinish:(NSString *)text {
5186 - (NSString *) finish {
5187 return (id) finish_ ?: [NSNull null];
5190 - (void) setRunning:(bool)running {
5194 - (NSNumber *) running {
5195 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5200 /* Progress Controller {{{ */
5201 @interface ProgressController : CYBrowserController <
5204 _transient Database *database_;
5205 _H<CydiaProgressData> progress_;
5209 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5211 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5213 - (void) setTitle:(NSString *)title;
5214 - (void) setCancellable:(bool)cancellable;
5218 @implementation ProgressController
5221 [database_ setProgressDelegate:nil];
5222 [progress_ setDelegate:nil];
5226 - (void) updateCancel {
5227 [[self navigationItem] setLeftBarButtonItem:(cancel_ == 1 ? [[[UIBarButtonItem alloc]
5228 initWithTitle:UCLocalize("CANCEL")
5229 style:UIBarButtonItemStylePlain
5231 action:@selector(cancel)
5232 ] autorelease] : nil)];
5235 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5236 if ((self = [super init]) != nil) {
5237 database_ = database;
5238 delegate_ = delegate;
5240 [database_ setProgressDelegate:self];
5242 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5243 [progress_ setDelegate:self];
5245 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5247 [scroller_ setBackgroundColor:[UIColor blackColor]];
5249 [[self navigationItem] setHidesBackButton:YES];
5251 [self updateCancel];
5255 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5256 [super webView:view didClearWindowObject:window forFrame:frame];
5257 [window setValue:progress_ forKey:@"cydiaProgress"];
5260 - (void) updateProgress {
5261 [self dispatchEvent:@"CydiaProgressUpdate"];
5264 - (void) viewWillAppear:(BOOL)animated {
5265 if (![self hasLoaded])
5266 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5268 [super viewWillAppear:animated];
5272 UpdateExternalStatus(0);
5279 [delegate_ terminateWithSuccess];
5280 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5281 [delegate_ suspendWithAnimation:YES];
5283 [delegate_ suspend];*/
5295 system("/usr/bin/sbreload");
5301 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5302 SBReboot(SBSSpringBoardServerPort());
5304 reboot2(RB_AUTOBOOT);
5311 - (void) setTitle:(NSString *)title {
5312 [progress_ setTitle:title];
5313 [self updateProgress];
5316 - (UIBarButtonItem *) rightButton {
5317 return [[progress_ running] boolValue] ? nil : [[[UIBarButtonItem alloc]
5318 initWithTitle:UCLocalize("CLOSE")
5319 style:UIBarButtonItemStylePlain
5321 action:@selector(close)
5325 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5326 UpdateExternalStatus(1);
5328 [progress_ setRunning:true];
5329 [self setTitle:title];
5330 // implicit updateProgress
5332 SHA1SumValue notifyconf; {
5334 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5337 MMap mmap(file, MMap::ReadOnly);
5339 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5340 notifyconf = sha1.Result();
5344 SHA1SumValue springlist; {
5346 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5349 MMap mmap(file, MMap::ReadOnly);
5351 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5352 springlist = sha1.Result();
5356 if (invocation != nil) {
5357 [invocation yieldToSelector:@selector(invoke)];
5358 [self setTitle:@"COMPLETE"];
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 if (!(notifyconf == sha1.Result()))
5376 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5379 MMap mmap(file, MMap::ReadOnly);
5381 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5382 if (!(springlist == sha1.Result()))
5388 if (RestartSubstrate_)
5392 RestartSubstrate_ = false;
5395 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5396 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5397 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5398 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5399 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5403 system("su -c /usr/bin/uicache mobile");
5406 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5408 [progress_ setRunning:false];
5409 [self updateProgress];
5411 [self applyRightButton];
5414 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5415 [progress_ addEvent:event];
5416 [self updateProgress];
5419 - (bool) isProgressCancelled {
5420 return cancel_ == 2;
5425 [self updateCancel];
5428 - (void) setCancellable:(bool)cancellable {
5429 unsigned cancel(cancel_);
5433 else if (cancel_ == 0)
5436 if (cancel != cancel_)
5437 [self updateCancel];
5440 - (void) setProgressCancellable:(NSNumber *)cancellable {
5441 [self setCancellable:[cancellable boolValue]];
5444 - (void) setProgressPercent:(NSNumber *)percent {
5445 [progress_ setPercent:[percent floatValue]];
5446 [self updateProgress];
5449 - (void) setProgressStatus:(NSDictionary *)status {
5450 if (status == nil) {
5451 [progress_ setCurrent:0];
5452 [progress_ setTotal:0];
5453 [progress_ setSpeed:0];
5455 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5457 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5458 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5459 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5462 [self updateProgress];
5468 /* Cell Content View {{{ */
5469 @protocol ContentDelegate
5470 - (void) drawContentRect:(CGRect)rect;
5473 @interface ContentView : UIView {
5474 _transient id<ContentDelegate> delegate_;
5479 @implementation ContentView
5481 - (id) initWithFrame:(CGRect)frame {
5482 if ((self = [super initWithFrame:frame]) != nil) {
5483 [self setNeedsDisplayOnBoundsChange:YES];
5487 - (void) setDelegate:(id<ContentDelegate>)delegate {
5488 delegate_ = delegate;
5491 - (void) drawRect:(CGRect)rect {
5492 [super drawRect:rect];
5493 [delegate_ drawContentRect:rect];
5498 /* Cydia TableView Cell {{{ */
5499 @interface CYTableViewCell : UITableViewCell {
5500 ContentView *content_;
5506 @implementation CYTableViewCell
5513 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5514 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5516 if (view == content_) {
5517 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5518 highlighted_ = highlighted;
5521 [super _updateHighlightColorsForView:view highlighted:highlighted];
5524 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5525 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5526 highlighted_ = selected;
5528 [super setSelected:selected animated:animated];
5529 [content_ setNeedsDisplay];
5535 /* Package Cell {{{ */
5536 @interface PackageCell : CYTableViewCell <
5541 NSString *description_;
5549 - (PackageCell *) init;
5550 - (void) setPackage:(Package *)package;
5552 - (void) drawContentRect:(CGRect)rect;
5556 @implementation PackageCell
5558 - (void) clearPackage {
5569 if (description_ != nil) {
5570 [description_ release];
5574 if (source_ != nil) {
5579 if (badge_ != nil) {
5584 if (placard_ != nil) {
5594 [self clearPackage];
5598 - (PackageCell *) init {
5599 CGRect frame(CGRectMake(0, 0, 320, 74));
5600 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5601 UIView *content([self contentView]);
5602 CGRect bounds([content bounds]);
5604 content_ = [[ContentView alloc] initWithFrame:bounds];
5605 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5606 [content addSubview:content_];
5608 [content_ setDelegate:self];
5609 [content_ setOpaque:YES];
5613 - (NSString *) accessibilityLabel {
5614 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5617 - (void) setPackage:(Package *)package {
5618 [self clearPackage];
5621 Source *source = [package source];
5623 icon_ = [[package icon] retain];
5624 name_ = [[package name] retain];
5627 description_ = [package longDescription];
5628 if (description_ == nil)
5629 description_ = [package shortDescription];
5630 if (description_ != nil)
5631 description_ = [description_ retain];
5633 commercial_ = [package isCommercial];
5635 package_ = [package retain];
5637 NSString *label = nil;
5638 bool trusted = false;
5640 if (source != nil) {
5641 label = [source label];
5642 trusted = [source trusted];
5643 } else if ([[package id] isEqualToString:@"firmware"])
5644 label = UCLocalize("APPLE");
5646 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5648 NSString *from(label);
5650 NSString *section = [package simpleSection];
5651 if (section != nil && ![section isEqualToString:label]) {
5652 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5653 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5656 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5657 source_ = [from retain];
5659 if (NSString *purpose = [package primaryPurpose])
5660 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5661 badge_ = [badge_ retain];
5666 if (NSString *mode = [package_ mode]) {
5667 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5668 color = RemovingColor_;
5669 //placard = @"removing";
5671 color = InstallingColor_;
5672 //placard = @"installing";
5675 // XXX: the removing/installing placards are not @2x
5678 color = [UIColor whiteColor];
5680 if ([package installed] != nil)
5681 placard = @"installed";
5686 [content_ setBackgroundColor:color];
5689 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5690 placard_ = [placard_ retain];
5692 [self setNeedsDisplay];
5693 [content_ setNeedsDisplay];
5696 - (void) drawContentRect:(CGRect)rect {
5697 bool highlighted(highlighted_);
5698 float width([self bounds].size.width);
5701 CGContextRef context(UIGraphicsGetCurrentContext());
5702 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5703 CGContextFillRect(context, rect);
5708 rect.size = [icon_ size];
5710 rect.size.width /= 2;
5711 rect.size.height /= 2;
5713 rect.origin.x = 25 - rect.size.width / 2;
5714 rect.origin.y = 25 - rect.size.height / 2;
5716 [icon_ drawInRect:rect];
5719 if (badge_ != nil) {
5721 rect.size = [badge_ size];
5723 rect.size.width /= 2;
5724 rect.size.height /= 2;
5726 rect.origin.x = 36 - rect.size.width / 2;
5727 rect.origin.y = 36 - rect.size.height / 2;
5729 [badge_ drawInRect:rect];
5736 UISetColor(commercial_ ? Purple_ : Black_);
5737 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5738 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5741 UISetColor(commercial_ ? Purplish_ : Gray_);
5742 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5744 if (placard_ != nil)
5745 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5750 /* Section Cell {{{ */
5751 @interface SectionCell : CYTableViewCell <
5763 - (void) setSection:(Section *)section editing:(BOOL)editing;
5767 @implementation SectionCell
5769 - (void) clearSection {
5770 if (basic_ != nil) {
5775 if (section_ != nil) {
5785 if (count_ != nil) {
5792 [self clearSection];
5798 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5799 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5800 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5801 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5802 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5804 UIView *content([self contentView]);
5805 CGRect bounds([content bounds]);
5807 content_ = [[ContentView alloc] initWithFrame:bounds];
5808 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5809 [content addSubview:content_];
5810 [content_ setBackgroundColor:[UIColor whiteColor]];
5812 [content_ setDelegate:self];
5816 - (void) onSwitch:(id)sender {
5817 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5818 if (metadata == nil) {
5819 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5820 [Sections_ setObject:metadata forKey:basic_];
5823 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5827 - (void) setSection:(Section *)section editing:(BOOL)editing {
5828 if (editing != editing_) {
5830 [switch_ removeFromSuperview];
5832 [self addSubview:switch_];
5836 [self clearSection];
5838 if (section == nil) {
5839 name_ = [UCLocalize("ALL_PACKAGES") retain];
5842 basic_ = [section name];
5844 basic_ = [basic_ retain];
5846 section_ = [section localized];
5847 if (section_ != nil)
5848 section_ = [section_ retain];
5850 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5851 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5854 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5857 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5858 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5860 [content_ setNeedsDisplay];
5863 - (void) setFrame:(CGRect)frame {
5864 [super setFrame:frame];
5866 CGRect rect([switch_ frame]);
5867 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5870 - (NSString *) accessibilityLabel {
5874 - (void) drawContentRect:(CGRect)rect {
5875 bool highlighted(highlighted_ && !editing_);
5877 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5882 float width(rect.size.width);
5888 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5890 CGSize size = [count_ sizeWithFont:Font14_];
5894 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5900 /* File Table {{{ */
5901 @interface FileTable : CYViewController <
5902 UITableViewDataSource,
5905 _transient Database *database_;
5908 NSMutableArray *files_;
5912 - (id) initWithDatabase:(Database *)database;
5913 - (void) setPackage:(Package *)package;
5917 @implementation FileTable
5920 [self releaseSubviews];
5929 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5930 return files_ == nil ? 0 : [files_ count];
5933 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5937 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5938 static NSString *reuseIdentifier = @"Cell";
5940 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5942 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5943 [cell setFont:[UIFont systemFontOfSize:16]];
5945 [cell setText:[files_ objectAtIndex:indexPath.row]];
5946 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5951 - (NSURL *) navigationURL {
5952 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5956 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5958 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5959 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5960 [list_ setRowHeight:24.0f];
5961 [list_ setDataSource:self];
5962 [list_ setDelegate:self];
5963 [[self view] addSubview:list_];
5966 - (void) viewDidLoad {
5967 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5970 - (void) releaseSubviews {
5975 - (id) initWithDatabase:(Database *)database {
5976 if ((self = [super init]) != nil) {
5977 database_ = database;
5979 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5983 - (void) setPackage:(Package *)package {
5984 if (package_ != nil) {
5985 [package_ autorelease];
5994 [files_ removeAllObjects];
5996 if (package != nil) {
5997 package_ = [package retain];
5998 name_ = [[package id] retain];
6000 if (NSArray *files = [package files])
6001 [files_ addObjectsFromArray:files];
6003 if ([files_ count] != 0) {
6004 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6005 [files_ removeObjectAtIndex:0];
6006 [files_ sortUsingSelector:@selector(compareByPath:)];
6008 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6009 [stack addObject:@"/"];
6011 for (int i(0), e([files_ count]); i != e; ++i) {
6012 NSString *file = [files_ objectAtIndex:i];
6013 while (![file hasPrefix:[stack lastObject]])
6014 [stack removeLastObject];
6015 NSString *directory = [stack lastObject];
6016 [stack addObject:[file stringByAppendingString:@"/"]];
6017 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6018 ([stack count] - 2) * 3, "",
6019 [file substringFromIndex:[directory length]]
6028 - (void) reloadData {
6031 [self setPackage:[database_ packageWithName:name_]];
6036 /* Package Controller {{{ */
6037 @interface CYPackageController : CYBrowserController <
6038 UIActionSheetDelegate
6040 _transient Database *database_;
6041 _H<Package> package_;
6044 _H<NSMutableArray> buttons_;
6045 _H<UIBarButtonItem> button_;
6048 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
6052 @implementation CYPackageController
6054 - (NSURL *) navigationURL {
6055 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6058 /* XXX: this is not safe at all... localization of /fail/ */
6059 - (void) _clickButtonWithName:(NSString *)name {
6060 if ([name isEqualToString:UCLocalize("CLEAR")])
6061 [delegate_ clearPackage:package_];
6062 else if ([name isEqualToString:UCLocalize("INSTALL")])
6063 [delegate_ installPackage:package_];
6064 else if ([name isEqualToString:UCLocalize("REINSTALL")])
6065 [delegate_ installPackage:package_];
6066 else if ([name isEqualToString:UCLocalize("REMOVE")])
6067 [delegate_ removePackage:package_];
6068 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6069 [delegate_ installPackage:package_];
6070 else _assert(false);
6073 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6074 NSString *context([sheet context]);
6076 if ([context isEqualToString:@"modify"]) {
6077 if (button != [sheet cancelButtonIndex]) {
6078 NSString *buttonName = [buttons_ objectAtIndex:button];
6079 [self _clickButtonWithName:buttonName];
6082 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6086 - (bool) _allowJavaScriptPanel {
6091 - (void) _customButtonClicked {
6092 int count([buttons_ count]);
6097 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6099 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6100 [buttons addObjectsFromArray:buttons_];
6102 UIActionSheet *sheet = [[[UIActionSheet alloc]
6105 cancelButtonTitle:nil
6106 destructiveButtonTitle:nil
6107 otherButtonTitles:nil
6110 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6112 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6113 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6115 [sheet setContext:@"modify"];
6117 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6121 // We don't want to allow non-commercial packages to do custom things to the install button,
6122 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6123 - (void) customButtonClicked {
6125 [super customButtonClicked];
6127 [self _customButtonClicked];
6130 - (void) reloadButtonClicked {
6131 // Don't reload a commerical package by tapping the loading button,
6132 // but if it's not an Install button, we should forward it on.
6133 if (![package_ uninstalled])
6134 [self _customButtonClicked];
6137 - (void) applyLoadingTitle {
6138 // Don't show "Loading" as the title. Ever.
6141 - (UIBarButtonItem *) rightButton {
6146 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
6147 if ((self = [super init]) != nil) {
6148 database_ = database;
6149 buttons_ = [NSMutableArray arrayWithCapacity:4];
6150 name_ = [NSString stringWithString:name];
6151 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
6155 - (void) reloadData {
6156 package_ = [database_ packageWithName:name_];
6158 [buttons_ removeAllObjects];
6160 if (package_ != nil) {
6161 [(Package *) package_ parse];
6163 commercial_ = [package_ isCommercial];
6165 if ([package_ mode] != nil)
6166 [buttons_ addObject:UCLocalize("CLEAR")];
6167 if ([package_ source] == nil);
6168 else if ([package_ upgradableAndEssential:NO])
6169 [buttons_ addObject:UCLocalize("UPGRADE")];
6170 else if ([package_ uninstalled])
6171 [buttons_ addObject:UCLocalize("INSTALL")];
6173 [buttons_ addObject:UCLocalize("REINSTALL")];
6174 if (![package_ uninstalled])
6175 [buttons_ addObject:UCLocalize("REMOVE")];
6179 switch ([buttons_ count]) {
6180 case 0: title = nil; break;
6181 case 1: title = [buttons_ objectAtIndex:0]; break;
6182 default: title = UCLocalize("MODIFY"); break;
6185 button_ = [[[UIBarButtonItem alloc]
6187 style:UIBarButtonItemStylePlain
6189 action:@selector(customButtonClicked)
6195 - (bool) isLoading {
6196 return commercial_ ? [super isLoading] : false;
6202 /* Package List Controller {{{ */
6203 @interface PackageListController : CYViewController <
6204 UITableViewDataSource,
6207 _transient Database *database_;
6209 NSMutableArray *packages_;
6210 NSMutableArray *sections_;
6212 NSMutableArray *index_;
6213 NSMutableDictionary *indices_;
6217 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6218 - (void) setDelegate:(id)delegate;
6219 - (void) resetCursor;
6223 @implementation PackageListController
6226 [packages_ release];
6227 [sections_ release];
6236 - (void) deselectWithAnimation:(BOOL)animated {
6237 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6240 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6241 CGRect base = [[self view] bounds];
6242 base.size.height -= bounds.size.height;
6243 base.origin = [list_ frame].origin;
6245 [UIView beginAnimations:nil context:NULL];
6246 [UIView setAnimationBeginsFromCurrentState:YES];
6247 [UIView setAnimationCurve:curve];
6248 [UIView setAnimationDuration:duration];
6249 [list_ setFrame:base];
6250 [UIView commitAnimations];
6253 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6254 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6257 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6258 [self resizeForKeyboardBounds:bounds duration:0];
6261 - (void) keyboardWillShow:(NSNotification *)notification {
6264 NSTimeInterval duration;
6265 UIViewAnimationCurve curve;
6266 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6267 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6268 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6269 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6271 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);
6272 UIViewController *base = self;
6273 while ([base parentViewController] != nil)
6274 base = [base parentViewController];
6275 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6276 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6278 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6281 - (void) keyboardWillHide:(NSNotification *)notification {
6282 NSTimeInterval duration;
6283 UIViewAnimationCurve curve;
6284 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6285 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6287 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6290 - (void) viewWillAppear:(BOOL)animated {
6291 [super viewWillAppear:animated];
6293 [self resizeForKeyboardBounds:CGRectZero];
6294 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6295 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6298 - (void) viewWillDisappear:(BOOL)animated {
6299 [super viewWillDisappear:animated];
6301 [self resizeForKeyboardBounds:CGRectZero];
6302 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6303 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6306 - (void) viewDidAppear:(BOOL)animated {
6307 [super viewDidAppear:animated];
6308 [self deselectWithAnimation:animated];
6311 - (void) didSelectPackage:(Package *)package {
6312 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6313 [view setDelegate:delegate_];
6314 [[self navigationController] pushViewController:view animated:YES];
6317 #if TryIndexedCollation
6318 + (BOOL) hasIndexedCollation {
6319 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6323 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6324 NSInteger count([sections_ count]);
6325 return count == 0 ? 1 : count;
6328 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6329 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6331 return [[sections_ objectAtIndex:section] name];
6334 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6335 if ([sections_ count] == 0)
6337 return [[sections_ objectAtIndex:section] count];
6340 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6341 @synchronized (database_) {
6342 if ([database_ era] != era_)
6345 Section *section([sections_ objectAtIndex:[path section]]);
6346 NSInteger row([path row]);
6347 Package *package([packages_ objectAtIndex:([section row] + row)]);
6348 return [[package retain] autorelease];
6351 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6352 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6354 cell = [[[PackageCell alloc] init] autorelease];
6355 [cell setPackage:[self packageAtIndexPath:path]];
6359 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6360 Package *package([self packageAtIndexPath:path]);
6361 package = [database_ packageWithName:[package id]];
6362 [self didSelectPackage:package];
6365 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6366 // XXX: is 20 the most optimal number here?
6367 return [packages_ count] > 20 ? index_ : nil;
6370 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6371 #if TryIndexedCollation
6372 if ([[self class] hasIndexedCollation]) {
6373 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6380 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6381 if ((self = [super init]) != nil) {
6382 database_ = database;
6383 title_ = [title copy];
6384 [[self navigationItem] setTitle:title_];
6386 #if TryIndexedCollation
6387 if ([[self class] hasIndexedCollation])
6388 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6391 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6393 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6395 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6396 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6398 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6399 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6400 [list_ setRowHeight:73];
6401 [[self view] addSubview:list_];
6403 [list_ setDataSource:self];
6404 [list_ setDelegate:self];
6408 - (void) setDelegate:(id)delegate {
6409 delegate_ = delegate;
6412 - (bool) hasPackage:(Package *)package {
6416 - (void) reloadData {
6419 era_ = [database_ era];
6420 NSArray *packages = [database_ packages];
6422 [packages_ removeAllObjects];
6423 [sections_ removeAllObjects];
6425 _profile(PackageTable$reloadData$Filter)
6426 for (Package *package in packages)
6427 if ([self hasPackage:package])
6428 [packages_ addObject:package];
6431 [indices_ removeAllObjects];
6433 Section *section = nil;
6435 #if TryIndexedCollation
6436 if ([[self class] hasIndexedCollation]) {
6437 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6438 NSArray *titles = [collation sectionIndexTitles];
6441 _profile(PackageTable$reloadData$Section)
6442 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6446 _profile(PackageTable$reloadData$Section$Package)
6447 package = [packages_ objectAtIndex:offset];
6448 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6451 while (secidx < index) {
6454 _profile(PackageTable$reloadData$Section$Allocate)
6455 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6458 _profile(PackageTable$reloadData$Section$Add)
6459 [sections_ addObject:section];
6463 [section addToCount];
6469 [index_ removeAllObjects];
6471 _profile(PackageTable$reloadData$Section)
6472 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6476 _profile(PackageTable$reloadData$Section$Package)
6477 package = [packages_ objectAtIndex:offset];
6478 index = [package index];
6481 if (section == nil || [section index] != index) {
6482 _profile(PackageTable$reloadData$Section$Allocate)
6483 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6486 [index_ addObject:[section name]];
6487 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6489 _profile(PackageTable$reloadData$Section$Add)
6490 [sections_ addObject:section];
6494 [section addToCount];
6499 _profile(PackageTable$reloadData$List)
6504 - (void) resetCursor {
6505 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6510 /* Filtered Package List Controller {{{ */
6511 @interface FilteredPackageListController : PackageListController {
6517 - (void) setObject:(id)object;
6518 - (void) setObject:(id)object forFilter:(SEL)filter;
6520 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6524 @implementation FilteredPackageListController
6532 - (void) setFilter:(SEL)filter {
6535 /* XXX: this is an unsafe optimization of doomy hell */
6536 Method method(class_getInstanceMethod([Package class], filter));
6537 _assert(method != NULL);
6538 imp_ = method_getImplementation(method);
6539 _assert(imp_ != NULL);
6542 - (void) setObject:(id)object {
6548 object_ = [object retain];
6551 - (void) setObject:(id)object forFilter:(SEL)filter {
6552 [self setFilter:filter];
6553 [self setObject:object];
6556 - (bool) hasPackage:(Package *)package {
6557 _profile(FilteredPackageTable$hasPackage)
6558 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6562 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6563 if ((self = [super initWithDatabase:database title:title]) != nil) {
6564 [self setFilter:filter];
6565 [self setObject:object];
6572 /* Home Controller {{{ */
6573 @interface HomeController : CYBrowserController {
6578 @implementation HomeController
6581 if ((self = [super init]) != nil) {
6582 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6586 - (NSURL *) navigationURL {
6587 return [NSURL URLWithString:@"cydia://home"];
6590 - (void) aboutButtonClicked {
6591 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6593 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6594 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6595 [alert setCancelButtonIndex:0];
6598 @"Copyright (C) 2008-2011\n"
6599 "Jay Freeman (saurik)\n"
6600 "saurik@saurik.com\n"
6601 "http://www.saurik.com/"
6607 - (void) viewDidLoad {
6608 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6609 initWithTitle:UCLocalize("ABOUT")
6610 style:UIBarButtonItemStylePlain
6612 action:@selector(aboutButtonClicked)
6618 /* Manage Controller {{{ */
6619 @interface ManageController : CYBrowserController {
6622 - (void) queueStatusDidChange;
6626 @implementation ManageController
6629 if ((self = [super init]) != nil) {
6630 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6634 - (NSURL *) navigationURL {
6635 return [NSURL URLWithString:@"cydia://manage"];
6638 - (void) viewDidLoad {
6639 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6640 initWithTitle:UCLocalize("SETTINGS")
6641 style:UIBarButtonItemStylePlain
6643 action:@selector(settingsButtonClicked)
6646 [self queueStatusDidChange];
6649 - (void) settingsButtonClicked {
6650 [delegate_ showSettings];
6654 - (void) queueButtonClicked {
6658 - (void) applyLoadingTitle {
6659 // Disable "Loading" title.
6662 - (void) applyRightButton {
6663 // Disable right button.
6667 - (void) queueStatusDidChange {
6669 if (!IsWildcat_ && Queuing_) {
6670 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6671 initWithTitle:UCLocalize("QUEUE")
6672 style:UIBarButtonItemStyleDone
6674 action:@selector(queueButtonClicked)
6677 [[self navigationItem] setRightBarButtonItem:nil];
6682 - (bool) isLoading {
6683 // Never show as loading.
6690 /* Refresh Bar {{{ */
6691 @interface RefreshBar : UINavigationBar {
6692 UIProgressIndicator *indicator_;
6693 UITextLabel *prompt_;
6694 UIProgressBar *progress_;
6695 UINavigationButton *cancel_;
6700 @implementation RefreshBar
6703 [indicator_ release];
6705 [progress_ release];
6710 - (void) positionViews {
6711 CGRect frame = [cancel_ frame];
6712 frame.size = [cancel_ sizeThatFits:frame.size];
6713 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6714 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6715 [cancel_ setFrame:frame];
6717 CGSize prgsize = {75, 100};
6719 [self frame].size.width - prgsize.width - 10,
6720 ([self frame].size.height - prgsize.height) / 2
6722 [progress_ setFrame:prgrect];
6724 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6725 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6726 CGRect indrect = {{indoffset, indoffset}, indsize};
6727 [indicator_ setFrame:indrect];
6729 CGSize prmsize = {215, indsize.height + 4};
6731 indoffset * 2 + indsize.width,
6732 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6734 [prompt_ setFrame:prmrect];
6737 - (void) setFrame:(CGRect)frame {
6738 [super setFrame:frame];
6739 [self positionViews];
6742 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6743 if ((self = [super initWithFrame:frame]) != nil) {
6744 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6746 [self setBarStyle:UIBarStyleBlack];
6748 UIBarStyle barstyle([self _barStyle:NO]);
6749 bool ugly(barstyle == UIBarStyleDefault);
6751 UIProgressIndicatorStyle style = ugly ?
6752 UIProgressIndicatorStyleMediumBrown :
6753 UIProgressIndicatorStyleMediumWhite;
6755 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6756 [indicator_ setStyle:style];
6757 [indicator_ startAnimation];
6758 [self addSubview:indicator_];
6760 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6761 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6762 [prompt_ setBackgroundColor:[UIColor clearColor]];
6763 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6764 [self addSubview:prompt_];
6766 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6767 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6768 [progress_ setStyle:0];
6769 [self addSubview:progress_];
6771 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6772 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6773 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6774 [cancel_ setBarStyle:barstyle];
6776 [self positionViews];
6780 - (void) setCancellable:(bool)cancellable {
6782 [self addSubview:cancel_];
6784 [cancel_ removeFromSuperview];
6788 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6789 [progress_ setProgress:0];
6793 [self setCancellable:NO];
6796 - (void) setPrompt:(NSString *)prompt {
6797 [prompt_ setText:prompt];
6800 - (void) setProgress:(float)progress {
6801 [progress_ setProgress:progress];
6807 @class CYNavigationController;
6809 /* Cydia Tab Bar Controller {{{ */
6810 @interface CYTabBarController : UITabBarController <
6811 UITabBarControllerDelegate,
6814 _transient Database *database_;
6815 RefreshBar *refreshbar_;
6819 // XXX: ok, "updatedelegate_"?...
6820 _transient NSObject<CydiaDelegate> *updatedelegate_;
6823 UIViewController *remembered_;
6824 _transient UIViewController *transient_;
6827 - (NSArray *) navigationURLCollection;
6828 - (void) dropBar:(BOOL)animated;
6829 - (void) beginUpdate;
6830 - (void) raiseBar:(BOOL)animated;
6835 @implementation CYTabBarController
6837 - (void) setUnselectedViewController:(UIViewController *)transient {
6838 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6839 if (transient != nil) {
6840 if (transient_ == nil)
6841 remembered_ = [[controllers objectAtIndex:0] retain];
6842 transient_ = transient;
6843 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6844 [controllers replaceObjectAtIndex:0 withObject:transient_];
6845 [self setSelectedIndex:0];
6846 [self setViewControllers:controllers];
6847 [self concealTabBarSelection];
6848 } else if (remembered_ != nil) {
6849 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6850 transient_ = transient;
6851 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6852 [remembered_ release];
6854 [self setViewControllers:controllers];
6855 [self revealTabBarSelection];
6859 - (UIViewController *) unselectedViewController {
6863 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6864 if ([self unselectedViewController])
6865 [self setUnselectedViewController:nil];
6868 - (NSArray *) navigationURLCollection {
6869 NSMutableArray *items([NSMutableArray array]);
6871 // XXX: Should this deal with transient view controllers?
6872 for (id navigation in [self viewControllers]) {
6873 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6875 [items addObject:stack];
6881 - (void) reloadData {
6882 for (CYViewController *controller in [self viewControllers])
6883 [controller reloadData];
6885 [(CYNavigationController *)[self unselectedViewController] reloadData];
6889 [refreshbar_ release];
6890 [[NSNotificationCenter defaultCenter] removeObserver:self];
6895 - (id) initWithDatabase:(Database *)database {
6896 if ((self = [super init]) != nil) {
6897 database_ = database;
6898 [self setDelegate:self];
6900 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6901 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6903 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6907 - (void) setUpdate:(NSDate *)date {
6911 - (void) beginUpdate {
6912 [refreshbar_ start];
6915 [updatedelegate_ retainNetworkActivityIndicator];
6919 detachNewThreadSelector:@selector(performUpdate)
6925 - (void) performUpdate { _pooled
6927 status.setDelegate(self);
6928 [database_ updateWithStatus:status];
6931 performSelectorOnMainThread:@selector(completeUpdate)
6937 - (void) stopUpdateWithSelector:(SEL)selector {
6939 [updatedelegate_ releaseNetworkActivityIndicator];
6941 [self raiseBar:YES];
6944 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6947 - (void) completeUpdate {
6950 [self stopUpdateWithSelector:@selector(reloadData)];
6953 - (void) cancelUpdate {
6954 [self stopUpdateWithSelector:@selector(updateData)];
6957 - (void) cancelPressed {
6958 [self cancelUpdate];
6965 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6966 [refreshbar_ setPrompt:[event compoundMessage]];
6969 - (bool) isProgressCancelled {
6973 - (void) setProgressCancellable:(NSNumber *)cancellable {
6974 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6977 - (void) setProgressPercent:(NSNumber *)percent {
6978 [refreshbar_ setProgress:[percent floatValue]];
6981 - (void) setProgressStatus:(NSDictionary *)status {
6983 [self setProgressPercent:[status objectForKey:@"Percent"]];
6986 - (void) setUpdateDelegate:(id)delegate {
6987 updatedelegate_ = delegate;
6990 - (CGFloat) statusBarHeight {
6991 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6992 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6994 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6998 - (UIView *) transitionView {
6999 if ([self respondsToSelector:@selector(_transitionView)])
7000 return [self _transitionView];
7002 return MSHookIvar<id>(self, "_viewControllerTransitionView");
7005 - (void) dropBar:(BOOL)animated {
7010 UIView *transition([self transitionView]);
7011 [[self view] addSubview:refreshbar_];
7013 CGRect barframe([refreshbar_ frame]);
7015 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
7016 barframe.origin.y = [self statusBarHeight];
7018 barframe.origin.y = 0;
7020 [refreshbar_ setFrame:barframe];
7023 [UIView beginAnimations:nil context:NULL];
7025 CGRect viewframe = [transition frame];
7026 viewframe.origin.y += barframe.size.height;
7027 viewframe.size.height -= barframe.size.height;
7028 [transition setFrame:viewframe];
7031 [UIView commitAnimations];
7033 // Ensure bar has the proper width for our view, it might have changed
7034 barframe.size.width = viewframe.size.width;
7035 [refreshbar_ setFrame:barframe];
7037 // XXX: fix Apple's layout bug
7038 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7041 - (void) raiseBar:(BOOL)animated {
7046 UIView *transition([self transitionView]);
7047 [refreshbar_ removeFromSuperview];
7049 CGRect barframe([refreshbar_ frame]);
7052 [UIView beginAnimations:nil context:NULL];
7054 CGRect viewframe = [transition frame];
7055 viewframe.origin.y -= barframe.size.height;
7056 viewframe.size.height += barframe.size.height;
7057 [transition setFrame:viewframe];
7060 [UIView commitAnimations];
7062 // XXX: fix Apple's layout bug
7063 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7067 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7068 // XXX: fix Apple's layout bug
7069 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7073 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7074 bool dropped(dropped_);
7079 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7084 // XXX: fix Apple's layout bug
7085 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7088 - (void) statusBarFrameChanged:(NSNotification *)notification {
7097 /* Cydia Navigation Controller {{{ */
7098 @interface CYNavigationController : UINavigationController {
7099 _transient Database *database_;
7100 _transient id<UINavigationControllerDelegate> delegate_;
7103 - (NSArray *) navigationURLCollection;
7104 - (id) initWithDatabase:(Database *)database;
7105 - (void) reloadData;
7110 @implementation CYNavigationController
7112 - (NSArray *) navigationURLCollection {
7113 NSMutableArray *stack([NSMutableArray array]);
7115 for (CYViewController *controller in [self viewControllers]) {
7116 NSString *url = [[controller navigationURL] absoluteString];
7118 [stack addObject:url];
7124 - (void) reloadData {
7125 for (CYViewController *page in [self viewControllers]) {
7126 // Only reload controllers that have already loaded.
7127 // This prevents a page from accidentally loading too
7128 // early if it hasn't been shown on the screen yet.
7129 if ([page hasLoaded])
7134 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
7135 delegate_ = delegate;
7138 - (id) initWithDatabase:(Database *)database {
7139 if ((self = [super init]) != nil) {
7140 database_ = database;
7147 /* Cydia:// Protocol {{{ */
7148 @interface CydiaURLProtocol : NSURLProtocol {
7153 @implementation CydiaURLProtocol
7155 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7156 NSURL *url([request URL]);
7160 NSString *scheme([[url scheme] lowercaseString]);
7161 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7163 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7169 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7173 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7174 id<NSURLProtocolClient> client([self client]);
7176 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7178 NSData *data(UIImagePNGRepresentation(icon));
7180 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7181 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7182 [client URLProtocol:self didLoadData:data];
7183 [client URLProtocolDidFinishLoading:self];
7187 - (void) startLoading {
7188 id<NSURLProtocolClient> client([self client]);
7189 NSURLRequest *request([self request]);
7191 NSURL *url([request URL]);
7192 NSString *href([url absoluteString]);
7193 NSString *scheme([[url scheme] lowercaseString]);
7197 if ([scheme isEqualToString:@"cydia"])
7198 path = [href substringFromIndex:8];
7199 else if ([scheme isEqualToString:@"about"])
7200 path = [href substringFromIndex:12];
7201 else _assert(false);
7203 NSRange slash([path rangeOfString:@"/"]);
7206 if (slash.location == NSNotFound) {
7210 command = [path substringToIndex:slash.location];
7211 path = [path substringFromIndex:(slash.location + 1)];
7214 Database *database([Database sharedInstance]);
7216 if ([command isEqualToString:@"package-icon"]) {
7219 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7220 Package *package([database packageWithName:path]);
7223 UIImage *icon([package icon]);
7224 [self _returnPNGWithImage:icon forRequest:request];
7225 } else if ([command isEqualToString:@"source-icon"]) {
7228 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7229 NSString *source(Simplify(path));
7230 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7232 icon = [UIImage applicationImageNamed:@"unknown.png"];
7233 [self _returnPNGWithImage:icon forRequest:request];
7234 } else if ([command isEqualToString:@"uikit-image"]) {
7237 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7238 UIImage *icon(_UIImageWithName(path));
7239 [self _returnPNGWithImage:icon forRequest:request];
7240 } else if ([command isEqualToString:@"section-icon"]) {
7243 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7244 NSString *section(Simplify(path));
7245 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7247 icon = [UIImage applicationImageNamed:@"unknown.png"];
7248 [self _returnPNGWithImage:icon forRequest:request];
7250 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7254 - (void) stopLoading {
7260 /* Section Controller {{{ */
7261 @interface SectionController : FilteredPackageListController {
7262 _H<NSString> section_;
7265 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7269 @implementation SectionController
7271 - (NSURL *) navigationURL {
7272 NSString *name = section_;
7276 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7279 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7282 title = UCLocalize("ALL_PACKAGES");
7283 else if (![name isEqual:@""])
7284 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7286 title = UCLocalize("NO_SECTION");
7288 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7295 /* Sections Controller {{{ */
7296 @interface SectionsController : CYViewController <
7297 UITableViewDataSource,
7300 _transient Database *database_;
7301 NSMutableArray *sections_;
7302 NSMutableArray *filtered_;
7306 - (id) initWithDatabase:(Database *)database;
7307 - (void) editButtonClicked;
7311 @implementation SectionsController
7314 [self releaseSubviews];
7315 [sections_ release];
7316 [filtered_ release];
7321 - (NSURL *) navigationURL {
7322 return [NSURL URLWithString:@"cydia://sections"];
7325 - (void) updateNavigationItem {
7326 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7327 if ([sections_ count] == 0) {
7328 [[self navigationItem] setRightBarButtonItem:nil];
7330 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7331 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7333 action:@selector(editButtonClicked)
7334 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7338 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7339 [super setEditing:editing animated:animated];
7344 [delegate_ updateData];
7346 [self updateNavigationItem];
7349 - (void) viewDidAppear:(BOOL)animated {
7350 [super viewDidAppear:animated];
7351 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7354 - (void) viewWillDisappear:(BOOL)animated {
7355 [super viewWillDisappear:animated];
7356 if ([self isEditing]) [self setEditing:NO];
7359 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7360 Section *section = nil;
7361 int index = [indexPath row];
7362 if (![self isEditing]) {
7365 section = [filtered_ objectAtIndex:index];
7367 section = [sections_ objectAtIndex:index];
7372 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7373 if ([self isEditing])
7374 return [sections_ count];
7376 return [filtered_ count] + 1;
7379 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7383 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7384 static NSString *reuseIdentifier = @"SectionCell";
7386 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7388 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7390 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7395 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7396 if ([self isEditing])
7399 Section *section = [self sectionAtIndexPath:indexPath];
7401 SectionController *controller = [[[SectionController alloc]
7402 initWithDatabase:database_
7403 section:[section name]
7405 [controller setDelegate:delegate_];
7407 [[self navigationController] pushViewController:controller animated:YES];
7411 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7413 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7414 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7415 [list_ setRowHeight:45.0f];
7416 [list_ setDataSource:self];
7417 [list_ setDelegate:self];
7418 [[self view] addSubview:list_];
7421 - (void) viewDidLoad {
7422 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7425 - (void) releaseSubviews {
7430 - (id) initWithDatabase:(Database *)database {
7431 if ((self = [super init]) != nil) {
7432 database_ = database;
7434 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7435 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7439 - (void) reloadData {
7442 NSArray *packages = [database_ packages];
7444 [sections_ removeAllObjects];
7445 [filtered_ removeAllObjects];
7447 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7450 for (Package *package in packages) {
7451 NSString *name([package section]);
7452 NSString *key(name == nil ? @"" : name);
7456 _profile(SectionsView$reloadData$Section)
7457 section = [sections objectForKey:key];
7458 if (section == nil) {
7459 _profile(SectionsView$reloadData$Section$Allocate)
7460 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7461 [sections setObject:section forKey:key];
7466 [section addToCount];
7468 _profile(SectionsView$reloadData$Filter)
7469 if (![package valid] || ![package visible])
7477 [sections_ addObjectsFromArray:[sections allValues]];
7479 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7481 for (Section *section in sections_) {
7482 size_t count([section row]);
7486 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7487 [section setCount:count];
7488 [filtered_ addObject:section];
7491 [self updateNavigationItem];
7496 - (void) editButtonClicked {
7497 [self setEditing:![self isEditing] animated:YES];
7503 /* Changes Controller {{{ */
7504 @interface ChangesController : CYViewController <
7505 UITableViewDataSource,
7508 _transient Database *database_;
7510 CFMutableArrayRef packages_;
7511 NSMutableArray *sections_;
7514 BOOL hasSentFirstLoad_;
7517 - (id) initWithDatabase:(Database *)database;
7521 @implementation ChangesController
7524 [self releaseSubviews];
7525 CFRelease(packages_);
7526 [sections_ release];
7531 - (NSURL *) navigationURL {
7532 return [NSURL URLWithString:@"cydia://changes"];
7535 - (void) viewWillAppear:(BOOL)animated {
7536 // Loads after it appears, so don't load beforehand.
7538 [super viewWillAppear:animated];
7541 - (void) viewDidAppear:(BOOL)animated {
7542 [super viewDidAppear:animated];
7544 if (!hasSentFirstLoad_) {
7545 hasSentFirstLoad_ = YES;
7546 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7548 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7552 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7553 NSInteger count([sections_ count]);
7554 return count == 0 ? 1 : count;
7557 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7558 if ([sections_ count] == 0)
7560 return [[sections_ objectAtIndex:section] name];
7563 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7564 if ([sections_ count] == 0)
7566 return [[sections_ objectAtIndex:section] count];
7569 - (Package *) packageAtIndex:(NSUInteger)index {
7570 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7573 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7574 @synchronized (database_) {
7575 if ([database_ era] != era_)
7578 NSUInteger sectionIndex([path section]);
7579 if (sectionIndex >= [sections_ count])
7581 Section *section([sections_ objectAtIndex:sectionIndex]);
7582 NSInteger row([path row]);
7583 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7586 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7587 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7589 cell = [[[PackageCell alloc] init] autorelease];
7590 [cell setPackage:[self packageAtIndexPath:path]];
7594 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7595 Package *package([self packageAtIndexPath:path]);
7596 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7597 [view setDelegate:delegate_];
7598 [[self navigationController] pushViewController:view animated:YES];
7602 - (void) refreshButtonClicked {
7603 [delegate_ beginUpdate];
7604 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7607 - (void) upgradeButtonClicked {
7608 [delegate_ distUpgrade];
7612 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7614 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7615 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7616 [list_ setRowHeight:73];
7617 [list_ setDataSource:self];
7618 [list_ setDelegate:self];
7619 [[self view] addSubview:list_];
7622 - (void) viewDidLoad {
7623 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7626 - (void) releaseSubviews {
7631 - (id) initWithDatabase:(Database *)database {
7632 if ((self = [super init]) != nil) {
7633 database_ = database;
7635 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7636 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7640 // this mostly works because reloadData (below) is @synchronized (database_)
7641 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7642 - (void) _reloadPackages:(NSArray *)packages {
7643 CFRelease(packages_);
7644 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7647 _profile(ChangesController$_reloadPackages$Filter)
7648 for (Package *package in packages)
7649 if ([package upgradableAndEssential:YES] || [package visible])
7650 CFArrayAppendValue(packages_, package);
7653 _profile(ChangesController$_reloadPackages$radixSort)
7654 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7659 - (void) reloadData {
7660 @synchronized (database_) {
7661 era_ = [database_ era];
7662 NSArray *packages = [database_ packages];
7664 [sections_ removeAllObjects];
7667 UIProgressHUD *hud([delegate_ addProgressHUD]);
7668 [hud setText:UCLocalize("LOADING")];
7669 //NSLog(@"HUD:%@::%@", delegate_, hud);
7670 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7671 [delegate_ removeProgressHUD:hud];
7673 [self _reloadPackages:packages];
7676 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7677 Section *ignored = nil;
7678 Section *section = nil;
7682 bool unseens = false;
7684 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7686 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7687 Package *package = [self packageAtIndex:offset];
7689 BOOL uae = [package upgradableAndEssential:YES];
7693 time_t seen([package seen]);
7695 if (section == nil || last != seen) {
7699 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7702 _profile(ChangesController$reloadData$Allocate)
7703 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7704 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7705 [sections_ addObject:section];
7709 [section addToCount];
7710 } else if ([package ignored]) {
7711 if (ignored == nil) {
7712 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7714 [ignored addToCount];
7717 [upgradable addToCount];
7722 CFRelease(formatter);
7725 Section *last = [sections_ lastObject];
7726 size_t count = [last count];
7727 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7728 [sections_ removeLastObject];
7731 if ([ignored count] != 0)
7732 [sections_ insertObject:ignored atIndex:0];
7734 [sections_ insertObject:upgradable atIndex:0];
7739 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7740 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7741 style:UIBarButtonItemStylePlain
7743 action:@selector(upgradeButtonClicked)
7746 if (![delegate_ updating])
7747 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7748 initWithTitle:UCLocalize("REFRESH")
7749 style:UIBarButtonItemStylePlain
7751 action:@selector(refreshButtonClicked)
7759 /* Search Controller {{{ */
7760 @interface SearchController : FilteredPackageListController <
7763 _H<UISearchBar> search_;
7767 - (id) initWithDatabase:(Database *)database;
7768 - (void) setSearchTerm:(NSString *)term;
7769 - (void) reloadData;
7773 @implementation SearchController
7776 [search_ setDelegate:nil];
7780 - (NSURL *) navigationURL {
7781 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7782 return [NSURL URLWithString:@"cydia://search"];
7784 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7787 - (void) setSearchTerm:(NSString *)searchTerm {
7788 [search_ setText:searchTerm];
7792 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7793 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7794 [search_ resignFirstResponder];
7798 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7799 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7803 - (id) initWithDatabase:(Database *)database {
7804 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7805 search_ = [[[UISearchBar alloc] init] autorelease];
7806 [search_ setDelegate:self];
7810 - (void) viewDidAppear:(BOOL)animated {
7811 [super viewDidAppear:animated];
7813 if (!searchloaded_) {
7814 searchloaded_ = YES;
7815 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7816 [search_ layoutSubviews];
7817 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7819 UITextField *textField;
7820 if ([search_ respondsToSelector:@selector(searchField)])
7821 textField = [search_ searchField];
7823 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7825 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7826 [textField setEnablesReturnKeyAutomatically:NO];
7827 [[self navigationItem] setTitleView:textField];
7831 - (void) reloadData {
7832 [self setObject:[search_ text]];
7837 - (void) didSelectPackage:(Package *)package {
7838 [search_ resignFirstResponder];
7839 [super didSelectPackage:package];
7844 /* Package Settings Controller {{{ */
7845 @interface PackageSettingsController : CYViewController <
7846 UITableViewDataSource,
7849 _transient Database *database_;
7852 UITableView *table_;
7853 UISwitch *subscribedSwitch_;
7854 UISwitch *ignoredSwitch_;
7855 UITableViewCell *subscribedCell_;
7856 UITableViewCell *ignoredCell_;
7859 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7863 @implementation PackageSettingsController
7866 [self releaseSubviews];
7873 - (NSURL *) navigationURL {
7874 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7877 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7878 if (package_ == nil)
7881 if ([package_ installed] == nil)
7887 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7888 if (package_ == nil)
7891 // both sections contain just one item right now.
7895 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7899 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7901 return UCLocalize("SHOW_ALL_CHANGES_EX");
7903 return UCLocalize("IGNORE_UPGRADES_EX");
7906 - (void) onSubscribed:(id)control {
7907 bool value([control isOn]);
7908 if (package_ == nil)
7910 if ([package_ setSubscribed:value])
7911 [delegate_ updateData];
7914 - (void) _updateIgnored {
7915 const char *package([name_ UTF8String]);
7916 bool on([ignoredSwitch_ isOn]);
7918 pid_t pid(ExecFork());
7920 FILE *dpkg(popen("dpkg --set-selections", "w"));
7921 fwrite(package, strlen(package), 1, dpkg);
7924 fwrite(" hold\n", 6, 1, dpkg);
7926 fwrite(" install\n", 9, 1, dpkg);
7936 int result(waitpid(pid, &status, 0));
7939 _assert(result == pid);
7945 - (void) onIgnored:(id)control {
7946 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7947 [invocation setTarget:self];
7948 [invocation setSelector:@selector(_updateIgnored)];
7950 [delegate_ reloadDataWithInvocation:invocation];
7953 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7954 if (package_ == nil)
7957 switch ([indexPath section]) {
7958 case 0: return subscribedCell_;
7959 case 1: return ignoredCell_;
7968 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7970 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7971 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7972 [table_ setDataSource:self];
7973 [table_ setDelegate:self];
7974 [[self view] addSubview:table_];
7976 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7977 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7978 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7980 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7981 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7982 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7984 subscribedCell_ = [[UITableViewCell alloc] init];
7985 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7986 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7987 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7989 ignoredCell_ = [[UITableViewCell alloc] init];
7990 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7991 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7992 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7995 - (void) viewDidLoad {
7996 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7999 - (void) releaseSubviews {
8000 [ignoredCell_ release];
8003 [subscribedCell_ release];
8004 subscribedCell_ = nil;
8009 [ignoredSwitch_ release];
8010 ignoredSwitch_ = nil;
8012 [subscribedSwitch_ release];
8013 subscribedSwitch_ = nil;
8016 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8017 if ((self = [super init]) != nil) {
8018 database_ = database;
8019 name_ = [package retain];
8023 - (void) reloadData {
8026 if (package_ != nil)
8027 [package_ autorelease];
8028 package_ = [database_ packageWithName:name_];
8030 if (package_ != nil) {
8031 package_ = [package_ retain];
8032 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8033 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8034 } // XXX: what now, G?
8036 [table_ reloadData];
8042 /* Installed Controller {{{ */
8043 @interface InstalledController : FilteredPackageListController {
8047 - (id) initWithDatabase:(Database *)database;
8049 - (void) updateRoleButton;
8050 - (void) queueStatusDidChange;
8054 @implementation InstalledController
8060 - (NSURL *) navigationURL {
8061 return [NSURL URLWithString:@"cydia://installed"];
8064 - (id) initWithDatabase:(Database *)database {
8065 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8066 [self updateRoleButton];
8067 [self queueStatusDidChange];
8072 - (void) queueButtonClicked {
8077 - (void) queueStatusDidChange {
8081 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8082 initWithTitle:UCLocalize("QUEUE")
8083 style:UIBarButtonItemStyleDone
8085 action:@selector(queueButtonClicked)
8088 [[self navigationItem] setLeftBarButtonItem:nil];
8094 - (void) updateRoleButton {
8095 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8096 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8097 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8098 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8100 action:@selector(roleButtonClicked)
8104 - (void) roleButtonClicked {
8105 [self setObject:[NSNumber numberWithBool:expert_]];
8109 [self updateRoleButton];
8115 /* Source Cell {{{ */
8116 @interface SourceCell : CYTableViewCell <
8124 - (void) setSource:(Source *)source;
8128 @implementation SourceCell
8130 - (void) clearSource {
8140 - (void) setSource:(Source *)source {
8144 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
8146 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8147 icon_ = [icon_ retain];
8149 origin_ = [[source name] retain];
8150 label_ = [[source uri] retain];
8152 [content_ setNeedsDisplay];
8160 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8161 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8162 UIView *content([self contentView]);
8163 CGRect bounds([content bounds]);
8165 content_ = [[ContentView alloc] initWithFrame:bounds];
8166 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8167 [content_ setBackgroundColor:[UIColor whiteColor]];
8168 [content addSubview:content_];
8170 [content_ setDelegate:self];
8171 [content_ setOpaque:YES];
8175 - (NSString *) accessibilityLabel {
8179 - (void) drawContentRect:(CGRect)rect {
8180 bool highlighted(highlighted_);
8181 float width(rect.size.width);
8184 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8191 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8195 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8200 /* Source Controller {{{ */
8201 @interface SourceController : FilteredPackageListController {
8202 _transient Source *source_;
8206 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8210 @implementation SourceController
8212 - (NSURL *) navigationURL {
8213 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8216 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8217 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8219 key_ = [[source key] retain];
8223 - (void) reloadData {
8224 source_ = [database_ sourceWithKey:key_];
8226 key_ = [[source_ key] retain];
8227 [self setObject:source_];
8228 [[self navigationItem] setTitle:[source_ label]];
8235 /* Sources Controller {{{ */
8236 @interface SourcesController : CYViewController <
8237 UITableViewDataSource,
8240 _transient Database *database_;
8242 NSMutableArray *sources_;
8246 UIProgressHUD *hud_;
8249 //NSURLConnection *installer_;
8250 NSURLConnection *trivial_;
8251 NSURLConnection *trivial_bz2_;
8252 NSURLConnection *trivial_gz_;
8253 //NSURLConnection *automatic_;
8258 - (id) initWithDatabase:(Database *)database;
8259 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8263 @implementation SourcesController
8265 - (void) _releaseConnection:(NSURLConnection *)connection {
8266 if (connection != nil) {
8267 [connection cancel];
8268 //[connection setDelegate:nil];
8269 [connection release];
8274 [self releaseSubviews];
8280 //[self _releaseConnection:installer_];
8281 [self _releaseConnection:trivial_];
8282 [self _releaseConnection:trivial_gz_];
8283 [self _releaseConnection:trivial_bz2_];
8284 //[self _releaseConnection:automatic_];
8290 - (NSURL *) navigationURL {
8291 return [NSURL URLWithString:@"cydia://sources"];
8294 - (void) viewDidAppear:(BOOL)animated {
8295 [super viewDidAppear:animated];
8296 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8299 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8300 return offset_ == 0 ? 1 : 2;
8303 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8304 switch (section + (offset_ == 0 ? 1 : 0)) {
8305 case 0: return UCLocalize("ENTERED_BY_USER");
8306 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8312 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8313 int count = [sources_ count];
8315 case 0: return (offset_ == 0 ? count : offset_);
8316 case 1: return count - offset_;
8322 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8324 switch (indexPath.section) {
8325 case 0: idx = indexPath.row; break;
8326 case 1: idx = indexPath.row + offset_; break;
8330 return [sources_ objectAtIndex:idx];
8333 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8334 static NSString *cellIdentifier = @"SourceCell";
8336 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8337 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8338 [cell setSource:[self sourceAtIndexPath:indexPath]];
8339 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8344 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8345 Source *source = [self sourceAtIndexPath:indexPath];
8347 SourceController *controller = [[[SourceController alloc]
8348 initWithDatabase:database_
8352 [controller setDelegate:delegate_];
8354 [[self navigationController] pushViewController:controller animated:YES];
8357 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8358 Source *source = [self sourceAtIndexPath:indexPath];
8359 return [source record] != nil;
8362 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8363 Source *source = [self sourceAtIndexPath:indexPath];
8364 [Sources_ removeObjectForKey:[source key]];
8365 [delegate_ syncData];
8369 [delegate_ addTrivialSource:href_];
8370 [delegate_ syncData];
8373 - (NSString *) getWarning {
8374 NSString *href(href_);
8375 NSRange colon([href rangeOfString:@"://"]);
8376 if (colon.location != NSNotFound)
8377 href = [href substringFromIndex:(colon.location + 3)];
8378 href = [href stringByAddingPercentEscapes];
8379 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8380 href = [href stringByCachingURLWithCurrentCDN];
8382 NSURL *url([NSURL URLWithString:href]);
8384 NSStringEncoding encoding;
8385 NSError *error(nil);
8387 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8388 return [warning length] == 0 ? nil : warning;
8392 - (void) _endConnection:(NSURLConnection *)connection {
8393 // XXX: the memory management in this method is horribly awkward
8395 NSURLConnection **field = NULL;
8396 if (connection == trivial_)
8398 else if (connection == trivial_bz2_)
8399 field = &trivial_bz2_;
8400 else if (connection == trivial_gz_)
8401 field = &trivial_gz_;
8402 _assert(field != NULL);
8403 [connection release];
8408 trivial_bz2_ == nil &&
8414 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8417 UIAlertView *alert = [[[UIAlertView alloc]
8418 initWithTitle:UCLocalize("SOURCE_WARNING")
8421 cancelButtonTitle:UCLocalize("CANCEL")
8423 UCLocalize("ADD_ANYWAY"),
8427 [alert setContext:@"warning"];
8428 [alert setNumberOfRows:1];
8432 } else if (error_ != nil) {
8433 UIAlertView *alert = [[[UIAlertView alloc]
8434 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8435 message:[error_ localizedDescription]
8437 cancelButtonTitle:UCLocalize("OK")
8438 otherButtonTitles:nil
8441 [alert setContext:@"urlerror"];
8444 UIAlertView *alert = [[[UIAlertView alloc]
8445 initWithTitle:UCLocalize("NOT_REPOSITORY")
8446 message:UCLocalize("NOT_REPOSITORY_EX")
8448 cancelButtonTitle:UCLocalize("OK")
8449 otherButtonTitles:nil
8452 [alert setContext:@"trivial"];
8456 [delegate_ releaseNetworkActivityIndicator];
8458 [delegate_ removeProgressHUD:hud_];
8467 if (error_ != nil) {
8474 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8475 switch ([response statusCode]) {
8481 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8482 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8484 error_ = [error retain];
8485 [self _endConnection:connection];
8488 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8489 [self _endConnection:connection];
8492 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8493 NSMutableURLRequest *request = [NSMutableURLRequest
8494 requestWithURL:[NSURL URLWithString:href]
8495 cachePolicy:NSURLRequestUseProtocolCachePolicy
8496 timeoutInterval:120.0
8499 [request setHTTPMethod:method];
8501 if (Machine_ != NULL)
8502 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8503 if (UniqueID_ != nil)
8504 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8506 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8509 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8510 NSString *context([alert context]);
8512 if ([context isEqualToString:@"source"]) {
8515 NSString *href = [[alert textField] text];
8517 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8519 if (![href hasSuffix:@"/"])
8520 href_ = [href stringByAppendingString:@"/"];
8523 href_ = [href_ retain];
8525 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8526 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8527 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8528 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8532 // XXX: this is stupid
8533 hud_ = [[delegate_ addProgressHUD] retain];
8534 [hud_ setText:UCLocalize("VERIFYING_URL")];
8535 [delegate_ retainNetworkActivityIndicator];
8544 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8545 } else if ([context isEqualToString:@"trivial"])
8546 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8547 else if ([context isEqualToString:@"urlerror"])
8548 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8549 else if ([context isEqualToString:@"warning"]) {
8564 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8569 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8571 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8572 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8573 [list_ setRowHeight:56];
8574 [list_ setDataSource:self];
8575 [list_ setDelegate:self];
8576 [[self view] addSubview:list_];
8579 - (void) viewDidLoad {
8580 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8581 [self updateButtonsForEditingStatus:NO animated:NO];
8584 - (void) releaseSubviews {
8589 - (id) initWithDatabase:(Database *)database {
8590 if ((self = [super init]) != nil) {
8591 database_ = database;
8592 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8596 - (void) reloadData {
8600 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8603 [sources_ removeAllObjects];
8604 [sources_ addObjectsFromArray:[database_ sources]];
8606 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8609 int count([sources_ count]);
8611 for (int i = 0; i != count; i++) {
8612 if ([[sources_ objectAtIndex:i] record] == nil)
8617 [list_ setEditing:NO];
8618 [self updateButtonsForEditingStatus:NO animated:NO];
8622 - (void) showAddSourcePrompt {
8623 UIAlertView *alert = [[[UIAlertView alloc]
8624 initWithTitle:UCLocalize("ENTER_APT_URL")
8627 cancelButtonTitle:UCLocalize("CANCEL")
8629 UCLocalize("ADD_SOURCE"),
8633 [alert setContext:@"source"];
8634 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8636 [alert setNumberOfRows:1];
8637 [alert addTextFieldWithValue:@"http://" label:@""];
8639 UITextInputTraits *traits = [[alert textField] textInputTraits];
8640 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8641 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8642 [traits setKeyboardType:UIKeyboardTypeURL];
8643 // XXX: UIReturnKeyDone
8644 [traits setReturnKeyType:UIReturnKeyNext];
8649 - (void) addButtonClicked {
8650 [self showAddSourcePrompt];
8653 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8654 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8655 initWithTitle:UCLocalize("ADD")
8656 style:UIBarButtonItemStylePlain
8658 action:@selector(addButtonClicked)
8659 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8661 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8662 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8663 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8665 action:@selector(editButtonClicked)
8666 ] autorelease] animated:animated];
8668 if (IsWildcat_ && !editing)
8669 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8670 initWithTitle:UCLocalize("SETTINGS")
8671 style:UIBarButtonItemStylePlain
8673 action:@selector(settingsButtonClicked)
8677 - (void) settingsButtonClicked {
8678 [delegate_ showSettings];
8681 - (void) editButtonClicked {
8682 [list_ setEditing:![list_ isEditing] animated:YES];
8684 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8690 /* Settings Controller {{{ */
8691 @interface SettingsController : CYViewController <
8692 UITableViewDataSource,
8695 _transient Database *database_;
8696 // XXX: ok, "roledelegate_"?...
8697 _transient id roledelegate_;
8698 UITableView *table_;
8699 UISegmentedControl *segment_;
8703 - (void) showDoneButton;
8704 - (void) resizeSegmentedControl;
8708 @implementation SettingsController
8711 [self releaseSubviews];
8717 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8719 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8720 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8721 [table_ setDelegate:self];
8722 [table_ setDataSource:self];
8723 [[self view] addSubview:table_];
8725 NSArray *items = [NSArray arrayWithObjects:
8727 UCLocalize("HACKER"),
8728 UCLocalize("DEVELOPER"),
8730 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8731 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8732 [container_ addSubview:segment_];
8735 - (void) viewDidLoad {
8736 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8739 if ([Role_ isEqualToString:@"User"]) index = 0;
8740 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8741 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8743 [segment_ setSelectedSegmentIndex:index];
8744 [self showDoneButton];
8747 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8748 [self resizeSegmentedControl];
8751 - (void) releaseSubviews {
8758 [container_ release];
8762 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8763 if ((self = [super init]) != nil) {
8764 database_ = database;
8765 roledelegate_ = delegate;
8769 - (void) resizeSegmentedControl {
8770 CGFloat width = [[self view] frame].size.width;
8771 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8774 - (void) viewWillAppear:(BOOL)animated {
8775 [super viewWillAppear:animated];
8777 [self resizeSegmentedControl];
8780 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8781 [self resizeSegmentedControl];
8784 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8785 [self resizeSegmentedControl];
8789 NSString *role(nil);
8791 switch ([segment_ selectedSegmentIndex]) {
8792 case 0: role = @"User"; break;
8793 case 1: role = @"Hacker"; break;
8794 case 2: role = @"Developer"; break;
8799 if (![role isEqualToString:Role_]) {
8800 bool rolling(Role_ == nil);
8803 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8807 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8811 [roledelegate_ loadData];
8813 [roledelegate_ updateData];
8817 - (void) segmentChanged:(UISegmentedControl *)control {
8818 [self showDoneButton];
8821 - (void) saveAndClose {
8824 [[self navigationItem] setRightBarButtonItem:nil];
8825 [[self navigationController] dismissModalViewControllerAnimated:YES];
8828 - (void) doneButtonClicked {
8829 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8830 [spinner startAnimating];
8831 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8832 [[self navigationItem] setRightBarButtonItem:spinItem];
8834 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8837 - (void) showDoneButton {
8838 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8839 initWithTitle:UCLocalize("DONE")
8840 style:UIBarButtonItemStyleDone
8842 action:@selector(doneButtonClicked)
8843 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8846 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8847 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8851 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8855 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8856 return nil; // This method is required by the protocol.
8859 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8861 return UCLocalize("ROLE_EX");
8863 return [NSString stringWithFormat:
8864 @"%@: %@\n%@: %@\n%@: %@",
8865 UCLocalize("USER"), UCLocalize("USER_EX"),
8866 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8867 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8872 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8873 return section == 3 ? 44.0f : 0;
8876 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8877 return section == 3 ? container_ : nil;
8880 - (void) reloadData {
8882 [table_ reloadData];
8887 /* Stash Controller {{{ */
8888 @interface StashController : CYViewController {
8889 UIActivityIndicatorView *spinner_;
8896 @implementation StashController
8899 [self releaseSubviews];
8905 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8906 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8908 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8909 CGRect spinrect = [spinner_ frame];
8910 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8911 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8912 [spinner_ setFrame:spinrect];
8913 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8914 [[self view] addSubview:spinner_];
8915 [spinner_ startAnimating];
8918 captrect.size.width = [[self view] frame].size.width;
8919 captrect.size.height = 40.0f;
8920 captrect.origin.x = 0;
8921 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8922 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8923 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8924 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8925 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8926 [caption_ setTextColor:[UIColor whiteColor]];
8927 [caption_ setBackgroundColor:[UIColor clearColor]];
8928 [caption_ setShadowColor:[UIColor blackColor]];
8929 [caption_ setTextAlignment:UITextAlignmentCenter];
8930 [[self view] addSubview:caption_];
8933 statusrect.size.width = [[self view] frame].size.width;
8934 statusrect.size.height = 30.0f;
8935 statusrect.origin.x = 0;
8936 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8937 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8938 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8939 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8940 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8941 [status_ setTextColor:[UIColor whiteColor]];
8942 [status_ setBackgroundColor:[UIColor clearColor]];
8943 [status_ setShadowColor:[UIColor blackColor]];
8944 [status_ setTextAlignment:UITextAlignmentCenter];
8945 [[self view] addSubview:status_];
8948 - (void) releaseSubviews {
8962 @interface Cydia : UIApplication <
8963 ConfirmationControllerDelegate,
8966 UINavigationControllerDelegate,
8967 UITabBarControllerDelegate
8969 // XXX: evaluate all fields for _transient
8972 CYTabBarController *tabbar_;
8973 CYEmulatedLoadingController *emulated_;
8975 NSMutableArray *essential_;
8976 NSMutableArray *broken_;
8978 Database *database_;
8985 StashController *stash_;
8994 @implementation Cydia
8996 - (void) beginUpdate {
8997 [tabbar_ beginUpdate];
9001 return [tabbar_ updating];
9005 if ([broken_ count] != 0) {
9006 int count = [broken_ count];
9008 UIAlertView *alert = [[[UIAlertView alloc]
9009 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9010 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9012 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
9014 UCLocalize("TEMPORARY_IGNORE"),
9018 [alert setContext:@"fixhalf"];
9019 [alert setNumberOfRows:2];
9021 } else if (!Ignored_ && [essential_ count] != 0) {
9022 int count = [essential_ count];
9024 UIAlertView *alert = [[[UIAlertView alloc]
9025 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9026 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9028 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9030 UCLocalize("UPGRADE_ESSENTIAL"),
9031 UCLocalize("COMPLETE_UPGRADE"),
9035 [alert setContext:@"upgrade"];
9040 - (void) _saveConfig {
9046 NSString *error(nil);
9048 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9050 NSError *error(nil);
9051 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9052 NSLog(@"failure to save metadata data: %@", error);
9057 NSLog(@"failure to serialize metadata: %@", error);
9062 // Navigation controller for the queuing badge.
9063 - (CYNavigationController *) queueNavigationController {
9064 NSArray *controllers = [tabbar_ viewControllers];
9065 return [controllers objectAtIndex:3];
9068 - (void) _updateData {
9071 [tabbar_ reloadData];
9073 CYNavigationController *navigation = [self queueNavigationController];
9075 id queuedelegate = nil;
9076 if ([[navigation viewControllers] count] > 0)
9077 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9079 [queuedelegate queueStatusDidChange];
9080 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9083 - (void) _refreshIfPossible:(NSDate *)update {
9084 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9086 bool recently = false;
9087 if (update != nil) {
9088 NSTimeInterval interval([update timeIntervalSinceNow]);
9089 if (interval <= 0 && interval > -(15*60))
9093 // Don't automatic refresh if:
9094 // - We already refreshed recently.
9095 // - We already auto-refreshed this launch.
9096 // - Auto-refresh is disabled.
9097 if (recently || loaded_ || ManualRefresh) {
9098 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9100 // If we are cancelling, we need to make sure it knows it's already loaded.
9104 // We are going to load, so remember that.
9108 SCNetworkReachabilityFlags flags; {
9109 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9110 SCNetworkReachabilityGetFlags(reachability, &flags);
9111 CFRelease(reachability);
9114 // XXX: this elaborate mess is what Apple is using to determine this? :(
9115 // XXX: do we care if the user has to intervene? maybe that's ok?
9117 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9118 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9119 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9120 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9121 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9122 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9126 // If we can reach the server, auto-refresh!
9128 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9133 - (void) refreshIfPossible {
9134 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9137 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
9138 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9139 [hud setText:UCLocalize("RELOADING_DATA")];
9141 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9144 [self removeProgressHUD:hud];
9148 [essential_ removeAllObjects];
9149 [broken_ removeAllObjects];
9151 NSArray *packages([database_ packages]);
9152 for (Package *package in packages) {
9154 [broken_ addObject:package];
9155 if ([package upgradableAndEssential:NO]) {
9156 if ([package essential])
9157 [essential_ addObject:package];
9162 NSLog(@"changes:#%u", changes);
9164 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9167 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9168 [changesItem setBadgeValue:badge];
9169 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9170 [self setApplicationIconBadgeNumber:changes];
9173 [changesItem setBadgeValue:nil];
9174 [changesItem setAnimatedBadge:NO];
9175 [self setApplicationIconBadgeNumber:0];
9180 [self refreshIfPossible];
9183 - (void) updateData {
9192 @synchronized (self) {
9193 [self _reloadDataWithInvocation:nil];
9197 - (void) disemulate {
9198 if (emulated_ == nil)
9201 [window_ addSubview:[tabbar_ view]];
9202 [[emulated_ view] removeFromSuperview];
9203 [emulated_ release];
9205 [window_ setUserInteractionEnabled:YES];
9208 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9209 UINavigationController *navigation([[[CYNavigationController alloc] initWithRootViewController:controller] autorelease]);
9211 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9213 UIViewController *parent;
9214 if (emulated_ == nil)
9223 [parent presentModalViewController:navigation animated:YES];
9226 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9227 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9229 if (navigation != nil)
9230 [navigation pushViewController:progress animated:YES];
9232 [self presentModalViewController:progress force:YES];
9234 [progress invoke:invocation withTitle:title];
9238 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9239 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9242 - (void) repairWithInvocation:(NSInvocation *)invocation {
9244 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9248 - (void) repairWithSelector:(SEL)selector {
9249 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9255 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
9256 _assert(file != NULL);
9258 for (NSString *key in [Sources_ allKeys]) {
9259 NSDictionary *source([Sources_ objectForKey:key]);
9261 fprintf(file, "%s %s %s\n",
9262 [[source objectForKey:@"Type"] UTF8String],
9263 [[source objectForKey:@"URI"] UTF8String],
9264 [[source objectForKey:@"Distribution"] UTF8String]
9270 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9275 - (void) addTrivialSource:(NSString *)href {
9276 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
9279 @"./", @"Distribution",
9280 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
9285 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9286 @synchronized (self) {
9287 [self _reloadDataWithInvocation:invocation];
9291 - (void) reloadData {
9292 [self reloadDataWithInvocation:nil];
9296 pkgProblemResolver *resolver = [database_ resolver];
9298 resolver->InstallProtect();
9299 if (!resolver->Resolve(true))
9304 // XXX: this is a really crappy way of doing this.
9305 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9306 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9307 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9308 if ([tabbar_ updating])
9309 [tabbar_ cancelUpdate];
9311 if (![database_ prepare])
9314 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9315 [page setDelegate:self];
9316 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
9317 [confirm_ setDelegate:self];
9320 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9321 [tabbar_ presentModalViewController:confirm_ animated:YES];
9327 @synchronized (self) {
9332 - (void) clearPackage:(Package *)package {
9333 @synchronized (self) {
9340 - (void) installPackages:(NSArray *)packages {
9341 @synchronized (self) {
9342 for (Package *package in packages)
9349 - (void) installPackage:(Package *)package {
9350 @synchronized (self) {
9357 - (void) removePackage:(Package *)package {
9358 @synchronized (self) {
9365 - (void) distUpgrade {
9366 @synchronized (self) {
9367 if (![database_ upgrade])
9373 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9376 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
9381 - (void) showSettings {
9382 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9383 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9385 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9386 [tabbar_ presentModalViewController:nav animated:YES];
9389 - (void) retainNetworkActivityIndicator {
9390 if (activity_++ == 0)
9391 [self setNetworkActivityIndicatorVisible:YES];
9394 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9398 - (void) releaseNetworkActivityIndicator {
9399 if (--activity_ == 0)
9400 [self setNetworkActivityIndicatorVisible:NO];
9403 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9408 - (void) cancelAndClear:(bool)clear {
9409 @synchronized (self) {
9421 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9422 NSString *context([alert context]);
9424 if ([context isEqualToString:@"conffile"]) {
9425 FILE *input = [database_ input];
9426 if (button == [alert cancelButtonIndex])
9427 fprintf(input, "N\n");
9428 else if (button == [alert firstOtherButtonIndex])
9429 fprintf(input, "Y\n");
9432 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9433 } else if ([context isEqualToString:@"fixhalf"]) {
9434 if (button == [alert cancelButtonIndex]) {
9435 @synchronized (self) {
9436 for (Package *broken in broken_) {
9439 NSString *id = [broken id];
9440 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9441 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9442 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9443 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9449 } else if (button == [alert firstOtherButtonIndex]) {
9450 [broken_ removeAllObjects];
9454 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9455 } else if ([context isEqualToString:@"upgrade"]) {
9456 if (button == [alert firstOtherButtonIndex]) {
9457 @synchronized (self) {
9458 for (Package *essential in essential_)
9459 [essential install];
9464 } else if (button == [alert firstOtherButtonIndex] + 1) {
9466 } else if (button == [alert cancelButtonIndex]) {
9470 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9474 - (void) system:(NSString *)command { _pooled
9476 system([command UTF8String]);
9480 - (void) applicationWillSuspend {
9482 [super applicationWillSuspend];
9485 - (BOOL) isSafeToSuspend {
9488 NSLog(@"isSafeToSuspend: locked_ != 0");
9493 // Use external process status API internally.
9494 // This is probably a really bad idea.
9495 // XXX: what is the point of this? does this solve anything at all?
9496 uint64_t status = 0;
9498 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9499 notify_get_state(notify_token, &status);
9500 notify_cancel(notify_token);
9505 NSLog(@"isSafeToSuspend: status != 0");
9511 NSLog(@"isSafeToSuspend: -> true");
9516 - (void) applicationSuspend:(__GSEvent *)event {
9517 if ([self isSafeToSuspend])
9518 [super applicationSuspend:event];
9521 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9522 if ([self isSafeToSuspend])
9523 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9526 - (void) _setSuspended:(BOOL)value {
9527 if ([self isSafeToSuspend])
9528 [super _setSuspended:value];
9531 - (UIProgressHUD *) addProgressHUD {
9532 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9533 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9535 [window_ setUserInteractionEnabled:NO];
9538 UIViewController *target = tabbar_;
9539 while ([target modalViewController] != nil) target = [target modalViewController];
9540 [[target view] addSubview:hud];
9546 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9548 [hud removeFromSuperview];
9549 [window_ setUserInteractionEnabled:YES];
9553 - (CYViewController *) pageForPackage:(NSString *)name {
9554 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9557 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9558 NSString *scheme([[url scheme] lowercaseString]);
9559 if ([[url absoluteString] length] <= [scheme length] + 3)
9561 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9562 NSArray *components([path pathComponents]);
9564 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9565 return [self pageForPackage:[components objectAtIndex:1]];
9567 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9570 NSString *base([components objectAtIndex:0]);
9572 CYViewController *controller = nil;
9574 if ([base isEqualToString:@"url"]) {
9575 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9576 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9577 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9578 } else if (!external && [components count] == 1) {
9579 if ([base isEqualToString:@"manage"]) {
9580 controller = [[[ManageController alloc] init] autorelease];
9583 if ([base isEqualToString:@"sources"]) {
9584 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9587 if ([base isEqualToString:@"home"]) {
9588 controller = [[[HomeController alloc] init] autorelease];
9591 if ([base isEqualToString:@"sections"]) {
9592 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9595 if ([base isEqualToString:@"search"]) {
9596 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9599 if ([base isEqualToString:@"changes"]) {
9600 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9603 if ([base isEqualToString:@"installed"]) {
9604 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9606 } else if ([components count] == 2) {
9607 NSString *argument = [components objectAtIndex:1];
9609 if ([base isEqualToString:@"package"]) {
9610 controller = [self pageForPackage:argument];
9613 if (!external && [base isEqualToString:@"search"]) {
9614 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9615 [(SearchController *)controller setSearchTerm:argument];
9618 if (!external && [base isEqualToString:@"sections"]) {
9619 if ([argument isEqualToString:@"all"])
9621 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9624 if (!external && [base isEqualToString:@"sources"]) {
9625 if ([argument isEqualToString:@"add"]) {
9626 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9627 [(SourcesController *)controller showAddSourcePrompt];
9629 Source *source = [database_ sourceWithKey:argument];
9630 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9634 if (!external && [base isEqualToString:@"launch"]) {
9635 [self launchApplicationWithIdentifier:argument suspended:NO];
9638 } else if (!external && [components count] == 3) {
9639 NSString *arg1 = [components objectAtIndex:1];
9640 NSString *arg2 = [components objectAtIndex:2];
9642 if ([base isEqualToString:@"package"]) {
9643 if ([arg2 isEqualToString:@"settings"]) {
9644 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9645 } else if ([arg2 isEqualToString:@"files"]) {
9646 if (Package *package = [database_ packageWithName:arg1]) {
9647 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9648 [(FileTable *)controller setPackage:package];
9654 [controller setDelegate:self];
9658 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9659 CYViewController *page([self pageForURL:url forExternal:external]);
9662 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9663 [nav setViewControllers:[NSArray arrayWithObject:page]];
9664 [tabbar_ setUnselectedViewController:nav];
9670 - (void) applicationOpenURL:(NSURL *)url {
9671 [super applicationOpenURL:url];
9673 if (!loaded_) starturl_ = [url retain];
9674 else [self openCydiaURL:url forExternal:YES];
9677 - (void) applicationWillResignActive:(UIApplication *)application {
9678 // Stop refreshing if you get a phone call or lock the device.
9679 if ([tabbar_ updating])
9680 [tabbar_ cancelUpdate];
9682 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9683 [super applicationWillResignActive:application];
9686 - (void) applicationWillTerminate:(UIApplication *)application {
9688 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9689 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9690 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9695 - (void) setConfigurationData:(NSString *)data {
9696 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9698 if (!conffile_r(data)) {
9699 lprintf("E:invalid conffile\n");
9703 NSString *ofile = conffile_r[1];
9704 //NSString *nfile = conffile_r[2];
9706 UIAlertView *alert = [[[UIAlertView alloc]
9707 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9708 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9710 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9712 UCLocalize("ACCEPT_NEW_COPY"),
9713 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9717 [alert setContext:@"conffile"];
9718 [alert setNumberOfRows:2];
9722 - (void) addStashController {
9724 stash_ = [[StashController alloc] init];
9725 [window_ addSubview:[stash_ view]];
9728 - (void) removeStashController {
9729 [[stash_ view] removeFromSuperview];
9735 [self setIdleTimerDisabled:YES];
9737 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9738 UpdateExternalStatus(1);
9739 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9740 UpdateExternalStatus(0);
9742 [self removeStashController];
9744 if (ExecFork() == 0) {
9745 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9746 perror("launchctl stop");
9750 - (void) setupViewControllers {
9751 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9753 NSMutableArray *items([NSMutableArray arrayWithObjects:
9754 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9755 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9756 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9757 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9761 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9762 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9764 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9767 NSMutableArray *controllers([NSMutableArray array]);
9768 for (UITabBarItem *item in items) {
9769 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9770 [controller setTabBarItem:item];
9771 [controllers addObject:controller];
9773 [tabbar_ setViewControllers:controllers];
9775 [tabbar_ setUpdateDelegate:self];
9778 - (void) applicationDidFinishLaunching:(id)unused {
9780 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9781 [self setApplicationSupportsShakeToEdit:NO];
9783 @synchronized (HostConfig_) {
9784 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9787 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9788 initWithMemoryCapacity:524288
9789 diskCapacity:10485760
9790 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9793 [CYBrowserController _initialize];
9795 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9797 Font12_ = [[UIFont systemFontOfSize:12] retain];
9798 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9799 Font14_ = [[UIFont systemFontOfSize:14] retain];
9800 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9801 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9803 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9804 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9806 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9807 [window_ orderFront:self];
9808 [window_ makeKey:self];
9809 [window_ setHidden:NO];
9812 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9813 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9814 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9815 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9816 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9817 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9818 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9819 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9820 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9823 [self addStashController];
9824 // XXX: this would be much cleaner as a yieldToSelector:
9825 // that way the removeStashController could happen right here inline
9826 // we also could no longer require the useless stash_ field anymore
9827 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9831 database_ = [Database sharedInstance];
9832 [database_ setDelegate:self];
9834 [window_ setUserInteractionEnabled:NO];
9835 [self setupViewControllers];
9837 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9838 [window_ addSubview:[emulated_ view]];
9840 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9844 - (NSArray *) defaultStartPages {
9845 NSMutableArray *standard = [NSMutableArray array];
9846 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9847 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9848 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9850 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9852 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9853 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9855 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9862 [window_ setUserInteractionEnabled:YES];
9863 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9866 if ([emulated_ modalViewController] != nil)
9867 [emulated_ dismissModalViewControllerAnimated:YES];
9868 [window_ setUserInteractionEnabled:NO];
9876 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9877 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9878 int standardIndex = 0;
9879 NSArray *standard = [self defaultStartPages];
9886 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9887 if (valid && closed != nil) {
9888 NSTimeInterval interval([closed timeIntervalSinceNow]);
9889 // XXX: Is 15 minutes the optimal time here?
9890 if (interval > 0 && interval <= -(15*60))
9894 if (valid && [saved count] != [standard count])
9898 for (unsigned int i = 0; i < [standard count]; i++) {
9899 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9900 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9901 // but it's good enough for now.
9902 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9909 NSArray *items = nil;
9911 [tabbar_ setSelectedIndex:savedIndex];
9914 [tabbar_ setSelectedIndex:standardIndex];
9918 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9919 NSArray *stack = [items objectAtIndex:tab];
9920 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9921 NSMutableArray *current = [NSMutableArray array];
9923 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9924 NSString *addr = [stack objectAtIndex:nav];
9925 NSURL *url = [NSURL URLWithString:addr];
9926 CYViewController *page = [self pageForURL:url forExternal:NO];
9928 [current addObject:page];
9931 [navigation setViewControllers:current];
9934 // (Try to) show the startup URL.
9935 if (starturl_ != nil) {
9936 [self openCydiaURL:starturl_ forExternal:NO];
9937 [starturl_ release];
9942 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9943 if (item != nil && IsWildcat_) {
9944 [sheet showFromBarButtonItem:item animated:YES];
9946 [sheet showInView:window_];
9950 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9951 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9952 [progress setTitle:task];
9953 [progress addProgressEvent:event];
9956 - (void) addProgressEventForTask:(NSArray *)data {
9957 CydiaProgressEvent *event([data objectAtIndex:0]);
9958 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9959 [self addProgressEvent:event forTask:task];
9962 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9963 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9969 id Alloc_(id self, SEL selector) {
9970 id object = alloc_(self, selector);
9971 lprintf("[%s]A-%p\n", self->isa->name, object);
9976 id Dealloc_(id self, SEL selector) {
9977 id object = dealloc_(self, selector);
9978 lprintf("[%s]D-%p\n", self->isa->name, object);
9982 Class $WebDefaultUIKitDelegate;
9984 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9985 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9986 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9987 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9990 static NSNumber *shouldPlayKeyboardSounds;
9994 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9996 case 1104: // Keyboard Button Clicked
9997 case 1105: // Keyboard Delete Repeated
9998 if (shouldPlayKeyboardSounds == nil) {
9999 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
10000 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
10003 if (![shouldPlayKeyboardSounds boolValue])
10007 _UIHardware$_playSystemSound$(self, _cmd, sound);
10011 Class $UIApplication;
10013 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
10014 static BOOL initialized = NO;
10015 static BOOL started = NO;
10017 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
10018 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
10020 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
10021 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
10022 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
10023 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
10025 if (initialized && !enabled) {
10027 [bundle performSelector:@selector(_accessibilityStopServer)];
10028 } else if (enabled) {
10032 [bundle performSelector:@selector(_accessibilityStartServer)];
10038 Class $NSURLConnection;
10040 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10041 NSMutableURLRequest *copy([request mutableCopy]);
10043 NSURL *url([copy URL]);
10044 NSString *host([url host]);
10045 NSString *scheme([[url scheme] lowercaseString]);
10047 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10049 @synchronized (HostConfig_) {
10050 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10051 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10052 [copy setHTTPShouldUsePipelining:YES];
10055 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10059 int main(int argc, char *argv[]) { _pooled
10062 UpdateExternalStatus(0);
10064 if (Class $UIDevice = objc_getClass("UIDevice")) {
10065 UIDevice *device([$UIDevice currentDevice]);
10066 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10068 IsWildcat_ = false;
10070 UIScreen *screen([UIScreen mainScreen]);
10071 if ([screen respondsToSelector:@selector(scale)])
10072 ScreenScale_ = [screen scale];
10076 UIDevice *device([UIDevice currentDevice]);
10077 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10078 Idiom_ = @"iphone";
10080 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10081 if (idiom == UIUserInterfaceIdiomPhone)
10082 Idiom_ = @"iphone";
10083 else if (idiom == UIUserInterfaceIdiomPad)
10086 NSLog(@"unknown UIUserInterfaceIdiom!");
10089 HostConfig_ = [[NSObject alloc] init];
10090 @synchronized (HostConfig_) {
10091 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10092 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10095 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
10097 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10099 /* Library Hacks {{{ */
10100 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10102 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10103 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10104 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10105 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10106 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10109 $NSURLConnection = objc_getClass("NSURLConnection");
10110 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10111 if (NSURLConnection$init$ != NULL) {
10112 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10113 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10116 $UIHardware = objc_getClass("UIHardware");
10117 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
10118 if (UIHardware$_playSystemSound$ != NULL) {
10119 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
10120 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
10123 $UIApplication = objc_getClass("UIApplication");
10124 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
10125 if (UIApplication$_updateApplicationAccessibility != NULL) {
10126 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
10127 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
10130 /* Set Locale {{{ */
10131 Locale_ = CFLocaleCopyCurrent();
10132 Languages_ = [NSLocale preferredLanguages];
10134 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10135 //NSLog(@"%@", [Languages_ description]);
10138 if (Locale_ != NULL)
10139 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10140 else if (Languages_ == nil || [Languages_ count] == 0)
10141 // XXX: consider just setting to C and then falling through?
10144 lang = [[Languages_ objectAtIndex:0] UTF8String];
10145 setenv("LANG", lang, true);
10146 std::setlocale(LC_ALL, lang);
10149 NSLog(@"Setting Language: %s", lang);
10152 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10154 /* Parse Arguments {{{ */
10155 bool substrate(false);
10161 for (int argi(1); argi != argc; ++argi)
10162 if (strcmp(argv[argi], "--") == 0) {
10164 argv[argi] = argv[0];
10170 for (int argi(1); argi != arge; ++argi)
10171 if (strcmp(args[argi], "--substrate") == 0)
10174 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10178 App_ = [[NSBundle mainBundle] bundlePath];
10184 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10185 alloc_ = alloc->method_imp;
10186 alloc->method_imp = (IMP) &Alloc_;*/
10188 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10189 dealloc_ = dealloc->method_imp;
10190 dealloc->method_imp = (IMP) &Dealloc_;*/
10192 /* System Information {{{ */
10196 size = sizeof(maxproc);
10197 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10198 perror("sysctlbyname(\"kern.maxproc\", ?)");
10199 else if (maxproc < 64) {
10201 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10202 perror("sysctlbyname(\"kern.maxproc\", #)");
10205 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10206 char *osversion = new char[size];
10207 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10208 perror("sysctlbyname(\"kern.osversion\", ?)");
10210 System_ = [NSString stringWithUTF8String:osversion];
10212 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10213 char *machine = new char[size];
10214 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10215 perror("sysctlbyname(\"hw.machine\", ?)");
10217 Machine_ = machine;
10219 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
10220 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
10221 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
10222 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
10226 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
10227 NSData *data((NSData *) ecid);
10228 size_t length([data length]);
10229 uint8_t bytes[length];
10230 [data getBytes:bytes];
10231 char string[length * 2 + 1];
10232 for (size_t i(0); i != length; ++i)
10233 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
10234 ChipID_ = [NSString stringWithUTF8String:string];
10238 IOObjectRelease(service);
10242 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
10244 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10245 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10246 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10248 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10249 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10250 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10252 if (mcc != NULL && mnc != NULL)
10253 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10260 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10261 Build_ = [system objectForKey:@"ProductBuildVersion"];
10262 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10263 Product_ = [info objectForKey:@"SafariProductVersion"];
10264 Safari_ = [info objectForKey:@"CFBundleVersion"];
10267 /* Load Database {{{ */
10269 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10271 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10273 if (Metadata_ == NULL)
10274 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10276 Settings_ = [Metadata_ objectForKey:@"Settings"];
10278 Packages_ = [Metadata_ objectForKey:@"Packages"];
10279 Sections_ = [Metadata_ objectForKey:@"Sections"];
10280 Sources_ = [Metadata_ objectForKey:@"Sources"];
10282 Token_ = [Metadata_ objectForKey:@"Token"];
10285 if (Settings_ != nil)
10286 Role_ = [Settings_ objectForKey:@"Role"];
10288 if (Sections_ == nil) {
10289 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10290 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10293 if (Sources_ == nil) {
10294 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10295 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10300 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10303 if (Packages_ != nil) {
10305 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10309 [Metadata_ removeObjectForKey:@"Packages"];
10315 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10317 #define MobileSubstrate_(name) \
10318 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10319 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10320 if (handle == NULL) \
10321 NSLog(@"%s", dlerror()); \
10324 MobileSubstrate_(Activator)
10325 MobileSubstrate_(libstatusbar)
10326 MobileSubstrate_(SimulatedKeyEvents)
10327 MobileSubstrate_(WinterBoard)
10329 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10330 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10332 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10334 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10335 unlink("/tmp/.cydia.fw");
10337 } else if (access("/User", F_OK) != 0 || version < 4) {
10340 system("/usr/libexec/cydia/firmware.sh");
10344 _assert([[NSFileManager defaultManager]
10345 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10346 withIntermediateDirectories:YES
10351 if (access("/tmp/cydia.chk", F_OK) == 0) {
10352 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10353 _assert(errno == ENOENT);
10354 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10355 _assert(errno == ENOENT);
10358 /* APT Initialization {{{ */
10359 _assert(pkgInitConfig(*_config));
10360 _assert(pkgInitSystem(*_config, _system));
10363 _config->Set("APT::Acquire::Translation", lang);
10365 // XXX: this timeout might be important :(
10366 //_config->Set("Acquire::http::Timeout", 15);
10368 _config->Set("Acquire::http::MaxParallel", 3);
10370 /* Color Choices {{{ */
10371 space_ = CGColorSpaceCreateDeviceRGB();
10373 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10374 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10375 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10376 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10377 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10378 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10379 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10380 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10381 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10383 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10384 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10386 /* UIKit Configuration {{{ */
10387 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10388 if ($GSFontSetUseLegacyFontMetrics != NULL)
10389 $GSFontSetUseLegacyFontMetrics(YES);
10391 // XXX: I have a feeling this was important
10392 //UIKeyboardDisableAutomaticAppearance();
10395 Colon_ = UCLocalize("COLON_DELIMITED");
10396 Elision_ = UCLocalize("ELISION");
10397 Error_ = UCLocalize("ERROR");
10398 Warning_ = UCLocalize("WARNING");
10401 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10403 CGColorSpaceRelease(space_);
10404 CFRelease(Locale_);