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 NSMutableSet *BridgedHosts_;
1091 static NSString *kCydiaProgressEventTypeError = @"Error";
1092 static NSString *kCydiaProgressEventTypeInformation = @"Information";
1093 static NSString *kCydiaProgressEventTypeStatus = @"Status";
1094 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
1097 /* Display Helpers {{{ */
1098 inline float Interpolate(float begin, float end, float fraction) {
1099 return (end - begin) * fraction + begin;
1102 static _finline const char *StripVersion_(const char *version) {
1103 const char *colon(strchr(version, ':'));
1104 return colon == NULL ? version : colon + 1;
1107 NSString *LocalizeSection(NSString *section) {
1108 static Pcre title_r("^(.*?) \\((.*)\\)$");
1109 if (title_r(section)) {
1110 NSString *parent(title_r[1]);
1111 NSString *child(title_r[2]);
1113 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1114 LocalizeSection(parent),
1115 LocalizeSection(child)
1119 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1122 NSString *Simplify(NSString *title) {
1123 const char *data = [title UTF8String];
1124 size_t size = [title length];
1126 static Pcre square_r("^\\[(.*)\\]$");
1127 if (square_r(data, size))
1128 return Simplify(square_r[1]);
1130 static Pcre paren_r("^\\((.*)\\)$");
1131 if (paren_r(data, size))
1132 return Simplify(paren_r[1]);
1134 static Pcre title_r("^(.*?) \\((.*)\\)$");
1135 if (title_r(data, size))
1136 return Simplify(title_r[1]);
1142 NSString *GetLastUpdate() {
1143 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1146 return UCLocalize("NEVER_OR_UNKNOWN");
1148 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1149 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1151 CFRelease(formatter);
1153 return [(NSString *) formatted autorelease];
1156 bool isSectionVisible(NSString *section) {
1157 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1158 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1159 return hidden == nil || ![hidden boolValue];
1164 /* Delegate Prototypes {{{ */
1167 @class CydiaProgressEvent;
1169 @protocol DatabaseDelegate
1170 - (void) repairWithSelector:(SEL)selector;
1171 - (void) setConfigurationData:(NSString *)data;
1172 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
1175 @class CYPackageController;
1177 @protocol CydiaDelegate
1178 - (void) retainNetworkActivityIndicator;
1179 - (void) releaseNetworkActivityIndicator;
1180 - (void) clearPackage:(Package *)package;
1181 - (void) installPackage:(Package *)package;
1182 - (void) installPackages:(NSArray *)packages;
1183 - (void) removePackage:(Package *)package;
1184 - (void) beginUpdate;
1186 - (void) distUpgrade;
1188 - (void) updateData;
1190 - (void) addTrivialSource:(NSString *)href;
1191 - (void) showSettings;
1192 - (UIProgressHUD *) addProgressHUD;
1193 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1194 - (CYViewController *) pageForPackage:(NSString *)name;
1195 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1196 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1200 /* ProgressEvent Interface/Delegate {{{ */
1201 @interface CydiaProgressEvent : NSObject {
1202 _H<NSString> message_;
1206 _H<NSString> package_;
1208 _H<NSString> version_;
1211 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type;
1212 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package;
1213 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item;
1215 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type;
1217 - (NSString *) message;
1218 - (NSString *) type;
1221 - (NSString *) package;
1223 - (NSString *) version;
1225 - (void) setItem:(NSArray *)item;
1226 - (void) setPackage:(NSString *)package;
1227 - (void) setURL:(NSString *)url;
1228 - (void) setVersion:(NSString *)version;
1230 - (NSString *) compound:(NSString *)value;
1231 - (NSString *) compoundMessage;
1232 - (NSString *) compoundTitle;
1236 @protocol ProgressDelegate
1237 - (void) addProgressEvent:(CydiaProgressEvent *)event;
1238 - (void) setProgressPercent:(NSNumber *)percent;
1239 - (void) setProgressStatus:(NSDictionary *)status;
1240 - (void) setProgressCancellable:(NSNumber *)cancellable;
1241 - (bool) isProgressCancelled;
1242 - (void) setTitle:(NSString *)title;
1245 /* Status Delegation {{{ */
1247 public pkgAcquireStatus
1250 _transient NSObject<ProgressDelegate> *delegate_;
1260 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1261 delegate_ = delegate;
1264 NSObject<ProgressDelegate> *getDelegate() const {
1268 virtual bool MediaChange(std::string media, std::string drive) {
1272 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1275 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1276 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1277 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
1278 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1281 virtual void Done(pkgAcquire::ItemDesc &item) {
1284 virtual void Fail(pkgAcquire::ItemDesc &item) {
1286 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1287 item.Owner->Status == pkgAcquire::Item::StatDone
1291 std::string &error(item.Owner->ErrorText);
1295 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
1296 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1299 virtual bool Pulse(pkgAcquire *Owner) {
1300 bool value = pkgAcquireStatus::Pulse(Owner);
1303 double(CurrentBytes + CurrentItems) /
1304 double(TotalBytes + TotalItems)
1307 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1308 [NSNumber numberWithDouble:percent], @"Percent",
1310 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1311 [NSNumber numberWithDouble:TotalBytes], @"Total",
1312 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1313 nil] waitUntilDone:YES];
1315 if (value && ![delegate_ isProgressCancelled])
1323 _finline bool WasCancelled() const {
1327 virtual void Start() {
1328 pkgAcquireStatus::Start();
1329 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1332 virtual void Stop() {
1333 pkgAcquireStatus::Stop();
1334 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1335 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1339 /* Database Interface {{{ */
1340 typedef std::map< unsigned long, _H<Source> > SourceMap;
1342 @interface Database : NSObject {
1348 pkgCacheFile cache_;
1349 pkgDepCache::Policy *policy_;
1350 pkgRecords *records_;
1351 pkgProblemResolver *resolver_;
1352 pkgAcquire *fetcher_;
1354 SPtr<pkgPackageManager> manager_;
1355 pkgSourceList *list_;
1357 SourceMap sourceMap_;
1358 NSMutableArray *sourceList_;
1360 CFMutableArrayRef packages_;
1362 _transient NSObject<DatabaseDelegate> *delegate_;
1363 _transient NSObject<ProgressDelegate> *progress_;
1371 std::map<const char *, _H<NSString> > sections_;
1374 + (Database *) sharedInstance;
1377 - (void) _readCydia:(NSNumber *)fd;
1378 - (void) _readStatus:(NSNumber *)fd;
1379 - (void) _readOutput:(NSNumber *)fd;
1383 - (Package *) packageWithName:(NSString *)name;
1385 - (pkgCacheFile &) cache;
1386 - (pkgDepCache::Policy *) policy;
1387 - (pkgRecords *) records;
1388 - (pkgProblemResolver *) resolver;
1389 - (pkgAcquire &) fetcher;
1390 - (pkgSourceList &) list;
1391 - (NSArray *) packages;
1392 - (NSArray *) sources;
1393 - (Source *) sourceWithKey:(NSString *)key;
1394 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1402 - (void) updateWithStatus:(Status &)status;
1404 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1406 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1407 - (NSObject<ProgressDelegate> *) progressDelegate;
1409 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1411 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1415 /* ProgressEvent Implementation {{{ */
1416 @implementation CydiaProgressEvent
1418 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1419 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1422 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1423 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1424 [event setPackage:package];
1428 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1429 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1431 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1432 NSArray *fields([description componentsSeparatedByString:@" "]);
1433 [event setItem:fields];
1435 if ([fields count] > 3) {
1436 [event setPackage:[fields objectAtIndex:2]];
1437 [event setVersion:[fields objectAtIndex:3]];
1440 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1445 + (NSArray *) _attributeKeys {
1446 return [NSArray arrayWithObjects:
1456 - (NSArray *) attributeKeys {
1457 return [[self class] _attributeKeys];
1460 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1461 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1464 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1465 if ((self = [super init]) != nil) {
1471 - (NSString *) message {
1475 - (NSString *) type {
1479 - (NSArray *) item {
1480 return (id) item_ ?: [NSNull null];
1483 - (void) setItem:(NSArray *)item {
1487 - (NSString *) package {
1488 return (id) package_ ?: [NSNull null];
1491 - (void) setPackage:(NSString *)package {
1495 - (NSString *) url {
1496 return (id) url_ ?: [NSNull null];
1499 - (void) setURL:(NSString *)url {
1503 - (void) setVersion:(NSString *)version {
1507 - (NSString *) version {
1508 return (id) version_ ?: [NSNull null];
1511 - (NSString *) compound:(NSString *)value {
1513 NSString *mode(nil); {
1514 NSString *type([self type]);
1515 if ([type isEqualToString:kCydiaProgressEventTypeError])
1516 mode = UCLocalize("ERROR");
1517 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1518 mode = UCLocalize("WARNING");
1522 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1528 - (NSString *) compoundMessage {
1529 return [self compound:[self message]];
1532 - (NSString *) compoundTitle {
1535 if (package_ == nil)
1537 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1538 title = [package name];
1542 return [self compound:title];
1548 // Cytore Definitions {{{
1549 struct PackageValue :
1552 Cytore::Offset<PackageValue> next_;
1554 uint32_t index_ : 23;
1555 uint32_t subscribed_ : 1;
1572 Cytore::Offset<PackageValue> packages_[1 << 16];
1575 static Cytore::File<MetaValue> MetaFile_;
1577 // Cytore Helper Functions {{{
1578 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1579 SplitHash nhash = { hashlittle(name, length) };
1581 PackageValue *metadata;
1583 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1584 offset: if (offset->IsNull()) {
1585 *offset = MetaFile_.New<PackageValue>(length + 1);
1586 metadata = &MetaFile_.Get(*offset);
1588 if (metadata == NULL) {
1592 metadata = new PackageValue();
1593 memset(metadata, 0, sizeof(*metadata));
1596 memcpy(metadata->name_, name, length + 1);
1597 metadata->nhash_ = nhash.u16[1];
1599 metadata = &MetaFile_.Get(*offset);
1601 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1602 offset = &metadata->next_;
1610 static void PackageImport(const void *key, const void *value, void *context) {
1611 bool &fail(*reinterpret_cast<bool *>(context));
1614 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1615 NSLog(@"failed to import package %@", key);
1619 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1620 NSDictionary *package((NSDictionary *) value);
1622 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1623 if ([subscribed boolValue] && !metadata->subscribed_)
1624 metadata->subscribed_ = true;
1626 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1627 time_t time([date timeIntervalSince1970]);
1628 if (metadata->first_ > time || metadata->first_ == 0)
1629 metadata->first_ = time;
1632 NSDate *date([package objectForKey:@"LastSeen"]);
1633 NSString *version([package objectForKey:@"LastVersion"]);
1635 if (date != nil && version != nil) {
1636 time_t time([date timeIntervalSince1970]);
1637 if (metadata->last_ < time || metadata->last_ == 0)
1638 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1639 size_t length(strlen(buffer));
1640 uint16_t vhash(hashlittle(buffer, length));
1642 size_t capped(std::min<size_t>(8, length));
1643 char *latest(buffer + length - capped);
1645 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1646 metadata->vhash_ = vhash;
1648 metadata->last_ = time;
1654 /* Source Class {{{ */
1655 @interface Source : NSObject {
1656 CYString depiction_;
1657 CYString description_;
1663 CYString distribution_;
1668 _H<NSString> authority_;
1670 CYString defaultIcon_;
1672 _H<NSDictionary> record_;
1676 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1678 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1680 - (NSString *) depictionForPackage:(NSString *)package;
1681 - (NSString *) supportForPackage:(NSString *)package;
1683 - (NSDictionary *) record;
1687 - (NSString *) distribution;
1688 - (NSString *) type;
1690 - (NSString *) host;
1692 - (NSString *) name;
1693 - (NSString *) description;
1694 - (NSString *) label;
1695 - (NSString *) origin;
1696 - (NSString *) version;
1698 - (NSString *) defaultIcon;
1702 @implementation Source
1706 distribution_.clear();
1709 description_.clear();
1715 defaultIcon_.clear();
1723 // XXX: this is a very inefficient way to call these deconstructors
1728 + (NSArray *) _attributeKeys {
1729 return [NSArray arrayWithObjects:
1744 - (NSArray *) attributeKeys {
1745 return [[self class] _attributeKeys];
1748 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1749 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1752 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1755 trusted_ = index->IsTrusted();
1757 uri_.set(pool, index->GetURI());
1758 distribution_.set(pool, index->GetDist());
1759 type_.set(pool, index->GetType());
1761 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1762 if (dindex != NULL) {
1764 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1767 pkgTagFile tags(&fd);
1769 pkgTagSection section;
1776 {"default-icon", &defaultIcon_},
1777 {"depiction", &depiction_},
1778 {"description", &description_},
1780 {"origin", &origin_},
1781 {"support", &support_},
1782 {"version", &version_},
1785 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1786 const char *start, *end;
1788 if (section.Find(names[i].name_, start, end)) {
1789 CYString &value(*names[i].value_);
1790 value.set(pool, start, end - start);
1796 record_ = [Sources_ objectForKey:[self key]];
1798 NSURL *url([NSURL URLWithString:uri_]);
1802 host_ = [host_ lowercaseString];
1805 // XXX: this is due to a bug in _H<>
1806 authority_ = (id) host_;
1808 authority_ = [url path];
1811 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1812 if ((self = [super init]) != nil) {
1813 [self setMetaIndex:index inPool:pool];
1817 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1818 NSDictionary *lhr = [self record];
1819 NSDictionary *rhr = [source record];
1822 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1824 NSString *lhs = [self name];
1825 NSString *rhs = [source name];
1827 if ([lhs length] != 0 && [rhs length] != 0) {
1828 unichar lhc = [lhs characterAtIndex:0];
1829 unichar rhc = [rhs characterAtIndex:0];
1831 if (isalpha(lhc) && !isalpha(rhc))
1832 return NSOrderedAscending;
1833 else if (!isalpha(lhc) && isalpha(rhc))
1834 return NSOrderedDescending;
1837 return [lhs compare:rhs options:LaxCompareOptions_];
1840 - (NSString *) depictionForPackage:(NSString *)package {
1841 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1844 - (NSString *) supportForPackage:(NSString *)package {
1845 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1848 - (NSDictionary *) record {
1856 - (NSString *) uri {
1860 - (NSString *) distribution {
1861 return distribution_;
1864 - (NSString *) type {
1868 - (NSString *) key {
1869 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1872 - (NSString *) host {
1876 - (NSString *) name {
1877 return origin_.empty() ? (id) authority_ : origin_;
1880 - (NSString *) description {
1881 return description_;
1884 - (NSString *) label {
1885 return label_.empty() ? (id) authority_ : label_;
1888 - (NSString *) origin {
1892 - (NSString *) version {
1896 - (NSString *) defaultIcon {
1897 return defaultIcon_;
1902 /* CydiaOperation Class {{{ */
1903 @interface CydiaOperation : NSObject {
1904 NSString *operator_;
1908 - (NSString *) operator;
1909 - (NSString *) value;
1913 @implementation CydiaOperation
1916 [operator_ release];
1921 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1922 if ((self = [super init]) != nil) {
1923 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1924 value_ = [[NSString alloc] initWithUTF8String:value];
1928 + (NSArray *) _attributeKeys {
1929 return [NSArray arrayWithObjects:
1935 - (NSArray *) attributeKeys {
1936 return [[self class] _attributeKeys];
1939 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1940 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1943 - (NSString *) operator {
1947 - (NSString *) value {
1953 /* CydiaClause Class {{{ */
1954 @interface CydiaClause : NSObject {
1956 CydiaOperation *version_;
1959 - (NSString *) package;
1960 - (CydiaOperation *) version;
1964 @implementation CydiaClause
1972 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1973 if ((self = [super init]) != nil) {
1974 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1976 if (const char *version = dep.TargetVer())
1977 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1979 version_ = [[NSNull null] retain];
1983 + (NSArray *) _attributeKeys {
1984 return [NSArray arrayWithObjects:
1990 - (NSArray *) attributeKeys {
1991 return [[self class] _attributeKeys];
1994 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1995 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1998 - (NSString *) package {
2002 - (CydiaOperation *) version {
2008 /* CydiaRelation Class {{{ */
2009 @interface CydiaRelation : NSObject {
2010 NSString *relationship_;
2011 NSMutableArray *clauses_;
2014 - (NSString *) relationship;
2015 - (NSArray *) clauses;
2019 @implementation CydiaRelation
2022 [relationship_ release];
2027 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2028 if ((self = [super init]) != nil) {
2029 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
2030 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
2032 pkgCache::DepIterator start;
2033 pkgCache::DepIterator end;
2034 dep.GlobOr(start, end); // ++dep
2037 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2039 // yes, seriously. (wtf?)
2047 + (NSArray *) _attributeKeys {
2048 return [NSArray arrayWithObjects:
2054 - (NSArray *) attributeKeys {
2055 return [[self class] _attributeKeys];
2058 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2059 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2062 - (NSString *) relationship {
2063 return relationship_;
2066 - (NSArray *) clauses {
2070 - (void) addClause:(CydiaClause *)clause {
2071 [clauses_ addObject:clause];
2076 /* Package Class {{{ */
2077 struct ParsedPackage {
2082 CYString depiction_;
2092 @interface Package : NSObject {
2095 uint32_t essential_ : 1;
2096 uint32_t obsolete_ : 1;
2097 uint32_t ignored_ : 1;
2101 _transient Database *database_;
2103 pkgCache::VerIterator version_;
2104 pkgCache::PkgIterator iterator_;
2105 pkgCache::VerFileIterator file_;
2111 CYString installed_;
2113 const char *section_;
2114 _transient NSString *section$_;
2118 PackageValue *metadata_;
2119 ParsedPackage *parsed_;
2121 NSMutableArray *tags_;
2124 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2125 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2127 - (pkgCache::PkgIterator) iterator;
2130 - (NSString *) section;
2131 - (NSString *) simpleSection;
2133 - (NSString *) longSection;
2134 - (NSString *) shortSection;
2138 - (Address *) maintainer;
2140 - (NSString *) longDescription;
2141 - (NSString *) shortDescription;
2144 - (PackageValue *) metadata;
2147 - (bool) subscribed;
2148 - (bool) setSubscribed:(bool)subscribed;
2152 - (NSString *) latest;
2153 - (NSString *) installed;
2154 - (BOOL) uninstalled;
2157 - (BOOL) upgradableAndEssential:(BOOL)essential;
2160 - (BOOL) unfiltered;
2164 - (BOOL) halfConfigured;
2165 - (BOOL) halfInstalled;
2167 - (NSString *) mode;
2170 - (NSString *) name;
2172 - (NSString *) homepage;
2173 - (NSString *) depiction;
2174 - (Address *) author;
2176 - (NSString *) support;
2178 - (NSArray *) files;
2179 - (NSArray *) warnings;
2180 - (NSArray *) applications;
2182 - (Source *) source;
2184 - (BOOL) matches:(NSString *)text;
2186 - (bool) hasSupportingRole;
2187 - (BOOL) hasTag:(NSString *)tag;
2188 - (NSString *) primaryPurpose;
2189 - (NSArray *) purposes;
2190 - (bool) isCommercial;
2192 - (void) setIndex:(size_t)index;
2194 - (CYString &) cyname;
2196 - (uint32_t) compareBySection:(NSArray *)sections;
2201 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2202 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2203 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2204 - (bool) isVisibleInSection:(NSString *)section;
2205 - (bool) isVisibleInSource:(Source *)source;
2209 uint32_t PackageChangesRadix(Package *self, void *) {
2214 uint32_t timestamp : 30;
2215 uint32_t ignored : 1;
2216 uint32_t upgradable : 1;
2220 bool upgradable([self upgradableAndEssential:YES]);
2221 value.bits.upgradable = upgradable ? 1 : 0;
2224 value.bits.timestamp = 0;
2225 value.bits.ignored = [self ignored] ? 0 : 1;
2226 value.bits.upgradable = 1;
2228 value.bits.timestamp = [self seen] >> 2;
2229 value.bits.ignored = 0;
2230 value.bits.upgradable = 0;
2233 return _not(uint32_t) - value.key;
2236 uint32_t PackagePrefixRadix(Package *self, void *context) {
2237 size_t offset(reinterpret_cast<size_t>(context));
2238 CYString &name([self cyname]);
2240 size_t size(name.size());
2243 char *text(name.data());
2246 if (!isdigit(text[0]))
2250 while (size != digits && isdigit(text[digits]))
2258 if (offset == 0 && zeros != 0) {
2259 memset(data, '0', zeros);
2260 memcpy(data + zeros, text, 4 - zeros);
2262 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2263 if (size <= offset - zeros)
2266 text += offset - zeros;
2267 size -= offset - zeros;
2270 memcpy(data, text, 4);
2272 memcpy(data, text, size);
2273 memset(data + size, 0, 4 - size);
2276 for (size_t i(0); i != 4; ++i)
2277 if (isalpha(data[i]))
2285 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2287 /* XXX: ntohl may be more honest */
2288 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2291 CYString &(*PackageName)(Package *self, SEL sel);
2293 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2294 _profile(PackageNameCompare)
2295 CYString &lhi(PackageName(lhs, @selector(cyname)));
2296 CYString &rhi(PackageName(rhs, @selector(cyname)));
2297 CFStringRef lhn(lhi), rhn(rhi);
2300 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2301 else if (rhn == NULL)
2302 return NSOrderedDescending;
2304 _profile(PackageNameCompare$NumbersLast)
2305 if (!lhi.empty() && !rhi.empty()) {
2306 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2307 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2308 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2309 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2310 return lha ? NSOrderedAscending : NSOrderedDescending;
2314 CFIndex length = CFStringGetLength(lhn);
2316 _profile(PackageNameCompare$Compare)
2317 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2322 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2323 return PackageNameCompare(*lhs, *rhs, context);
2326 struct PackageNameOrdering :
2327 std::binary_function<Package *, Package *, bool>
2329 _finline bool operator ()(Package *lhs, Package *rhs) const {
2330 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2334 @implementation Package
2336 - (NSString *) description {
2337 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2341 if (parsed_ != NULL)
2350 + (NSString *) webScriptNameForSelector:(SEL)selector {
2352 else if (selector == @selector(clear))
2354 else if (selector == @selector(getField:))
2356 else if (selector == @selector(hasTag:))
2358 else if (selector == @selector(install))
2360 else if (selector == @selector(remove))
2366 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2367 return [self webScriptNameForSelector:selector] == nil;
2370 + (NSArray *) _attributeKeys {
2371 return [NSArray arrayWithObjects:
2390 @"shortDescription",
2403 - (NSArray *) attributeKeys {
2404 return [[self class] _attributeKeys];
2407 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2408 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2411 - (NSArray *) relations {
2412 @synchronized (database_) {
2413 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2414 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2415 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2419 - (NSString *) getField:(NSString *)name {
2420 @synchronized (database_) {
2421 if ([database_ era] != era_ || file_.end())
2424 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2426 const char *start, *end;
2427 if (!parser.Find([name UTF8String], start, end))
2428 return (NSString *) [NSNull null];
2430 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2434 if (parsed_ != NULL)
2436 @synchronized (database_) {
2437 if ([database_ era] != era_ || file_.end())
2440 ParsedPackage *parsed(new ParsedPackage);
2443 _profile(Package$parse)
2444 pkgRecords::Parser *parser;
2446 _profile(Package$parse$Lookup)
2447 parser = &[database_ records]->Lookup(file_);
2452 _profile(Package$parse$Find)
2457 {"icon", &parsed->icon_},
2458 {"depiction", &parsed->depiction_},
2459 {"homepage", &parsed->homepage_},
2460 {"website", &website},
2461 {"bugs", &parsed->bugs_},
2462 {"support", &parsed->support_},
2463 {"sponsor", &parsed->sponsor_},
2464 {"author", &parsed->author_},
2467 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2468 const char *start, *end;
2470 if (parser->Find(names[i].name_, start, end)) {
2471 CYString &value(*names[i].value_);
2472 _profile(Package$parse$Value)
2473 value.set(pool_, start, end - start);
2479 _profile(Package$parse$Tagline)
2480 const char *start, *end;
2481 if (parser->ShortDesc(start, end)) {
2482 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2485 while (stop != start && stop[-1] == '\r')
2487 parsed->tagline_.set(pool_, start, stop - start);
2491 _profile(Package$parse$Retain)
2492 if (parsed->homepage_.empty())
2493 parsed->homepage_ = website;
2494 if (parsed->homepage_ == parsed->depiction_)
2495 parsed->homepage_.clear();
2500 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2501 if ((self = [super init]) != nil) {
2502 _profile(Package$initWithVersion)
2505 database_ = database;
2506 era_ = [database era];
2510 pkgCache::PkgIterator iterator(version.ParentPkg());
2511 iterator_ = iterator;
2513 _profile(Package$initWithVersion$Version)
2514 if (!version_.end())
2515 file_ = version_.FileList();
2517 pkgCache &cache([database_ cache]);
2518 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2522 _profile(Package$initWithVersion$Cache)
2523 name_.set(NULL, iterator.Display());
2525 latest_.set(NULL, StripVersion_(version_.VerStr()));
2527 pkgCache::VerIterator current(iterator.CurrentVer());
2529 installed_.set(NULL, StripVersion_(current.VerStr()));
2532 _profile(Package$initWithVersion$Tags)
2533 pkgCache::TagIterator tag(iterator.TagList());
2535 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2537 const char *name(tag.Name());
2538 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2540 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2541 if (strcmp(name + 6, "enduser") == 0)
2543 else if (strcmp(name + 6, "hacker") == 0)
2545 else if (strcmp(name + 6, "developer") == 0)
2547 else if (strcmp(name + 6, "cydia") == 0)
2553 if (strncmp(name, "cydia::", 7) == 0) {
2554 if (strcmp(name + 7, "essential") == 0)
2556 else if (strcmp(name + 7, "obsolete") == 0)
2561 } while (!tag.end());
2565 _profile(Package$initWithVersion$Metadata)
2566 const char *mixed(iterator.Name());
2567 size_t size(strlen(mixed));
2568 char lower[size + 1];
2570 for (size_t i(0); i != size; ++i)
2571 lower[i] = mixed[i] | 0x20;
2574 PackageValue *metadata(PackageFind(lower, size));
2575 metadata_ = metadata;
2577 id_.set(NULL, metadata->name_, size);
2579 const char *latest(version_.VerStr());
2580 size_t length(strlen(latest));
2582 uint16_t vhash(hashlittle(latest, length));
2584 size_t capped(std::min<size_t>(8, length));
2585 latest = latest + length - capped;
2587 if (metadata->first_ == 0)
2588 metadata->first_ = now_;
2590 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2591 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2592 metadata->vhash_ = vhash;
2593 metadata->last_ = now_;
2594 } else if (metadata->last_ == 0)
2595 metadata->last_ = metadata->first_;
2598 _profile(Package$initWithVersion$Section)
2599 section_ = iterator.Section();
2602 _profile(Package$initWithVersion$Flags)
2603 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2604 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2609 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2610 pkgCache::VerIterator version;
2612 _profile(Package$packageWithIterator$GetCandidateVer)
2613 version = [database policy]->GetCandidateVer(iterator);
2621 _profile(Package$packageWithIterator$Allocate)
2622 package = [Package allocWithZone:zone];
2625 _profile(Package$packageWithIterator$Initialize)
2627 initWithVersion:version
2634 _profile(Package$packageWithIterator$Autorelease)
2635 package = [package autorelease];
2641 - (pkgCache::PkgIterator) iterator {
2645 - (NSString *) section {
2646 if (section$_ == nil) {
2647 if (section_ == NULL)
2650 _profile(Package$section$mappedSectionForPointer)
2651 section$_ = [database_ mappedSectionForPointer:section_];
2656 - (NSString *) simpleSection {
2657 if (NSString *section = [self section])
2658 return Simplify(section);
2663 - (NSString *) longSection {
2664 return LocalizeSection([self section]);
2667 - (NSString *) shortSection {
2668 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2671 - (NSString *) uri {
2674 pkgIndexFile *index;
2675 pkgCache::PkgFileIterator file(file_.File());
2676 if (![database_ list].FindIndex(file, index))
2678 return [NSString stringWithUTF8String:iterator_->Path];
2679 //return [NSString stringWithUTF8String:file.Site()];
2680 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2684 - (Address *) maintainer {
2685 @synchronized (database_) {
2686 if ([database_ era] != era_ || file_.end())
2689 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2690 const std::string &maintainer(parser->Maintainer());
2691 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2695 @synchronized (database_) {
2696 if ([database_ era] != era_ || version_.end())
2699 return version_->InstalledSize;
2702 - (NSString *) longDescription {
2703 @synchronized (database_) {
2704 if ([database_ era] != era_ || file_.end())
2707 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2708 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2710 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2711 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2712 if ([lines count] < 2)
2715 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2716 for (size_t i(1), e([lines count]); i != e; ++i) {
2717 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2718 [trimmed addObject:trim];
2721 return [trimmed componentsJoinedByString:@"\n"];
2724 - (NSString *) shortDescription {
2725 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2729 _profile(Package$index)
2730 CFStringRef name((CFStringRef) [self name]);
2731 if (CFStringGetLength(name) == 0)
2733 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2734 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2736 return toupper(character);
2740 - (PackageValue *) metadata {
2745 PackageValue *metadata([self metadata]);
2746 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2749 - (bool) subscribed {
2750 return [self metadata]->subscribed_;
2753 - (bool) setSubscribed:(bool)subscribed {
2754 PackageValue *metadata([self metadata]);
2755 if (metadata->subscribed_ == subscribed)
2757 metadata->subscribed_ = subscribed;
2765 - (NSString *) latest {
2769 - (NSString *) installed {
2773 - (BOOL) uninstalled {
2774 return installed_.empty();
2778 return !version_.end();
2781 - (BOOL) upgradableAndEssential:(BOOL)essential {
2782 _profile(Package$upgradableAndEssential)
2783 pkgCache::VerIterator current(iterator_.CurrentVer());
2785 return essential && essential_;
2787 return !version_.end() && version_ != current;
2791 - (BOOL) essential {
2796 return [database_ cache][iterator_].InstBroken();
2799 - (BOOL) unfiltered {
2800 _profile(Package$unfiltered$obsolete)
2801 if (_unlikely(obsolete_))
2805 _profile(Package$unfiltered$hasSupportingRole)
2806 if (_unlikely(![self hasSupportingRole]))
2814 if (![self unfiltered])
2819 _profile(Package$visible$section)
2820 section = [self section];
2823 _profile(Package$visible$isSectionVisible)
2824 if (!isSectionVisible(section))
2832 unsigned char current(iterator_->CurrentState);
2833 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2836 - (BOOL) halfConfigured {
2837 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2840 - (BOOL) halfInstalled {
2841 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2845 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2846 return state.Mode != pkgDepCache::ModeKeep;
2849 - (NSString *) mode {
2850 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2852 switch (state.Mode) {
2853 case pkgDepCache::ModeDelete:
2854 if ((state.iFlags & pkgDepCache::Purge) != 0)
2858 case pkgDepCache::ModeKeep:
2859 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2860 return @"REINSTALL";
2861 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2865 case pkgDepCache::ModeInstall:
2866 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2867 return @"REINSTALL";
2868 else*/ switch (state.Status) {
2870 return @"DOWNGRADE";
2876 return @"NEW_INSTALL";
2887 - (NSString *) name {
2888 return name_.empty() ? id_ : name_;
2891 - (UIImage *) icon {
2892 NSString *section = [self simpleSection];
2895 if (parsed_ != NULL)
2896 if (NSString *href = parsed_->icon_)
2897 if ([href hasPrefix:@"file:///"])
2898 // XXX: correct escaping
2899 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2900 if (icon == nil) if (section != nil)
2901 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2902 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2903 if ([dicon hasPrefix:@"file:///"])
2904 // XXX: correct escaping
2905 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2907 icon = [UIImage applicationImageNamed:@"unknown.png"];
2911 - (NSString *) homepage {
2912 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2915 - (NSString *) depiction {
2916 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2919 - (Address *) sponsor {
2920 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2923 - (Address *) author {
2924 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2927 - (NSString *) support {
2928 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2931 - (NSArray *) files {
2932 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2933 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2936 fin.open([path UTF8String]);
2941 while (std::getline(fin, line))
2942 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2947 - (NSString *) state {
2948 @synchronized (database_) {
2949 if ([database_ era] != era_ || file_.end())
2952 switch (iterator_->CurrentState) {
2953 case pkgCache::State::NotInstalled:
2954 return @"NotInstalled";
2955 case pkgCache::State::UnPacked:
2957 case pkgCache::State::HalfConfigured:
2958 return @"HalfConfigured";
2959 case pkgCache::State::HalfInstalled:
2960 return @"HalfInstalled";
2961 case pkgCache::State::ConfigFiles:
2962 return @"ConfigFiles";
2963 case pkgCache::State::Installed:
2964 return @"Installed";
2965 case pkgCache::State::TriggersAwaited:
2966 return @"TriggersAwaited";
2967 case pkgCache::State::TriggersPending:
2968 return @"TriggersPending";
2971 return (NSString *) [NSNull null];
2974 - (NSString *) selection {
2975 @synchronized (database_) {
2976 if ([database_ era] != era_ || file_.end())
2979 switch (iterator_->SelectedState) {
2980 case pkgCache::State::Unknown:
2982 case pkgCache::State::Install:
2984 case pkgCache::State::Hold:
2986 case pkgCache::State::DeInstall:
2987 return @"DeInstall";
2988 case pkgCache::State::Purge:
2992 return (NSString *) [NSNull null];
2995 - (NSArray *) warnings {
2996 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2997 const char *name(iterator_.Name());
2999 size_t length(strlen(name));
3000 if (length < 2) invalid:
3001 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3002 else for (size_t i(0); i != length; ++i)
3004 /* XXX: technically this is not allowed */
3005 (name[i] < 'A' || name[i] > 'Z') &&
3006 (name[i] < 'a' || name[i] > 'z') &&
3007 (name[i] < '0' || name[i] > '9') &&
3008 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3011 if (strcmp(name, "cydia") != 0) {
3014 bool _private = false;
3017 bool repository = [[self section] isEqualToString:@"Repositories"];
3019 if (NSArray *files = [self files])
3020 for (NSString *file in files)
3021 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3023 else if (!user && [file isEqualToString:@"/User"])
3025 else if (!_private && [file isEqualToString:@"/private"])
3027 else if (!stash && [file isEqualToString:@"/var/stash"])
3030 /* XXX: this is not sensitive enough. only some folders are valid. */
3031 if (cydia && !repository)
3032 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3034 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3036 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3038 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3041 return [warnings count] == 0 ? nil : warnings;
3044 - (NSArray *) applications {
3045 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3047 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3049 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
3050 if (NSArray *files = [self files])
3051 for (NSString *file in files)
3052 if (application_r(file)) {
3053 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3054 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3055 if ([id isEqualToString:me])
3058 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3060 display = application_r[1];
3062 NSString *bundle([file stringByDeletingLastPathComponent]);
3063 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3064 if (icon == nil || [icon length] == 0)
3066 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3068 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3069 [applications addObject:application];
3071 [application addObject:id];
3072 [application addObject:display];
3073 [application addObject:url];
3076 return [applications count] == 0 ? nil : applications;
3079 - (Source *) source {
3080 if (source_ == nil) {
3081 @synchronized (database_) {
3082 if ([database_ era] != era_ || file_.end())
3083 source_ = (Source *) [NSNull null];
3085 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
3089 return source_ == (Source *) [NSNull null] ? nil : source_;
3092 - (BOOL) matches:(NSString *)text {
3098 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
3099 if (range.location != NSNotFound)
3102 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
3103 if (range.location != NSNotFound)
3108 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
3109 if (range.location != NSNotFound)
3115 - (bool) hasSupportingRole {
3120 if ([Role_ isEqualToString:@"User"])
3124 if ([Role_ isEqualToString:@"Hacker"])
3128 if ([Role_ isEqualToString:@"Developer"])
3133 - (NSArray *) tags {
3137 - (BOOL) hasTag:(NSString *)tag {
3138 return tags_ == nil ? NO : [tags_ containsObject:tag];
3141 - (NSString *) primaryPurpose {
3142 for (NSString *tag in tags_)
3143 if ([tag hasPrefix:@"purpose::"])
3144 return [tag substringFromIndex:9];
3148 - (NSArray *) purposes {
3149 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3150 for (NSString *tag in tags_)
3151 if ([tag hasPrefix:@"purpose::"])
3152 [purposes addObject:[tag substringFromIndex:9]];
3153 return [purposes count] == 0 ? nil : purposes;
3156 - (bool) isCommercial {
3157 return [self hasTag:@"cydia::commercial"];
3160 - (void) setIndex:(size_t)index {
3161 if (metadata_->index_ != index)
3162 metadata_->index_ = index;
3165 - (CYString &) cyname {
3166 return name_.empty() ? id_ : name_;
3169 - (uint32_t) compareBySection:(NSArray *)sections {
3170 NSString *section([self section]);
3171 for (size_t i(0), e([sections count]); i != e; ++i) {
3172 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3176 return _not(uint32_t);
3180 @synchronized (database_) {
3181 pkgProblemResolver *resolver = [database_ resolver];
3182 resolver->Clear(iterator_);
3184 pkgCacheFile &cache([database_ cache]);
3185 cache->SetReInstall(iterator_, false);
3186 cache->MarkKeep(iterator_, false);
3190 @synchronized (database_) {
3191 pkgProblemResolver *resolver = [database_ resolver];
3192 resolver->Clear(iterator_);
3193 resolver->Protect(iterator_);
3195 pkgCacheFile &cache([database_ cache]);
3196 cache->SetReInstall(iterator_, false);
3197 cache->MarkInstall(iterator_, false);
3199 pkgDepCache::StateCache &state((*cache)[iterator_]);
3200 if (!state.Install())
3201 cache->SetReInstall(iterator_, true);
3205 @synchronized (database_) {
3206 pkgProblemResolver *resolver = [database_ resolver];
3207 resolver->Clear(iterator_);
3208 resolver->Remove(iterator_);
3209 resolver->Protect(iterator_);
3211 pkgCacheFile &cache([database_ cache]);
3212 cache->SetReInstall(iterator_, false);
3213 cache->MarkDelete(iterator_, true);
3216 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3217 _profile(Package$isUnfilteredAndSearchedForBy)
3220 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3221 value &= [self unfiltered];
3224 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3225 value &= [self matches:search];
3232 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3233 if ([search length] == 0)
3236 _profile(Package$isUnfilteredAndSelectedForBy)
3239 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3240 value &= [self unfiltered];
3243 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3244 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3251 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3252 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3255 - (bool) isVisibleInSection:(NSString *)name {
3256 NSString *section([self section]);
3260 section == nil && [name length] == 0 ||
3261 [name isEqualToString:section]
3262 ) && [self visible];
3265 - (bool) isVisibleInSource:(Source *)source {
3266 return [self source] == source && [self visible];
3271 /* Section Class {{{ */
3272 @interface Section : NSObject {
3277 NSString *localized_;
3280 - (NSComparisonResult) compareByLocalized:(Section *)section;
3281 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3282 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3283 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3284 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3285 - (NSString *) name;
3292 - (void) addToCount;
3294 - (void) setCount:(size_t)count;
3295 - (NSString *) localized;
3299 @implementation Section
3303 if (localized_ != nil)
3304 [localized_ release];
3308 - (NSComparisonResult) compareByLocalized:(Section *)section {
3309 NSString *lhs(localized_);
3310 NSString *rhs([section localized]);
3312 /*if ([lhs length] != 0 && [rhs length] != 0) {
3313 unichar lhc = [lhs characterAtIndex:0];
3314 unichar rhc = [rhs characterAtIndex:0];
3316 if (isalpha(lhc) && !isalpha(rhc))
3317 return NSOrderedAscending;
3318 else if (!isalpha(lhc) && isalpha(rhc))
3319 return NSOrderedDescending;
3322 return [lhs compare:rhs options:LaxCompareOptions_];
3325 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3326 if ((self = [self initWithName:name localize:NO]) != nil) {
3327 if (localized != nil)
3328 localized_ = [localized retain];
3332 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3333 return [self initWithName:name row:0 localize:localize];
3336 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3337 if ((self = [super init]) != nil) {
3338 name_ = [name retain];
3342 localized_ = [LocalizeSection(name_) retain];
3346 /* XXX: localize the index thingees */
3347 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3348 if ((self = [super init]) != nil) {
3349 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3355 - (NSString *) name {
3375 - (void) addToCount {
3379 - (void) setCount:(size_t)count {
3383 - (NSString *) localized {
3390 static NSString *Colon_;
3391 static NSString *Elision_;
3392 static NSString *Error_;
3393 static NSString *Warning_;
3395 /* Database Implementation {{{ */
3396 @implementation Database
3398 + (Database *) sharedInstance {
3399 static Database *instance;
3400 if (instance == nil)
3401 instance = [[Database alloc] init];
3409 - (void) releasePackages {
3410 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3411 CFArrayRemoveAllValues(packages_);
3415 // XXX: actually implement this thing
3417 [sourceList_ release];
3418 [self releasePackages];
3419 apr_pool_destroy(pool_);
3420 NSRecycleZone(zone_);
3424 - (void) _readCydia:(NSNumber *)fd { _pooled
3425 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3426 std::istream is(&ib);
3429 static Pcre finish_r("^finish:([^:]*)$");
3431 while (std::getline(is, line)) {
3432 const char *data(line.c_str());
3433 size_t size = line.size();
3434 lprintf("C:%s\n", data);
3436 if (finish_r(data, size)) {
3437 NSString *finish = finish_r[1];
3438 int index = [Finishes_ indexOfObject:finish];
3439 if (index != INT_MAX && index > Finish_)
3447 - (void) _readStatus:(NSNumber *)fd { _pooled
3448 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3449 std::istream is(&ib);
3452 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3453 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3455 while (std::getline(is, line)) {
3456 const char *data(line.c_str());
3457 size_t size(line.size());
3458 lprintf("S:%s\n", data);
3460 if (conffile_r(data, size)) {
3461 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3462 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3463 } else if (strncmp(data, "status: ", 8) == 0) {
3464 // status: <package>: {unpacked,half-configured,installed}
3465 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3466 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3467 } else if (strncmp(data, "processing: ", 12) == 0) {
3468 // processing: configure: config-test
3469 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3470 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3471 } else if (pmstatus_r(data, size)) {
3472 std::string type([pmstatus_r[1] UTF8String]);
3474 NSString *package = pmstatus_r[2];
3475 if ([package isEqualToString:@"dpkg-exec"])
3478 float percent([pmstatus_r[3] floatValue]);
3479 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3481 NSString *string = pmstatus_r[4];
3483 if (type == "pmerror") {
3484 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3485 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3486 } else if (type == "pmstatus") {
3487 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3488 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3489 } else if (type == "pmconffile")
3490 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3492 lprintf("E:unknown pmstatus\n");
3494 lprintf("E:unknown status\n");
3500 - (void) _readOutput:(NSNumber *)fd { _pooled
3501 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3502 std::istream is(&ib);
3505 while (std::getline(is, line)) {
3506 lprintf("O:%s\n", line.c_str());
3508 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3509 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3519 - (Package *) packageWithName:(NSString *)name {
3520 @synchronized (self) {
3521 if (static_cast<pkgDepCache *>(cache_) == NULL)
3523 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3524 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3528 if ((self = [super init]) != nil) {
3535 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3536 apr_pool_create(&pool_, NULL);
3538 size_t capacity(MetaFile_->active_);
3544 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3545 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3549 _assert(pipe(fds) != -1);
3552 _config->Set("APT::Keep-Fds::", cydiafd_);
3553 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3556 detachNewThreadSelector:@selector(_readCydia:)
3558 withObject:[NSNumber numberWithInt:fds[0]]
3561 _assert(pipe(fds) != -1);
3565 detachNewThreadSelector:@selector(_readStatus:)
3567 withObject:[NSNumber numberWithInt:fds[0]]
3570 _assert(pipe(fds) != -1);
3571 _assert(dup2(fds[0], 0) != -1);
3572 _assert(close(fds[0]) != -1);
3574 input_ = fdopen(fds[1], "a");
3576 _assert(pipe(fds) != -1);
3577 _assert(dup2(fds[1], 1) != -1);
3578 _assert(close(fds[1]) != -1);
3581 detachNewThreadSelector:@selector(_readOutput:)
3583 withObject:[NSNumber numberWithInt:fds[0]]
3588 - (pkgCacheFile &) cache {
3592 - (pkgDepCache::Policy *) policy {
3596 - (pkgRecords *) records {
3600 - (pkgProblemResolver *) resolver {
3604 - (pkgAcquire &) fetcher {
3608 - (pkgSourceList &) list {
3612 - (NSArray *) packages {
3613 return (NSArray *) packages_;
3616 - (NSArray *) sources {
3620 - (Source *) sourceWithKey:(NSString *)key {
3621 for (Source *source in [self sources]) {
3622 if ([[source key] isEqualToString:key])
3627 - (bool) popErrorWithTitle:(NSString *)title {
3630 while (!_error->empty()) {
3632 bool warning(!_error->PopMessage(error));
3637 size_t size(error.size());
3638 if (size == 0 || error[size - 1] != '\n')
3640 error.resize(size - 1);
3643 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3645 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3651 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3652 return [self popErrorWithTitle:title] || !success;
3655 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3656 @synchronized (self) {
3659 [self releasePackages];
3662 [sourceList_ removeAllObjects];
3682 apr_pool_clear(pool_);
3684 NSRecycleZone(zone_);
3685 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3687 int chk(creat("/tmp/cydia.chk", 0644));
3691 if (invocation != nil)
3692 [invocation invoke];
3694 NSString *title(UCLocalize("DATABASE"));
3697 OpProgress progress;
3698 while (!cache_.Open(progress, true)) { pop:
3700 bool warning(!_error->PopMessage(error));
3701 lprintf("cache_.Open():[%s]\n", error.c_str());
3703 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3704 [delegate_ repairWithSelector:@selector(configure)];
3705 else if (error == "The package lists or status file could not be parsed or opened.")
3706 [delegate_ repairWithSelector:@selector(update)];
3707 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3708 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3709 // else if (error == "Malformed Status line")
3710 // else if (error == "The list of sources could not be read.")
3712 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3722 unlink("/tmp/cydia.chk");
3724 now_ = [[NSDate date] timeIntervalSince1970];
3726 policy_ = new pkgDepCache::Policy();
3727 records_ = new pkgRecords(cache_);
3728 resolver_ = new pkgProblemResolver(cache_);
3729 fetcher_ = new pkgAcquire(&status_);
3732 list_ = new pkgSourceList();
3733 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3736 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3737 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3741 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3744 if (cache_->BrokenCount() != 0) {
3745 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3748 if (cache_->BrokenCount() != 0) {
3749 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3753 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3757 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3758 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3759 [sourceList_ addObject:object];
3761 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3762 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3763 // XXX: this could be more intelligent
3764 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3765 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3767 sourceMap_[cached->ID] = object;
3772 /*std::vector<Package *> packages;
3773 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3774 [packages_ release];
3779 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3780 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3781 //packages.push_back(package);
3782 CFArrayAppendValue(packages_, [package retain]);
3786 /*if (packages.empty())
3787 packages_ = [[NSArray alloc] init];
3789 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3792 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3793 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3794 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3802 /*if (!packages.empty())
3803 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3804 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3806 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3808 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3810 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3814 size_t count(CFArrayGetCount(packages_));
3815 MetaFile_->active_ = count;
3817 for (size_t index(0); index != count; ++index)
3818 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3822 } } CYPoolEnd() _trace(); }
3825 @synchronized (self) {
3827 resolver_ = new pkgProblemResolver(cache_);
3829 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3830 if (!cache_[iterator].Keep())
3831 cache_->MarkKeep(iterator, false);
3832 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3833 cache_->SetReInstall(iterator, false);
3836 - (void) configure {
3837 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3839 system([dpkg UTF8String]);
3844 // XXX: I don't remember this condition
3849 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3851 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3853 if ([self popErrorWithTitle:title])
3857 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3860 public pkgArchiveCleaner
3863 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3868 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3875 fetcher_->Shutdown();
3877 pkgRecords records(cache_);
3879 lock_ = new FileFd();
3880 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3882 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3884 if ([self popErrorWithTitle:title])
3888 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3891 manager_ = (_system->CreatePM(cache_));
3892 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3899 bool substrate(RestartSubstrate_);
3900 RestartSubstrate_ = false;
3902 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3904 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3906 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3908 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3909 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3912 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3914 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3916 [self popErrorWithTitle:title];
3920 bool failed = false;
3921 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3922 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3924 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3930 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3938 RestartSubstrate_ = true;
3941 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3943 if (_error->PendingError()) {
3948 if (result == pkgPackageManager::Failed) {
3953 if (result != pkgPackageManager::Completed) {
3958 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3960 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3962 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3963 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3966 if (![before isEqualToArray:after])
3971 NSString *title(UCLocalize("UPGRADE"));
3972 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3978 [self updateWithStatus:status_];
3981 - (void) updateWithStatus:(Status &)status {
3982 NSString *title(UCLocalize("REFRESHING_DATA"));
3985 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3989 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3990 if ([self popErrorWithTitle:title])
3993 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3995 bool success(ListUpdate(status, list, PulseInterval_));
3996 if (status.WasCancelled())
3999 [self popErrorWithTitle:title forOperation:success];
4001 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4003 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
4007 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4008 delegate_ = delegate;
4011 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4012 progress_ = delegate;
4013 status_.setDelegate(delegate);
4016 - (NSObject<ProgressDelegate> *) progressDelegate {
4020 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4021 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4022 return i == sourceMap_.end() ? nil : i->second;
4025 - (NSString *) mappedSectionForPointer:(const char *)section {
4026 _H<NSString> *mapped;
4028 _profile(Database$mappedSectionForPointer$Cache)
4029 mapped = §ions_[section];
4032 if (*mapped == NULL) {
4033 size_t length(strlen(section));
4034 char spaced[length + 1];
4036 _profile(Database$mappedSectionForPointer$Replace)
4037 for (size_t index(0); index != length; ++index)
4038 spaced[index] = section[index] == '_' ? ' ' : section[index];
4039 spaced[length] = '\0';
4044 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4045 string = [NSString stringWithUTF8String:spaced];
4048 _profile(Database$mappedSectionForPointer$Map)
4049 string = [SectionMap_ objectForKey:string] ?: string;
4059 @interface Diversion : NSObject {
4062 _H<NSString> format_;
4067 @implementation Diversion
4069 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4070 if ((self = [super init]) != nil) {
4071 pattern_ = [from UTF8String];
4077 - (NSString *) divert:(NSString *)url {
4081 size_t count(pattern_.size());
4083 for (size_t i(0); i != count; ++i)
4084 values[i] = pattern_[i + 1];
4086 return [[[NSString alloc] initWithFormat:format_ arguments:reinterpret_cast<va_list>(values)] autorelease];
4089 - (NSString *) key {
4093 - (NSUInteger) hash {
4097 - (BOOL) isEqual:(Diversion *)object {
4098 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4103 @interface CydiaObject : NSObject {
4105 _transient id delegate_;
4108 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4112 @interface CYBrowserController : BrowserController {
4113 CydiaObject *cydia_;
4116 + (void) addDiversion:(Diversion *)diversion;
4120 static NSMutableSet *Diversions_;
4122 /* Web Scripting {{{ */
4123 @implementation CydiaObject
4126 [indirect_ release];
4130 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4131 if ((self = [super init]) != nil) {
4132 indirect_ = [indirect retain];
4136 - (void) setDelegate:(id)delegate {
4137 delegate_ = delegate;
4140 + (NSArray *) _attributeKeys {
4141 return [NSArray arrayWithObjects:
4156 - (NSArray *) attributeKeys {
4157 return [[self class] _attributeKeys];
4160 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4161 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4164 - (NSString *) version {
4168 - (NSString *) device {
4169 return [[UIDevice currentDevice] uniqueIdentifier];
4172 - (NSString *) firmware {
4173 return [[UIDevice currentDevice] systemVersion];
4176 - (NSString *) hostname {
4177 return [[UIDevice currentDevice] name];
4180 - (NSString *) idiom {
4181 return (id) Idiom_ ?: [NSNull null];
4184 - (NSString *) plmn {
4185 return (id) PLMN_ ?: [NSNull null];
4188 - (NSString *) ecid {
4189 return (id) ChipID_ ?: [NSNull null];
4192 - (NSString *) serial {
4193 return SerialNumber_;
4196 - (NSString *) role {
4197 return (id) Role_ ?: [NSNull null];
4200 - (NSString *) model {
4201 return [NSString stringWithUTF8String:Machine_];
4204 - (NSString *) token {
4205 return (id) Token_ ?: [NSNull null];
4208 + (NSString *) webScriptNameForSelector:(SEL)selector {
4210 else if (selector == @selector(addBridgedHost:))
4211 return @"addBridgedHost";
4212 else if (selector == @selector(addTrivialSource:))
4213 return @"addTrivialSource";
4214 else if (selector == @selector(close))
4216 else if (selector == @selector(divert::))
4218 else if (selector == @selector(du:))
4220 else if (selector == @selector(stringWithFormat:arguments:))
4222 else if (selector == @selector(getAllSources))
4223 return @"getAllSourcs";
4224 else if (selector == @selector(getKernelNumber:))
4225 return @"getKernelNumber";
4226 else if (selector == @selector(getKernelString:))
4227 return @"getKernelString";
4228 else if (selector == @selector(getInstalledPackages))
4229 return @"getInstalledPackages";
4230 else if (selector == @selector(getPackageById:))
4231 return @"getPackageById";
4232 else if (selector == @selector(installPackages:))
4233 return @"installPackages";
4234 else if (selector == @selector(localizedStringForKey:value:table:))
4236 else if (selector == @selector(popViewController:))
4237 return @"popViewController";
4238 else if (selector == @selector(refreshSources))
4239 return @"refreshSources";
4240 else if (selector == @selector(removeButton))
4241 return @"removeButton";
4242 else if (selector == @selector(substitutePackageNames:))
4243 return @"substitutePackageNames";
4244 else if (selector == @selector(scrollToBottom:))
4245 return @"scrollToBottom";
4246 else if (selector == @selector(setAllowsNavigationAction:))
4247 return @"setAllowsNavigationAction";
4248 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4249 return @"setButtonImage";
4250 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4251 return @"setButtonTitle";
4252 else if (selector == @selector(setHidesBackButton:))
4253 return @"setHidesBackButton";
4254 else if (selector == @selector(setHidesNavigationBar:))
4255 return @"setHidesNavigationBar";
4256 else if (selector == @selector(setNavigationBarStyle:))
4257 return @"setNavigationBarStyle";
4258 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4259 return @"setNavigationBarTintColor";
4260 else if (selector == @selector(setPopupHook:))
4261 return @"setPopupHook";
4262 else if (selector == @selector(setToken:))
4264 else if (selector == @selector(setViewportWidth:))
4265 return @"setViewportWidth";
4266 else if (selector == @selector(statfs:))
4268 else if (selector == @selector(supports:))
4274 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4275 return [self webScriptNameForSelector:selector] == nil;
4278 - (BOOL) supports:(NSString *)feature {
4279 return [feature isEqualToString:@"window.open"];
4282 - (void) divert:(NSString *)from :(NSString *)to {
4283 [CYBrowserController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4286 - (NSNumber *) getKernelNumber:(NSString *)name {
4287 const char *string([name UTF8String]);
4290 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4291 return (id) [NSNull null];
4293 if (size != sizeof(int))
4294 return (id) [NSNull null];
4297 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4298 return (id) [NSNull null];
4300 return [NSNumber numberWithInt:value];
4303 - (NSString *) getKernelString:(NSString *)name {
4304 const char *string([name UTF8String]);
4307 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4308 return (id) [NSNull null];
4310 char value[size + 1];
4311 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4312 return (id) [NSNull null];
4314 // XXX: just in case you request something ludicrous
4317 return [NSString stringWithCString:value];
4320 - (void) addBridgedHost:(NSString *)host {
4321 [BridgedHosts_ performSelectorOnMainThread:@selector(addObject:) withObject:host waitUntilDone:NO];
4324 - (void) popViewController:(NSNumber *)value {
4325 if (value == (id) [WebUndefined undefined])
4326 value = [NSNumber numberWithBool:YES];
4327 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4330 - (void) addTrivialSource:(NSString *)href {
4331 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4334 - (void) refreshSources {
4335 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4338 - (NSArray *) getAllSources {
4339 return [[Database sharedInstance] sources];
4342 - (NSArray *) getInstalledPackages {
4343 Database *database([Database sharedInstance]);
4344 @synchronized (database) {
4345 NSArray *packages([database packages]);
4346 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4347 for (Package *package in packages)
4348 if (![package uninstalled])
4349 [installed addObject:package];
4353 - (Package *) getPackageById:(NSString *)id {
4354 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4358 return (Package *) [NSNull null];
4361 - (NSArray *) statfs:(NSString *)path {
4364 if (path == nil || statfs([path UTF8String], &stat) == -1)
4367 return [NSArray arrayWithObjects:
4368 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4369 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4370 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4374 - (NSNumber *) du:(NSString *)path {
4375 NSNumber *value(nil);
4378 _assert(pipe(fds) != -1);
4380 pid_t pid(ExecFork());
4382 _assert(dup2(fds[1], 1) != -1);
4383 _assert(close(fds[0]) != -1);
4384 _assert(close(fds[1]) != -1);
4385 /* XXX: this should probably not use du */
4386 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4391 _assert(close(fds[1]) != -1);
4393 if (FILE *du = fdopen(fds[0], "r")) {
4395 while (fgets(line, sizeof(line), du) != NULL) {
4396 size_t length(strlen(line));
4397 while (length != 0 && line[length - 1] == '\n')
4398 line[--length] = '\0';
4399 if (char *tab = strchr(line, '\t')) {
4401 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4406 } else _assert(close(fds[0]));
4410 if (waitpid(pid, &status, 0) == -1)
4413 else _assert(false);
4419 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4422 - (void) installPackages:(NSArray *)packages {
4423 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4426 - (NSString *) substitutePackageNames:(NSString *)message {
4427 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4428 for (size_t i(0), e([words count]); i != e; ++i) {
4429 NSString *word([words objectAtIndex:i]);
4430 if (Package *package = [[Database sharedInstance] packageWithName:word])
4431 [words replaceObjectAtIndex:i withObject:[package name]];
4434 return [words componentsJoinedByString:@" "];
4437 - (void) removeButton {
4438 [indirect_ removeButton];
4441 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4442 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4445 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4446 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4449 - (void) setAllowsNavigationAction:(NSString *)value {
4450 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4453 - (void) setHidesBackButton:(NSString *)value {
4454 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4457 - (void) setHidesNavigationBar:(NSString *)value {
4458 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4461 - (void) setNavigationBarStyle:(NSString *)value {
4462 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4465 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4466 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4467 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4468 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4471 - (void) _setToken:(NSString *)token {
4475 [Metadata_ removeObjectForKey:@"Token"];
4477 [Metadata_ setObject:Token_ forKey:@"Token"];
4482 - (void) setToken:(NSString *)token {
4483 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4486 - (void) setPopupHook:(id)function {
4487 [indirect_ setPopupHook:function];
4490 - (void) scrollToBottom:(NSNumber *)animated {
4491 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4494 - (void) setViewportWidth:(float)width {
4495 [indirect_ setViewportWidthOnMainThread:width];
4498 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4499 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4500 unsigned count([arguments count]);
4502 for (unsigned i(0); i != count; ++i)
4503 values[i] = [arguments objectAtIndex:i];
4504 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4507 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4508 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4510 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4512 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4518 /* @ Loading... Indicator {{{ */
4519 @interface CYLoadingIndicator : UIView {
4520 _H<UIActivityIndicatorView> spinner_;
4522 _H<UIView> container_;
4525 @property (readonly, nonatomic) UILabel *label;
4526 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4530 @implementation CYLoadingIndicator
4532 - (id) initWithFrame:(CGRect)frame {
4533 if ((self = [super initWithFrame:frame]) != nil) {
4534 container_ = [[[UIView alloc] init] autorelease];
4535 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4537 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4538 [spinner_ startAnimating];
4539 [container_ addSubview:spinner_];
4541 label_ = [[[UILabel alloc] init] autorelease];
4542 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4543 [label_ setBackgroundColor:[UIColor clearColor]];
4544 [label_ setTextColor:[UIColor blackColor]];
4545 [label_ setShadowColor:[UIColor whiteColor]];
4546 [label_ setShadowOffset:CGSizeMake(0, 1)];
4547 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4548 [container_ addSubview:label_];
4550 CGSize viewsize = frame.size;
4551 CGSize spinnersize = [spinner_ bounds].size;
4552 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4553 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4555 CGRect containrect = {
4556 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4557 CGSizeMake(bothwidth, spinnersize.height)
4560 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4568 [container_ setFrame:containrect];
4569 [spinner_ setFrame:spinrect];
4570 [label_ setFrame:textrect];
4571 [self addSubview:container_];
4575 - (UILabel *) label {
4579 - (UIActivityIndicatorView *) activityIndicatorView {
4585 /* Emulated Loading Controller {{{ */
4586 @interface CYEmulatedLoadingController : CYViewController {
4587 _transient Database *database_;
4588 _H<CYLoadingIndicator> indicator_;
4589 _H<UITabBar> tabbar_;
4590 _H<UINavigationBar> navbar_;
4595 @implementation CYEmulatedLoadingController
4597 - (id) initWithDatabase:(Database *)database {
4598 if ((self = [super init]) != nil) {
4599 database_ = database;
4604 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4606 UITableView *table([[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]);
4607 [table setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4608 [[self view] addSubview:table];
4610 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4611 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4612 [[self view] addSubview:indicator_];
4614 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4615 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4616 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4617 [[self view] addSubview:tabbar_];
4619 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4620 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4621 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4622 [[self view] addSubview:navbar_];
4625 - (void) releaseSubviews {
4634 /* Cydia Browser Controller {{{ */
4635 @implementation CYBrowserController
4642 - (NSURL *) navigationURL {
4643 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4646 + (void) initialize {
4647 Diversions_ = [[NSMutableSet alloc] initWithCapacity:0];
4650 + (void) addDiversion:(Diversion *)diversion {
4651 [Diversions_ addObject:diversion];
4654 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4655 [super webView:view didClearWindowObject:window forFrame:frame];
4657 WebDataSource *source([frame dataSource]);
4658 NSURLResponse *response([source response]);
4659 NSURL *url([response URL]);
4661 if ([[[url scheme] lowercaseString] isEqualToString:@"https"])
4662 if ([BridgedHosts_ containsObject:[url host]])
4663 [window setValue:cydia_ forKey:@"cydia"];
4666 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4667 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4670 NSURL *url([copy URL]);
4671 NSString *href([url absoluteString]);
4673 for (Diversion *diversion in Diversions_)
4674 if (NSString *diverted = [diversion divert:href]) {
4675 [copy setURL:[NSURL URLWithString:diverted]];
4679 if (System_ != NULL)
4680 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4681 if (Machine_ != NULL)
4682 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4684 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4689 - (void) setDelegate:(id)delegate {
4690 [super setDelegate:delegate];
4691 [cydia_ setDelegate:delegate];
4695 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4696 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4698 WebView *webview([[webview_ _documentView] webView]);
4700 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4703 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4705 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4706 if (Product_ != nil)
4707 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4709 [webview setApplicationNameForUserAgent:application];
4717 @interface NSObject (CydiaScript)
4718 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4721 @implementation NSObject (CydiaScript)
4723 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4729 @implementation NSArray (CydiaScript)
4731 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4732 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4733 for (size_t i(0), e([self count]); i != e; ++i)
4734 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4740 @implementation NSDictionary (CydiaScript)
4742 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4743 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4745 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4752 /* Confirmation Controller {{{ */
4753 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4754 if (!iterator.end())
4755 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4756 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4758 pkgCache::PkgIterator package(dep.TargetPkg());
4761 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4768 @protocol ConfirmationControllerDelegate
4769 - (void) cancelAndClear:(bool)clear;
4770 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4774 @interface ConfirmationController : CYBrowserController {
4775 _transient Database *database_;
4777 UIAlertView *essential_;
4779 NSDictionary *changes_;
4780 NSMutableArray *issues_;
4781 NSDictionary *sizes_;
4786 - (id) initWithDatabase:(Database *)database;
4790 @implementation ConfirmationController
4797 if (essential_ != nil)
4798 [essential_ release];
4805 RestartSubstrate_ = true;
4806 [delegate_ confirmWithNavigationController:[self navigationController]];
4809 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4810 NSString *context([alert context]);
4812 if ([context isEqualToString:@"remove"]) {
4813 if (button == [alert cancelButtonIndex])
4814 [self dismissModalViewControllerAnimated:YES];
4815 else if (button == [alert firstOtherButtonIndex]) {
4819 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4820 } else if ([context isEqualToString:@"unable"]) {
4821 [self dismissModalViewControllerAnimated:YES];
4822 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4824 [super alertView:alert clickedButtonAtIndex:button];
4828 - (void) _doContinue {
4829 [self dismissModalViewControllerAnimated:YES];
4830 [delegate_ cancelAndClear:NO];
4833 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4834 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4838 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4839 [super webView:view didClearWindowObject:window forFrame:frame];
4841 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4842 changes_, @"changes",
4846 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4849 - (id) initWithDatabase:(Database *)database {
4850 if ((self = [super init]) != nil) {
4851 database_ = database;
4853 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4854 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4855 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4856 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4857 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4861 pkgCacheFile &cache([database_ cache]);
4862 NSArray *packages([database_ packages]);
4863 pkgDepCache::Policy *policy([database_ policy]);
4865 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4867 for (Package *package in packages) {
4868 pkgCache::PkgIterator iterator([package iterator]);
4869 NSString *name([package id]);
4871 if ([package broken]) {
4872 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4874 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4876 reasons, @"reasons",
4879 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4883 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4884 pkgCache::DepIterator start;
4885 pkgCache::DepIterator end;
4886 dep.GlobOr(start, end); // ++dep
4888 if (!cache->IsImportantDep(end))
4890 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4893 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4895 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4896 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4897 clauses, @"clauses",
4901 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4903 pkgCache::PkgIterator target(start.TargetPkg());
4904 if (target->ProvidesList != 0)
4905 reason = @"missing";
4907 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4909 reason = @"installed";
4910 installed = [NSString stringWithUTF8String:ver.VerStr()];
4911 } else if (!cache[target].CandidateVerIter(cache).end())
4912 reason = @"uninstalled";
4913 else if (target->ProvidesList == 0)
4914 reason = @"uninstallable";
4916 reason = @"virtual";
4919 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4920 [NSString stringWithUTF8String:start.CompType()], @"operator",
4921 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4924 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4925 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4926 version, @"version",
4928 installed, @"installed",
4931 // yes, seriously. (wtf?)
4939 pkgDepCache::StateCache &state(cache[iterator]);
4941 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4943 if (state.NewInstall())
4944 [installs addObject:name];
4945 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4946 [reinstalls addObject:name];
4947 else if (state.Upgrade())
4948 [upgrades addObject:name];
4949 else if (state.Downgrade())
4950 [downgrades addObject:name];
4951 else if (!state.Delete())
4953 else if (special_r(name))
4954 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4955 [NSNull null], @"package",
4956 [NSArray arrayWithObjects:
4957 [NSDictionary dictionaryWithObjectsAndKeys:
4958 @"Conflicts", @"relationship",
4959 [NSArray arrayWithObjects:
4960 [NSDictionary dictionaryWithObjectsAndKeys:
4962 [NSNull null], @"version",
4963 @"installed", @"reason",
4970 if ([package essential])
4972 [removes addObject:name];
4975 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4976 substrate_ |= DepSubstrate(iterator.CurrentVer());
4981 else if (Advanced_) {
4982 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4984 essential_ = [[UIAlertView alloc]
4985 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4986 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4988 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4990 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4994 [essential_ setContext:@"remove"];
4996 essential_ = [[UIAlertView alloc]
4997 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4998 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5000 cancelButtonTitle:UCLocalize("OKAY")
5001 otherButtonTitles:nil
5004 [essential_ setContext:@"unable"];
5007 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
5008 installs, @"installs",
5009 reinstalls, @"reinstalls",
5010 upgrades, @"upgrades",
5011 downgrades, @"downgrades",
5012 removes, @"removes",
5015 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
5016 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5017 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5020 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5022 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
5023 initWithTitle:UCLocalize("CANCEL")
5024 style:UIBarButtonItemStylePlain
5026 action:@selector(cancelButtonClicked)
5032 - (void) applyRightButton {
5033 if ([issues_ count] == 0 && ![self isLoading])
5034 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5035 initWithTitle:UCLocalize("CONFIRM")
5036 style:UIBarButtonItemStyleDone
5038 action:@selector(confirmButtonClicked)
5041 [[self navigationItem] setRightBarButtonItem:nil];
5045 - (void) cancelButtonClicked {
5046 [self dismissModalViewControllerAnimated:YES];
5047 [delegate_ cancelAndClear:YES];
5051 - (void) confirmButtonClicked {
5052 if (essential_ != nil)
5062 /* Progress Data {{{ */
5063 @interface CydiaProgressData : NSObject {
5064 _transient id delegate_;
5073 _H<NSMutableArray> events_;
5074 _H<NSString> title_;
5076 _H<NSString> status_;
5077 _H<NSString> finish_;
5082 @implementation CydiaProgressData
5084 + (NSArray *) _attributeKeys {
5085 return [NSArray arrayWithObjects:
5097 - (NSArray *) attributeKeys {
5098 return [[self class] _attributeKeys];
5101 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5102 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5106 if ((self = [super init]) != nil) {
5107 events_ = [NSMutableArray arrayWithCapacity:32];
5111 - (void) setDelegate:(id)delegate {
5112 delegate_ = delegate;
5115 - (void) setPercent:(float)value {
5119 - (NSNumber *) percent {
5120 return [NSNumber numberWithFloat:percent_];
5123 - (void) setCurrent:(float)value {
5127 - (NSNumber *) current {
5128 return [NSNumber numberWithFloat:current_];
5131 - (void) setTotal:(float)value {
5135 - (NSNumber *) total {
5136 return [NSNumber numberWithFloat:total_];
5139 - (void) setSpeed:(float)value {
5143 - (NSNumber *) speed {
5144 return [NSNumber numberWithFloat:speed_];
5147 - (NSArray *) events {
5151 - (void) removeAllEvents {
5152 [events_ removeAllObjects];
5155 - (void) addEvent:(CydiaProgressEvent *)event {
5156 [events_ addObject:event];
5159 - (void) setTitle:(NSString *)text {
5163 - (NSString *) title {
5167 - (void) setFinish:(NSString *)text {
5171 - (NSString *) finish {
5172 return (id) finish_ ?: [NSNull null];
5175 - (void) setRunning:(bool)running {
5179 - (NSNumber *) running {
5180 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5185 /* Progress Controller {{{ */
5186 @interface ProgressController : CYBrowserController <
5189 _transient Database *database_;
5190 _H<CydiaProgressData> progress_;
5194 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5196 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5198 - (void) setTitle:(NSString *)title;
5199 - (void) setCancellable:(bool)cancellable;
5203 @implementation ProgressController
5206 [database_ setProgressDelegate:nil];
5207 [progress_ setDelegate:nil];
5211 - (void) updateCancel {
5212 [[self navigationItem] setLeftBarButtonItem:(cancel_ == 1 ? [[[UIBarButtonItem alloc]
5213 initWithTitle:UCLocalize("CANCEL")
5214 style:UIBarButtonItemStylePlain
5216 action:@selector(cancel)
5217 ] autorelease] : nil)];
5220 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5221 if ((self = [super init]) != nil) {
5222 database_ = database;
5223 delegate_ = delegate;
5225 [database_ setProgressDelegate:self];
5227 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5228 [progress_ setDelegate:self];
5230 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5232 [scroller_ setBackgroundColor:[UIColor blackColor]];
5234 [[self navigationItem] setHidesBackButton:YES];
5236 [self updateCancel];
5240 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5241 [super webView:view didClearWindowObject:window forFrame:frame];
5242 [window setValue:progress_ forKey:@"cydiaProgress"];
5245 - (void) updateProgress {
5246 [self dispatchEvent:@"CydiaProgressUpdate"];
5249 - (void) viewWillAppear:(BOOL)animated {
5250 if (![self hasLoaded])
5251 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5253 [super viewWillAppear:animated];
5257 UpdateExternalStatus(0);
5264 [delegate_ terminateWithSuccess];
5265 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5266 [delegate_ suspendWithAnimation:YES];
5268 [delegate_ suspend];*/
5280 system("/usr/bin/sbreload");
5286 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5287 SBReboot(SBSSpringBoardServerPort());
5289 reboot2(RB_AUTOBOOT);
5296 - (void) setTitle:(NSString *)title {
5297 [progress_ setTitle:title];
5298 [self updateProgress];
5301 - (UIBarButtonItem *) rightButton {
5302 return [[progress_ running] boolValue] ? nil : [[[UIBarButtonItem alloc]
5303 initWithTitle:UCLocalize("CLOSE")
5304 style:UIBarButtonItemStylePlain
5306 action:@selector(close)
5310 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5311 UpdateExternalStatus(1);
5313 [progress_ setRunning:true];
5314 [self setTitle:title];
5315 // implicit updateProgress
5317 SHA1SumValue notifyconf; {
5319 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5322 MMap mmap(file, MMap::ReadOnly);
5324 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5325 notifyconf = sha1.Result();
5329 SHA1SumValue springlist; {
5331 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5334 MMap mmap(file, MMap::ReadOnly);
5336 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5337 springlist = sha1.Result();
5341 if (invocation != nil) {
5342 [invocation yieldToSelector:@selector(invoke)];
5343 [self setTitle:@"COMPLETE"];
5348 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5351 MMap mmap(file, MMap::ReadOnly);
5353 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5354 if (!(notifyconf == sha1.Result()))
5361 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5364 MMap mmap(file, MMap::ReadOnly);
5366 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5367 if (!(springlist == sha1.Result()))
5373 if (RestartSubstrate_)
5377 RestartSubstrate_ = false;
5380 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5381 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5382 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5383 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5384 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5388 system("su -c /usr/bin/uicache mobile");
5391 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5393 [progress_ setRunning:false];
5394 [self updateProgress];
5396 [self applyRightButton];
5399 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5400 [progress_ addEvent:event];
5401 [self updateProgress];
5404 - (bool) isProgressCancelled {
5405 return cancel_ == 2;
5410 [self updateCancel];
5413 - (void) setCancellable:(bool)cancellable {
5414 unsigned cancel(cancel_);
5418 else if (cancel_ == 0)
5421 if (cancel != cancel_)
5422 [self updateCancel];
5425 - (void) setProgressCancellable:(NSNumber *)cancellable {
5426 [self setCancellable:[cancellable boolValue]];
5429 - (void) setProgressPercent:(NSNumber *)percent {
5430 [progress_ setPercent:[percent floatValue]];
5431 [self updateProgress];
5434 - (void) setProgressStatus:(NSDictionary *)status {
5435 if (status == nil) {
5436 [progress_ setCurrent:0];
5437 [progress_ setTotal:0];
5438 [progress_ setSpeed:0];
5440 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5442 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5443 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5444 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5447 [self updateProgress];
5453 /* Cell Content View {{{ */
5454 @protocol ContentDelegate
5455 - (void) drawContentRect:(CGRect)rect;
5458 @interface ContentView : UIView {
5459 _transient id<ContentDelegate> delegate_;
5464 @implementation ContentView
5466 - (id) initWithFrame:(CGRect)frame {
5467 if ((self = [super initWithFrame:frame]) != nil) {
5468 [self setNeedsDisplayOnBoundsChange:YES];
5472 - (void) setDelegate:(id<ContentDelegate>)delegate {
5473 delegate_ = delegate;
5476 - (void) drawRect:(CGRect)rect {
5477 [super drawRect:rect];
5478 [delegate_ drawContentRect:rect];
5483 /* Cydia TableView Cell {{{ */
5484 @interface CYTableViewCell : UITableViewCell {
5485 ContentView *content_;
5491 @implementation CYTableViewCell
5498 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5499 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5501 if (view == content_) {
5502 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5503 highlighted_ = highlighted;
5506 [super _updateHighlightColorsForView:view highlighted:highlighted];
5509 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5510 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5511 highlighted_ = selected;
5513 [super setSelected:selected animated:animated];
5514 [content_ setNeedsDisplay];
5520 /* Package Cell {{{ */
5521 @interface PackageCell : CYTableViewCell <
5526 NSString *description_;
5534 - (PackageCell *) init;
5535 - (void) setPackage:(Package *)package;
5537 - (void) drawContentRect:(CGRect)rect;
5541 @implementation PackageCell
5543 - (void) clearPackage {
5554 if (description_ != nil) {
5555 [description_ release];
5559 if (source_ != nil) {
5564 if (badge_ != nil) {
5569 if (placard_ != nil) {
5579 [self clearPackage];
5583 - (PackageCell *) init {
5584 CGRect frame(CGRectMake(0, 0, 320, 74));
5585 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5586 UIView *content([self contentView]);
5587 CGRect bounds([content bounds]);
5589 content_ = [[ContentView alloc] initWithFrame:bounds];
5590 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5591 [content addSubview:content_];
5593 [content_ setDelegate:self];
5594 [content_ setOpaque:YES];
5598 - (NSString *) accessibilityLabel {
5599 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5602 - (void) setPackage:(Package *)package {
5603 [self clearPackage];
5606 Source *source = [package source];
5608 icon_ = [[package icon] retain];
5609 name_ = [[package name] retain];
5612 description_ = [package longDescription];
5613 if (description_ == nil)
5614 description_ = [package shortDescription];
5615 if (description_ != nil)
5616 description_ = [description_ retain];
5618 commercial_ = [package isCommercial];
5620 package_ = [package retain];
5622 NSString *label = nil;
5623 bool trusted = false;
5625 if (source != nil) {
5626 label = [source label];
5627 trusted = [source trusted];
5628 } else if ([[package id] isEqualToString:@"firmware"])
5629 label = UCLocalize("APPLE");
5631 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5633 NSString *from(label);
5635 NSString *section = [package simpleSection];
5636 if (section != nil && ![section isEqualToString:label]) {
5637 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5638 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5641 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5642 source_ = [from retain];
5644 if (NSString *purpose = [package primaryPurpose])
5645 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5646 badge_ = [badge_ retain];
5651 if (NSString *mode = [package_ mode]) {
5652 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5653 color = RemovingColor_;
5654 //placard = @"removing";
5656 color = InstallingColor_;
5657 //placard = @"installing";
5660 // XXX: the removing/installing placards are not @2x
5663 color = [UIColor whiteColor];
5665 if ([package installed] != nil)
5666 placard = @"installed";
5671 [content_ setBackgroundColor:color];
5674 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5675 placard_ = [placard_ retain];
5677 [self setNeedsDisplay];
5678 [content_ setNeedsDisplay];
5681 - (void) drawContentRect:(CGRect)rect {
5682 bool highlighted(highlighted_);
5683 float width([self bounds].size.width);
5686 CGContextRef context(UIGraphicsGetCurrentContext());
5687 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5688 CGContextFillRect(context, rect);
5693 rect.size = [icon_ size];
5695 rect.size.width /= 2;
5696 rect.size.height /= 2;
5698 rect.origin.x = 25 - rect.size.width / 2;
5699 rect.origin.y = 25 - rect.size.height / 2;
5701 [icon_ drawInRect:rect];
5704 if (badge_ != nil) {
5706 rect.size = [badge_ size];
5708 rect.size.width /= 2;
5709 rect.size.height /= 2;
5711 rect.origin.x = 36 - rect.size.width / 2;
5712 rect.origin.y = 36 - rect.size.height / 2;
5714 [badge_ drawInRect:rect];
5721 UISetColor(commercial_ ? Purple_ : Black_);
5722 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5723 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5726 UISetColor(commercial_ ? Purplish_ : Gray_);
5727 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5729 if (placard_ != nil)
5730 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5735 /* Section Cell {{{ */
5736 @interface SectionCell : CYTableViewCell <
5748 - (void) setSection:(Section *)section editing:(BOOL)editing;
5752 @implementation SectionCell
5754 - (void) clearSection {
5755 if (basic_ != nil) {
5760 if (section_ != nil) {
5770 if (count_ != nil) {
5777 [self clearSection];
5783 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5784 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5785 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5786 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5787 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5789 UIView *content([self contentView]);
5790 CGRect bounds([content bounds]);
5792 content_ = [[ContentView alloc] initWithFrame:bounds];
5793 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5794 [content addSubview:content_];
5795 [content_ setBackgroundColor:[UIColor whiteColor]];
5797 [content_ setDelegate:self];
5801 - (void) onSwitch:(id)sender {
5802 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5803 if (metadata == nil) {
5804 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5805 [Sections_ setObject:metadata forKey:basic_];
5808 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5812 - (void) setSection:(Section *)section editing:(BOOL)editing {
5813 if (editing != editing_) {
5815 [switch_ removeFromSuperview];
5817 [self addSubview:switch_];
5821 [self clearSection];
5823 if (section == nil) {
5824 name_ = [UCLocalize("ALL_PACKAGES") retain];
5827 basic_ = [section name];
5829 basic_ = [basic_ retain];
5831 section_ = [section localized];
5832 if (section_ != nil)
5833 section_ = [section_ retain];
5835 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5836 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5839 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5842 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5843 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5845 [content_ setNeedsDisplay];
5848 - (void) setFrame:(CGRect)frame {
5849 [super setFrame:frame];
5851 CGRect rect([switch_ frame]);
5852 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5855 - (NSString *) accessibilityLabel {
5859 - (void) drawContentRect:(CGRect)rect {
5860 bool highlighted(highlighted_ && !editing_);
5862 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5867 float width(rect.size.width);
5873 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5875 CGSize size = [count_ sizeWithFont:Font14_];
5879 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5885 /* File Table {{{ */
5886 @interface FileTable : CYViewController <
5887 UITableViewDataSource,
5890 _transient Database *database_;
5893 NSMutableArray *files_;
5897 - (id) initWithDatabase:(Database *)database;
5898 - (void) setPackage:(Package *)package;
5902 @implementation FileTable
5905 [self releaseSubviews];
5914 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5915 return files_ == nil ? 0 : [files_ count];
5918 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5922 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5923 static NSString *reuseIdentifier = @"Cell";
5925 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5927 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5928 [cell setFont:[UIFont systemFontOfSize:16]];
5930 [cell setText:[files_ objectAtIndex:indexPath.row]];
5931 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5936 - (NSURL *) navigationURL {
5937 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5941 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5943 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5944 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5945 [list_ setRowHeight:24.0f];
5946 [list_ setDataSource:self];
5947 [list_ setDelegate:self];
5948 [[self view] addSubview:list_];
5951 - (void) viewDidLoad {
5952 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5955 - (void) releaseSubviews {
5960 - (id) initWithDatabase:(Database *)database {
5961 if ((self = [super init]) != nil) {
5962 database_ = database;
5964 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5968 - (void) setPackage:(Package *)package {
5969 if (package_ != nil) {
5970 [package_ autorelease];
5979 [files_ removeAllObjects];
5981 if (package != nil) {
5982 package_ = [package retain];
5983 name_ = [[package id] retain];
5985 if (NSArray *files = [package files])
5986 [files_ addObjectsFromArray:files];
5988 if ([files_ count] != 0) {
5989 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5990 [files_ removeObjectAtIndex:0];
5991 [files_ sortUsingSelector:@selector(compareByPath:)];
5993 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5994 [stack addObject:@"/"];
5996 for (int i(0), e([files_ count]); i != e; ++i) {
5997 NSString *file = [files_ objectAtIndex:i];
5998 while (![file hasPrefix:[stack lastObject]])
5999 [stack removeLastObject];
6000 NSString *directory = [stack lastObject];
6001 [stack addObject:[file stringByAppendingString:@"/"]];
6002 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6003 ([stack count] - 2) * 3, "",
6004 [file substringFromIndex:[directory length]]
6013 - (void) reloadData {
6016 [self setPackage:[database_ packageWithName:name_]];
6021 /* Package Controller {{{ */
6022 @interface CYPackageController : CYBrowserController <
6023 UIActionSheetDelegate
6025 _transient Database *database_;
6026 _H<Package> package_;
6029 _H<NSMutableArray> buttons_;
6030 _H<UIBarButtonItem> button_;
6033 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
6037 @implementation CYPackageController
6039 - (NSURL *) navigationURL {
6040 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6043 /* XXX: this is not safe at all... localization of /fail/ */
6044 - (void) _clickButtonWithName:(NSString *)name {
6045 if ([name isEqualToString:UCLocalize("CLEAR")])
6046 [delegate_ clearPackage:package_];
6047 else if ([name isEqualToString:UCLocalize("INSTALL")])
6048 [delegate_ installPackage:package_];
6049 else if ([name isEqualToString:UCLocalize("REINSTALL")])
6050 [delegate_ installPackage:package_];
6051 else if ([name isEqualToString:UCLocalize("REMOVE")])
6052 [delegate_ removePackage:package_];
6053 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6054 [delegate_ installPackage:package_];
6055 else _assert(false);
6058 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6059 NSString *context([sheet context]);
6061 if ([context isEqualToString:@"modify"]) {
6062 if (button != [sheet cancelButtonIndex]) {
6063 NSString *buttonName = [buttons_ objectAtIndex:button];
6064 [self _clickButtonWithName:buttonName];
6067 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6071 - (bool) _allowJavaScriptPanel {
6076 - (void) _customButtonClicked {
6077 int count([buttons_ count]);
6082 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6084 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6085 [buttons addObjectsFromArray:buttons_];
6087 UIActionSheet *sheet = [[[UIActionSheet alloc]
6090 cancelButtonTitle:nil
6091 destructiveButtonTitle:nil
6092 otherButtonTitles:nil
6095 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6097 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6098 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6100 [sheet setContext:@"modify"];
6102 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6106 // We don't want to allow non-commercial packages to do custom things to the install button,
6107 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6108 - (void) customButtonClicked {
6110 [super customButtonClicked];
6112 [self _customButtonClicked];
6115 - (void) reloadButtonClicked {
6116 // Don't reload a commerical package by tapping the loading button,
6117 // but if it's not an Install button, we should forward it on.
6118 if (![package_ uninstalled])
6119 [self _customButtonClicked];
6122 - (void) applyLoadingTitle {
6123 // Don't show "Loading" as the title. Ever.
6126 - (UIBarButtonItem *) rightButton {
6131 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
6132 if ((self = [super init]) != nil) {
6133 database_ = database;
6134 buttons_ = [NSMutableArray arrayWithCapacity:4];
6135 name_ = [NSString stringWithString:name];
6136 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
6140 - (void) reloadData {
6141 package_ = [database_ packageWithName:name_];
6143 [buttons_ removeAllObjects];
6145 if (package_ != nil) {
6146 [(Package *) package_ parse];
6148 commercial_ = [package_ isCommercial];
6150 if ([package_ mode] != nil)
6151 [buttons_ addObject:UCLocalize("CLEAR")];
6152 if ([package_ source] == nil);
6153 else if ([package_ upgradableAndEssential:NO])
6154 [buttons_ addObject:UCLocalize("UPGRADE")];
6155 else if ([package_ uninstalled])
6156 [buttons_ addObject:UCLocalize("INSTALL")];
6158 [buttons_ addObject:UCLocalize("REINSTALL")];
6159 if (![package_ uninstalled])
6160 [buttons_ addObject:UCLocalize("REMOVE")];
6164 switch ([buttons_ count]) {
6165 case 0: title = nil; break;
6166 case 1: title = [buttons_ objectAtIndex:0]; break;
6167 default: title = UCLocalize("MODIFY"); break;
6170 button_ = [[[UIBarButtonItem alloc]
6172 style:UIBarButtonItemStylePlain
6174 action:@selector(customButtonClicked)
6180 - (bool) isLoading {
6181 return commercial_ ? [super isLoading] : false;
6187 /* Package List Controller {{{ */
6188 @interface PackageListController : CYViewController <
6189 UITableViewDataSource,
6192 _transient Database *database_;
6194 NSMutableArray *packages_;
6195 NSMutableArray *sections_;
6197 NSMutableArray *index_;
6198 NSMutableDictionary *indices_;
6202 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6203 - (void) setDelegate:(id)delegate;
6204 - (void) resetCursor;
6208 @implementation PackageListController
6211 [packages_ release];
6212 [sections_ release];
6221 - (void) deselectWithAnimation:(BOOL)animated {
6222 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6225 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6226 CGRect base = [[self view] bounds];
6227 base.size.height -= bounds.size.height;
6228 base.origin = [list_ frame].origin;
6230 [UIView beginAnimations:nil context:NULL];
6231 [UIView setAnimationBeginsFromCurrentState:YES];
6232 [UIView setAnimationCurve:curve];
6233 [UIView setAnimationDuration:duration];
6234 [list_ setFrame:base];
6235 [UIView commitAnimations];
6238 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6239 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6242 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6243 [self resizeForKeyboardBounds:bounds duration:0];
6246 - (void) keyboardWillShow:(NSNotification *)notification {
6249 NSTimeInterval duration;
6250 UIViewAnimationCurve curve;
6251 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6252 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6253 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6254 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6256 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);
6257 UIViewController *base = self;
6258 while ([base parentViewController] != nil)
6259 base = [base parentViewController];
6260 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6261 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6263 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6266 - (void) keyboardWillHide:(NSNotification *)notification {
6267 NSTimeInterval duration;
6268 UIViewAnimationCurve curve;
6269 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6270 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6272 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6275 - (void) viewWillAppear:(BOOL)animated {
6276 [super viewWillAppear:animated];
6278 [self resizeForKeyboardBounds:CGRectZero];
6279 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6280 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6283 - (void) viewWillDisappear:(BOOL)animated {
6284 [super viewWillDisappear:animated];
6286 [self resizeForKeyboardBounds:CGRectZero];
6287 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6288 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6291 - (void) viewDidAppear:(BOOL)animated {
6292 [super viewDidAppear:animated];
6293 [self deselectWithAnimation:animated];
6296 - (void) didSelectPackage:(Package *)package {
6297 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6298 [view setDelegate:delegate_];
6299 [[self navigationController] pushViewController:view animated:YES];
6302 #if TryIndexedCollation
6303 + (BOOL) hasIndexedCollation {
6304 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6308 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6309 NSInteger count([sections_ count]);
6310 return count == 0 ? 1 : count;
6313 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6314 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6316 return [[sections_ objectAtIndex:section] name];
6319 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6320 if ([sections_ count] == 0)
6322 return [[sections_ objectAtIndex:section] count];
6325 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6326 @synchronized (database_) {
6327 if ([database_ era] != era_)
6330 Section *section([sections_ objectAtIndex:[path section]]);
6331 NSInteger row([path row]);
6332 Package *package([packages_ objectAtIndex:([section row] + row)]);
6333 return [[package retain] autorelease];
6336 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6337 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6339 cell = [[[PackageCell alloc] init] autorelease];
6340 [cell setPackage:[self packageAtIndexPath:path]];
6344 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6345 Package *package([self packageAtIndexPath:path]);
6346 package = [database_ packageWithName:[package id]];
6347 [self didSelectPackage:package];
6350 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6351 // XXX: is 20 the most optimal number here?
6352 return [packages_ count] > 20 ? index_ : nil;
6355 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6356 #if TryIndexedCollation
6357 if ([[self class] hasIndexedCollation]) {
6358 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6365 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6366 if ((self = [super init]) != nil) {
6367 database_ = database;
6368 title_ = [title copy];
6369 [[self navigationItem] setTitle:title_];
6371 #if TryIndexedCollation
6372 if ([[self class] hasIndexedCollation])
6373 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6376 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6378 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6380 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6381 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6383 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6384 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6385 [list_ setRowHeight:73];
6386 [[self view] addSubview:list_];
6388 [list_ setDataSource:self];
6389 [list_ setDelegate:self];
6393 - (void) setDelegate:(id)delegate {
6394 delegate_ = delegate;
6397 - (bool) hasPackage:(Package *)package {
6401 - (void) reloadData {
6404 era_ = [database_ era];
6405 NSArray *packages = [database_ packages];
6407 [packages_ removeAllObjects];
6408 [sections_ removeAllObjects];
6410 _profile(PackageTable$reloadData$Filter)
6411 for (Package *package in packages)
6412 if ([self hasPackage:package])
6413 [packages_ addObject:package];
6416 [indices_ removeAllObjects];
6418 Section *section = nil;
6420 #if TryIndexedCollation
6421 if ([[self class] hasIndexedCollation]) {
6422 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6423 NSArray *titles = [collation sectionIndexTitles];
6426 _profile(PackageTable$reloadData$Section)
6427 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6431 _profile(PackageTable$reloadData$Section$Package)
6432 package = [packages_ objectAtIndex:offset];
6433 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6436 while (secidx < index) {
6439 _profile(PackageTable$reloadData$Section$Allocate)
6440 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6443 _profile(PackageTable$reloadData$Section$Add)
6444 [sections_ addObject:section];
6448 [section addToCount];
6454 [index_ removeAllObjects];
6456 _profile(PackageTable$reloadData$Section)
6457 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6461 _profile(PackageTable$reloadData$Section$Package)
6462 package = [packages_ objectAtIndex:offset];
6463 index = [package index];
6466 if (section == nil || [section index] != index) {
6467 _profile(PackageTable$reloadData$Section$Allocate)
6468 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6471 [index_ addObject:[section name]];
6472 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6474 _profile(PackageTable$reloadData$Section$Add)
6475 [sections_ addObject:section];
6479 [section addToCount];
6484 _profile(PackageTable$reloadData$List)
6489 - (void) resetCursor {
6490 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6495 /* Filtered Package List Controller {{{ */
6496 @interface FilteredPackageListController : PackageListController {
6502 - (void) setObject:(id)object;
6503 - (void) setObject:(id)object forFilter:(SEL)filter;
6505 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6509 @implementation FilteredPackageListController
6517 - (void) setFilter:(SEL)filter {
6520 /* XXX: this is an unsafe optimization of doomy hell */
6521 Method method(class_getInstanceMethod([Package class], filter));
6522 _assert(method != NULL);
6523 imp_ = method_getImplementation(method);
6524 _assert(imp_ != NULL);
6527 - (void) setObject:(id)object {
6533 object_ = [object retain];
6536 - (void) setObject:(id)object forFilter:(SEL)filter {
6537 [self setFilter:filter];
6538 [self setObject:object];
6541 - (bool) hasPackage:(Package *)package {
6542 _profile(FilteredPackageTable$hasPackage)
6543 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6547 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6548 if ((self = [super initWithDatabase:database title:title]) != nil) {
6549 [self setFilter:filter];
6550 [self setObject:object];
6557 /* Home Controller {{{ */
6558 @interface HomeController : CYBrowserController {
6563 @implementation HomeController
6566 if ((self = [super init]) != nil) {
6567 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6571 - (NSURL *) navigationURL {
6572 return [NSURL URLWithString:@"cydia://home"];
6575 - (void) aboutButtonClicked {
6576 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6578 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6579 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6580 [alert setCancelButtonIndex:0];
6583 @"Copyright (C) 2008-2011\n"
6584 "Jay Freeman (saurik)\n"
6585 "saurik@saurik.com\n"
6586 "http://www.saurik.com/"
6592 - (void) viewDidLoad {
6593 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6594 initWithTitle:UCLocalize("ABOUT")
6595 style:UIBarButtonItemStylePlain
6597 action:@selector(aboutButtonClicked)
6603 /* Manage Controller {{{ */
6604 @interface ManageController : CYBrowserController {
6607 - (void) queueStatusDidChange;
6611 @implementation ManageController
6614 if ((self = [super init]) != nil) {
6615 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6619 - (NSURL *) navigationURL {
6620 return [NSURL URLWithString:@"cydia://manage"];
6623 - (void) viewDidLoad {
6624 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6625 initWithTitle:UCLocalize("SETTINGS")
6626 style:UIBarButtonItemStylePlain
6628 action:@selector(settingsButtonClicked)
6631 [self queueStatusDidChange];
6634 - (void) settingsButtonClicked {
6635 [delegate_ showSettings];
6639 - (void) queueButtonClicked {
6643 - (void) applyLoadingTitle {
6644 // Disable "Loading" title.
6647 - (void) applyRightButton {
6648 // Disable right button.
6652 - (void) queueStatusDidChange {
6654 if (!IsWildcat_ && Queuing_) {
6655 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6656 initWithTitle:UCLocalize("QUEUE")
6657 style:UIBarButtonItemStyleDone
6659 action:@selector(queueButtonClicked)
6662 [[self navigationItem] setRightBarButtonItem:nil];
6667 - (bool) isLoading {
6668 // Never show as loading.
6675 /* Refresh Bar {{{ */
6676 @interface RefreshBar : UINavigationBar {
6677 UIProgressIndicator *indicator_;
6678 UITextLabel *prompt_;
6679 UIProgressBar *progress_;
6680 UINavigationButton *cancel_;
6685 @implementation RefreshBar
6688 [indicator_ release];
6690 [progress_ release];
6695 - (void) positionViews {
6696 CGRect frame = [cancel_ frame];
6697 frame.size = [cancel_ sizeThatFits:frame.size];
6698 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6699 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6700 [cancel_ setFrame:frame];
6702 CGSize prgsize = {75, 100};
6704 [self frame].size.width - prgsize.width - 10,
6705 ([self frame].size.height - prgsize.height) / 2
6707 [progress_ setFrame:prgrect];
6709 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6710 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6711 CGRect indrect = {{indoffset, indoffset}, indsize};
6712 [indicator_ setFrame:indrect];
6714 CGSize prmsize = {215, indsize.height + 4};
6716 indoffset * 2 + indsize.width,
6717 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6719 [prompt_ setFrame:prmrect];
6722 - (void) setFrame:(CGRect)frame {
6723 [super setFrame:frame];
6724 [self positionViews];
6727 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6728 if ((self = [super initWithFrame:frame]) != nil) {
6729 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6731 [self setBarStyle:UIBarStyleBlack];
6733 UIBarStyle barstyle([self _barStyle:NO]);
6734 bool ugly(barstyle == UIBarStyleDefault);
6736 UIProgressIndicatorStyle style = ugly ?
6737 UIProgressIndicatorStyleMediumBrown :
6738 UIProgressIndicatorStyleMediumWhite;
6740 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6741 [indicator_ setStyle:style];
6742 [indicator_ startAnimation];
6743 [self addSubview:indicator_];
6745 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6746 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6747 [prompt_ setBackgroundColor:[UIColor clearColor]];
6748 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6749 [self addSubview:prompt_];
6751 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6752 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6753 [progress_ setStyle:0];
6754 [self addSubview:progress_];
6756 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6757 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6758 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6759 [cancel_ setBarStyle:barstyle];
6761 [self positionViews];
6765 - (void) setCancellable:(bool)cancellable {
6767 [self addSubview:cancel_];
6769 [cancel_ removeFromSuperview];
6773 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6774 [progress_ setProgress:0];
6778 [self setCancellable:NO];
6781 - (void) setPrompt:(NSString *)prompt {
6782 [prompt_ setText:prompt];
6785 - (void) setProgress:(float)progress {
6786 [progress_ setProgress:progress];
6792 @class CYNavigationController;
6794 /* Cydia Tab Bar Controller {{{ */
6795 @interface CYTabBarController : UITabBarController <
6796 UITabBarControllerDelegate,
6799 _transient Database *database_;
6800 RefreshBar *refreshbar_;
6804 // XXX: ok, "updatedelegate_"?...
6805 _transient NSObject<CydiaDelegate> *updatedelegate_;
6808 UIViewController *remembered_;
6809 _transient UIViewController *transient_;
6812 - (NSArray *) navigationURLCollection;
6813 - (void) dropBar:(BOOL)animated;
6814 - (void) beginUpdate;
6815 - (void) raiseBar:(BOOL)animated;
6820 @implementation CYTabBarController
6822 - (void) setUnselectedViewController:(UIViewController *)transient {
6823 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6824 if (transient != nil) {
6825 if (transient_ == nil)
6826 remembered_ = [[controllers objectAtIndex:0] retain];
6827 transient_ = transient;
6828 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6829 [controllers replaceObjectAtIndex:0 withObject:transient_];
6830 [self setSelectedIndex:0];
6831 [self setViewControllers:controllers];
6832 [self concealTabBarSelection];
6833 } else if (remembered_ != nil) {
6834 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6835 transient_ = transient;
6836 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6837 [remembered_ release];
6839 [self setViewControllers:controllers];
6840 [self revealTabBarSelection];
6844 - (UIViewController *) unselectedViewController {
6848 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6849 if ([self unselectedViewController])
6850 [self setUnselectedViewController:nil];
6853 - (NSArray *) navigationURLCollection {
6854 NSMutableArray *items([NSMutableArray array]);
6856 // XXX: Should this deal with transient view controllers?
6857 for (id navigation in [self viewControllers]) {
6858 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6860 [items addObject:stack];
6866 - (void) reloadData {
6867 for (CYViewController *controller in [self viewControllers])
6868 [controller reloadData];
6870 [(CYNavigationController *)[self unselectedViewController] reloadData];
6874 [refreshbar_ release];
6875 [[NSNotificationCenter defaultCenter] removeObserver:self];
6880 - (id) initWithDatabase:(Database *)database {
6881 if ((self = [super init]) != nil) {
6882 database_ = database;
6883 [self setDelegate:self];
6885 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6886 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6888 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6892 - (void) setUpdate:(NSDate *)date {
6896 - (void) beginUpdate {
6897 [refreshbar_ start];
6900 [updatedelegate_ retainNetworkActivityIndicator];
6904 detachNewThreadSelector:@selector(performUpdate)
6910 - (void) performUpdate { _pooled
6912 status.setDelegate(self);
6913 [database_ updateWithStatus:status];
6916 performSelectorOnMainThread:@selector(completeUpdate)
6922 - (void) stopUpdateWithSelector:(SEL)selector {
6924 [updatedelegate_ releaseNetworkActivityIndicator];
6926 [self raiseBar:YES];
6929 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6932 - (void) completeUpdate {
6935 [self stopUpdateWithSelector:@selector(reloadData)];
6938 - (void) cancelUpdate {
6939 [self stopUpdateWithSelector:@selector(updateData)];
6942 - (void) cancelPressed {
6943 [self cancelUpdate];
6950 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6951 [refreshbar_ setPrompt:[event compoundMessage]];
6954 - (bool) isProgressCancelled {
6958 - (void) setProgressCancellable:(NSNumber *)cancellable {
6959 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6962 - (void) setProgressPercent:(NSNumber *)percent {
6963 [refreshbar_ setProgress:[percent floatValue]];
6966 - (void) setProgressStatus:(NSDictionary *)status {
6968 [self setProgressPercent:[status objectForKey:@"Percent"]];
6971 - (void) setUpdateDelegate:(id)delegate {
6972 updatedelegate_ = delegate;
6975 - (CGFloat) statusBarHeight {
6976 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6977 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6979 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6983 - (UIView *) transitionView {
6984 if ([self respondsToSelector:@selector(_transitionView)])
6985 return [self _transitionView];
6987 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6990 - (void) dropBar:(BOOL)animated {
6995 UIView *transition([self transitionView]);
6996 [[self view] addSubview:refreshbar_];
6998 CGRect barframe([refreshbar_ frame]);
7000 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
7001 barframe.origin.y = [self statusBarHeight];
7003 barframe.origin.y = 0;
7005 [refreshbar_ setFrame:barframe];
7008 [UIView beginAnimations:nil context:NULL];
7010 CGRect viewframe = [transition frame];
7011 viewframe.origin.y += barframe.size.height;
7012 viewframe.size.height -= barframe.size.height;
7013 [transition setFrame:viewframe];
7016 [UIView commitAnimations];
7018 // Ensure bar has the proper width for our view, it might have changed
7019 barframe.size.width = viewframe.size.width;
7020 [refreshbar_ setFrame:barframe];
7022 // XXX: fix Apple's layout bug
7023 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7026 - (void) raiseBar:(BOOL)animated {
7031 UIView *transition([self transitionView]);
7032 [refreshbar_ removeFromSuperview];
7034 CGRect barframe([refreshbar_ frame]);
7037 [UIView beginAnimations:nil context:NULL];
7039 CGRect viewframe = [transition frame];
7040 viewframe.origin.y -= barframe.size.height;
7041 viewframe.size.height += barframe.size.height;
7042 [transition setFrame:viewframe];
7045 [UIView commitAnimations];
7047 // XXX: fix Apple's layout bug
7048 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7052 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7053 // XXX: fix Apple's layout bug
7054 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7058 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7059 bool dropped(dropped_);
7064 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7069 // XXX: fix Apple's layout bug
7070 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7073 - (void) statusBarFrameChanged:(NSNotification *)notification {
7082 /* Cydia Navigation Controller {{{ */
7083 @interface CYNavigationController : UINavigationController {
7084 _transient Database *database_;
7085 _transient id<UINavigationControllerDelegate> delegate_;
7088 - (NSArray *) navigationURLCollection;
7089 - (id) initWithDatabase:(Database *)database;
7090 - (void) reloadData;
7095 @implementation CYNavigationController
7097 - (NSArray *) navigationURLCollection {
7098 NSMutableArray *stack([NSMutableArray array]);
7100 for (CYViewController *controller in [self viewControllers]) {
7101 NSString *url = [[controller navigationURL] absoluteString];
7103 [stack addObject:url];
7109 - (void) reloadData {
7110 for (CYViewController *page in [self viewControllers]) {
7111 // Only reload controllers that have already loaded.
7112 // This prevents a page from accidentally loading too
7113 // early if it hasn't been shown on the screen yet.
7114 if ([page hasLoaded])
7119 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
7120 delegate_ = delegate;
7123 - (id) initWithDatabase:(Database *)database {
7124 if ((self = [super init]) != nil) {
7125 database_ = database;
7132 /* Cydia:// Protocol {{{ */
7133 @interface CydiaURLProtocol : NSURLProtocol {
7138 @implementation CydiaURLProtocol
7140 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7141 NSURL *url([request URL]);
7145 NSString *scheme([[url scheme] lowercaseString]);
7146 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7148 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7154 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7158 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7159 id<NSURLProtocolClient> client([self client]);
7161 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7163 NSData *data(UIImagePNGRepresentation(icon));
7165 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7166 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7167 [client URLProtocol:self didLoadData:data];
7168 [client URLProtocolDidFinishLoading:self];
7172 - (void) startLoading {
7173 id<NSURLProtocolClient> client([self client]);
7174 NSURLRequest *request([self request]);
7176 NSURL *url([request URL]);
7177 NSString *href([url absoluteString]);
7178 NSString *scheme([[url scheme] lowercaseString]);
7182 if ([scheme isEqualToString:@"cydia"])
7183 path = [href substringFromIndex:8];
7184 else if ([scheme isEqualToString:@"about"])
7185 path = [href substringFromIndex:12];
7186 else _assert(false);
7188 NSRange slash([path rangeOfString:@"/"]);
7191 if (slash.location == NSNotFound) {
7195 command = [path substringToIndex:slash.location];
7196 path = [path substringFromIndex:(slash.location + 1)];
7199 Database *database([Database sharedInstance]);
7201 if ([command isEqualToString:@"package-icon"]) {
7204 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7205 Package *package([database packageWithName:path]);
7208 UIImage *icon([package icon]);
7209 [self _returnPNGWithImage:icon forRequest:request];
7210 } else if ([command isEqualToString:@"source-icon"]) {
7213 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7214 NSString *source(Simplify(path));
7215 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7217 icon = [UIImage applicationImageNamed:@"unknown.png"];
7218 [self _returnPNGWithImage:icon forRequest:request];
7219 } else if ([command isEqualToString:@"uikit-image"]) {
7222 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7223 UIImage *icon(_UIImageWithName(path));
7224 [self _returnPNGWithImage:icon forRequest:request];
7225 } else if ([command isEqualToString:@"section-icon"]) {
7228 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7229 NSString *section(Simplify(path));
7230 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7232 icon = [UIImage applicationImageNamed:@"unknown.png"];
7233 [self _returnPNGWithImage:icon forRequest:request];
7235 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7239 - (void) stopLoading {
7245 /* Section Controller {{{ */
7246 @interface SectionController : FilteredPackageListController {
7247 _H<NSString> section_;
7250 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7254 @implementation SectionController
7256 - (NSURL *) navigationURL {
7257 NSString *name = section_;
7261 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7264 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7267 title = UCLocalize("ALL_PACKAGES");
7268 else if (![name isEqual:@""])
7269 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7271 title = UCLocalize("NO_SECTION");
7273 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7280 /* Sections Controller {{{ */
7281 @interface SectionsController : CYViewController <
7282 UITableViewDataSource,
7285 _transient Database *database_;
7286 NSMutableArray *sections_;
7287 NSMutableArray *filtered_;
7291 - (id) initWithDatabase:(Database *)database;
7292 - (void) editButtonClicked;
7296 @implementation SectionsController
7299 [self releaseSubviews];
7300 [sections_ release];
7301 [filtered_ release];
7306 - (NSURL *) navigationURL {
7307 return [NSURL URLWithString:@"cydia://sections"];
7310 - (void) updateNavigationItem {
7311 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7312 if ([sections_ count] == 0) {
7313 [[self navigationItem] setRightBarButtonItem:nil];
7315 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7316 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7318 action:@selector(editButtonClicked)
7319 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7323 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7324 [super setEditing:editing animated:animated];
7329 [delegate_ updateData];
7331 [self updateNavigationItem];
7334 - (void) viewDidAppear:(BOOL)animated {
7335 [super viewDidAppear:animated];
7336 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7339 - (void) viewWillDisappear:(BOOL)animated {
7340 [super viewWillDisappear:animated];
7341 if ([self isEditing]) [self setEditing:NO];
7344 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7345 Section *section = nil;
7346 int index = [indexPath row];
7347 if (![self isEditing]) {
7350 section = [filtered_ objectAtIndex:index];
7352 section = [sections_ objectAtIndex:index];
7357 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7358 if ([self isEditing])
7359 return [sections_ count];
7361 return [filtered_ count] + 1;
7364 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7368 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7369 static NSString *reuseIdentifier = @"SectionCell";
7371 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7373 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7375 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7380 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7381 if ([self isEditing])
7384 Section *section = [self sectionAtIndexPath:indexPath];
7386 SectionController *controller = [[[SectionController alloc]
7387 initWithDatabase:database_
7388 section:[section name]
7390 [controller setDelegate:delegate_];
7392 [[self navigationController] pushViewController:controller animated:YES];
7396 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7398 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7399 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7400 [list_ setRowHeight:45.0f];
7401 [list_ setDataSource:self];
7402 [list_ setDelegate:self];
7403 [[self view] addSubview:list_];
7406 - (void) viewDidLoad {
7407 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7410 - (void) releaseSubviews {
7415 - (id) initWithDatabase:(Database *)database {
7416 if ((self = [super init]) != nil) {
7417 database_ = database;
7419 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7420 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7424 - (void) reloadData {
7427 NSArray *packages = [database_ packages];
7429 [sections_ removeAllObjects];
7430 [filtered_ removeAllObjects];
7432 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7435 for (Package *package in packages) {
7436 NSString *name([package section]);
7437 NSString *key(name == nil ? @"" : name);
7441 _profile(SectionsView$reloadData$Section)
7442 section = [sections objectForKey:key];
7443 if (section == nil) {
7444 _profile(SectionsView$reloadData$Section$Allocate)
7445 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7446 [sections setObject:section forKey:key];
7451 [section addToCount];
7453 _profile(SectionsView$reloadData$Filter)
7454 if (![package valid] || ![package visible])
7462 [sections_ addObjectsFromArray:[sections allValues]];
7464 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7466 for (Section *section in sections_) {
7467 size_t count([section row]);
7471 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7472 [section setCount:count];
7473 [filtered_ addObject:section];
7476 [self updateNavigationItem];
7481 - (void) editButtonClicked {
7482 [self setEditing:![self isEditing] animated:YES];
7488 /* Changes Controller {{{ */
7489 @interface ChangesController : CYViewController <
7490 UITableViewDataSource,
7493 _transient Database *database_;
7495 CFMutableArrayRef packages_;
7496 NSMutableArray *sections_;
7499 BOOL hasSentFirstLoad_;
7502 - (id) initWithDatabase:(Database *)database;
7506 @implementation ChangesController
7509 [self releaseSubviews];
7510 CFRelease(packages_);
7511 [sections_ release];
7516 - (NSURL *) navigationURL {
7517 return [NSURL URLWithString:@"cydia://changes"];
7520 - (void) viewWillAppear:(BOOL)animated {
7521 // Loads after it appears, so don't load beforehand.
7523 [super viewWillAppear:animated];
7526 - (void) viewDidAppear:(BOOL)animated {
7527 [super viewDidAppear:animated];
7529 if (!hasSentFirstLoad_) {
7530 hasSentFirstLoad_ = YES;
7531 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7533 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7537 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7538 NSInteger count([sections_ count]);
7539 return count == 0 ? 1 : count;
7542 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7543 if ([sections_ count] == 0)
7545 return [[sections_ objectAtIndex:section] name];
7548 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7549 if ([sections_ count] == 0)
7551 return [[sections_ objectAtIndex:section] count];
7554 - (Package *) packageAtIndex:(NSUInteger)index {
7555 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7558 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7559 @synchronized (database_) {
7560 if ([database_ era] != era_)
7563 NSUInteger sectionIndex([path section]);
7564 if (sectionIndex >= [sections_ count])
7566 Section *section([sections_ objectAtIndex:sectionIndex]);
7567 NSInteger row([path row]);
7568 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7571 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7572 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7574 cell = [[[PackageCell alloc] init] autorelease];
7575 [cell setPackage:[self packageAtIndexPath:path]];
7579 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7580 Package *package([self packageAtIndexPath:path]);
7581 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7582 [view setDelegate:delegate_];
7583 [[self navigationController] pushViewController:view animated:YES];
7587 - (void) refreshButtonClicked {
7588 [delegate_ beginUpdate];
7589 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7592 - (void) upgradeButtonClicked {
7593 [delegate_ distUpgrade];
7597 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7599 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7600 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7601 [list_ setRowHeight:73];
7602 [list_ setDataSource:self];
7603 [list_ setDelegate:self];
7604 [[self view] addSubview:list_];
7607 - (void) viewDidLoad {
7608 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7611 - (void) releaseSubviews {
7616 - (id) initWithDatabase:(Database *)database {
7617 if ((self = [super init]) != nil) {
7618 database_ = database;
7620 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7621 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7625 // this mostly works because reloadData (below) is @synchronized (database_)
7626 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7627 - (void) _reloadPackages:(NSArray *)packages {
7628 CFRelease(packages_);
7629 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7632 _profile(ChangesController$_reloadPackages$Filter)
7633 for (Package *package in packages)
7634 if ([package upgradableAndEssential:YES] || [package visible])
7635 CFArrayAppendValue(packages_, package);
7638 _profile(ChangesController$_reloadPackages$radixSort)
7639 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7644 - (void) reloadData {
7645 @synchronized (database_) {
7646 era_ = [database_ era];
7647 NSArray *packages = [database_ packages];
7649 [sections_ removeAllObjects];
7652 UIProgressHUD *hud([delegate_ addProgressHUD]);
7653 [hud setText:UCLocalize("LOADING")];
7654 //NSLog(@"HUD:%@::%@", delegate_, hud);
7655 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7656 [delegate_ removeProgressHUD:hud];
7658 [self _reloadPackages:packages];
7661 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7662 Section *ignored = nil;
7663 Section *section = nil;
7667 bool unseens = false;
7669 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7671 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7672 Package *package = [self packageAtIndex:offset];
7674 BOOL uae = [package upgradableAndEssential:YES];
7678 time_t seen([package seen]);
7680 if (section == nil || last != seen) {
7684 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7687 _profile(ChangesController$reloadData$Allocate)
7688 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7689 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7690 [sections_ addObject:section];
7694 [section addToCount];
7695 } else if ([package ignored]) {
7696 if (ignored == nil) {
7697 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7699 [ignored addToCount];
7702 [upgradable addToCount];
7707 CFRelease(formatter);
7710 Section *last = [sections_ lastObject];
7711 size_t count = [last count];
7712 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7713 [sections_ removeLastObject];
7716 if ([ignored count] != 0)
7717 [sections_ insertObject:ignored atIndex:0];
7719 [sections_ insertObject:upgradable atIndex:0];
7724 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7725 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7726 style:UIBarButtonItemStylePlain
7728 action:@selector(upgradeButtonClicked)
7731 if (![delegate_ updating])
7732 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7733 initWithTitle:UCLocalize("REFRESH")
7734 style:UIBarButtonItemStylePlain
7736 action:@selector(refreshButtonClicked)
7744 /* Search Controller {{{ */
7745 @interface SearchController : FilteredPackageListController <
7748 _H<UISearchBar> search_;
7752 - (id) initWithDatabase:(Database *)database;
7753 - (void) setSearchTerm:(NSString *)term;
7754 - (void) reloadData;
7758 @implementation SearchController
7761 [search_ setDelegate:nil];
7765 - (NSURL *) navigationURL {
7766 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7767 return [NSURL URLWithString:@"cydia://search"];
7769 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7772 - (void) setSearchTerm:(NSString *)searchTerm {
7773 [search_ setText:searchTerm];
7777 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7778 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7779 [search_ resignFirstResponder];
7783 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7784 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7788 - (id) initWithDatabase:(Database *)database {
7789 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7790 search_ = [[[UISearchBar alloc] init] autorelease];
7791 [search_ setDelegate:self];
7795 - (void) viewDidAppear:(BOOL)animated {
7796 [super viewDidAppear:animated];
7798 if (!searchloaded_) {
7799 searchloaded_ = YES;
7800 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7801 [search_ layoutSubviews];
7802 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7804 UITextField *textField;
7805 if ([search_ respondsToSelector:@selector(searchField)])
7806 textField = [search_ searchField];
7808 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7810 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7811 [textField setEnablesReturnKeyAutomatically:NO];
7812 [[self navigationItem] setTitleView:textField];
7816 - (void) reloadData {
7817 [self setObject:[search_ text]];
7822 - (void) didSelectPackage:(Package *)package {
7823 [search_ resignFirstResponder];
7824 [super didSelectPackage:package];
7829 /* Package Settings Controller {{{ */
7830 @interface PackageSettingsController : CYViewController <
7831 UITableViewDataSource,
7834 _transient Database *database_;
7837 UITableView *table_;
7838 UISwitch *subscribedSwitch_;
7839 UISwitch *ignoredSwitch_;
7840 UITableViewCell *subscribedCell_;
7841 UITableViewCell *ignoredCell_;
7844 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7848 @implementation PackageSettingsController
7851 [self releaseSubviews];
7858 - (NSURL *) navigationURL {
7859 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7862 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7863 if (package_ == nil)
7866 if ([package_ installed] == nil)
7872 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7873 if (package_ == nil)
7876 // both sections contain just one item right now.
7880 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7884 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7886 return UCLocalize("SHOW_ALL_CHANGES_EX");
7888 return UCLocalize("IGNORE_UPGRADES_EX");
7891 - (void) onSubscribed:(id)control {
7892 bool value([control isOn]);
7893 if (package_ == nil)
7895 if ([package_ setSubscribed:value])
7896 [delegate_ updateData];
7899 - (void) _updateIgnored {
7900 const char *package([name_ UTF8String]);
7901 bool on([ignoredSwitch_ isOn]);
7903 pid_t pid(ExecFork());
7905 FILE *dpkg(popen("dpkg --set-selections", "w"));
7906 fwrite(package, strlen(package), 1, dpkg);
7909 fwrite(" hold\n", 6, 1, dpkg);
7911 fwrite(" install\n", 9, 1, dpkg);
7921 int result(waitpid(pid, &status, 0));
7924 _assert(result == pid);
7930 - (void) onIgnored:(id)control {
7931 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7932 [invocation setTarget:self];
7933 [invocation setSelector:@selector(_updateIgnored)];
7935 [delegate_ reloadDataWithInvocation:invocation];
7938 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7939 if (package_ == nil)
7942 switch ([indexPath section]) {
7943 case 0: return subscribedCell_;
7944 case 1: return ignoredCell_;
7953 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7955 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7956 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7957 [table_ setDataSource:self];
7958 [table_ setDelegate:self];
7959 [[self view] addSubview:table_];
7961 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7962 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7963 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7965 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7966 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7967 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7969 subscribedCell_ = [[UITableViewCell alloc] init];
7970 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7971 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7972 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7974 ignoredCell_ = [[UITableViewCell alloc] init];
7975 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7976 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7977 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7980 - (void) viewDidLoad {
7981 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7984 - (void) releaseSubviews {
7985 [ignoredCell_ release];
7988 [subscribedCell_ release];
7989 subscribedCell_ = nil;
7994 [ignoredSwitch_ release];
7995 ignoredSwitch_ = nil;
7997 [subscribedSwitch_ release];
7998 subscribedSwitch_ = nil;
8001 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8002 if ((self = [super init]) != nil) {
8003 database_ = database;
8004 name_ = [package retain];
8008 - (void) reloadData {
8011 if (package_ != nil)
8012 [package_ autorelease];
8013 package_ = [database_ packageWithName:name_];
8015 if (package_ != nil) {
8016 package_ = [package_ retain];
8017 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8018 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8019 } // XXX: what now, G?
8021 [table_ reloadData];
8027 /* Installed Controller {{{ */
8028 @interface InstalledController : FilteredPackageListController {
8032 - (id) initWithDatabase:(Database *)database;
8034 - (void) updateRoleButton;
8035 - (void) queueStatusDidChange;
8039 @implementation InstalledController
8045 - (NSURL *) navigationURL {
8046 return [NSURL URLWithString:@"cydia://installed"];
8049 - (id) initWithDatabase:(Database *)database {
8050 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8051 [self updateRoleButton];
8052 [self queueStatusDidChange];
8057 - (void) queueButtonClicked {
8062 - (void) queueStatusDidChange {
8066 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8067 initWithTitle:UCLocalize("QUEUE")
8068 style:UIBarButtonItemStyleDone
8070 action:@selector(queueButtonClicked)
8073 [[self navigationItem] setLeftBarButtonItem:nil];
8079 - (void) updateRoleButton {
8080 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8081 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8082 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8083 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8085 action:@selector(roleButtonClicked)
8089 - (void) roleButtonClicked {
8090 [self setObject:[NSNumber numberWithBool:expert_]];
8094 [self updateRoleButton];
8100 /* Source Cell {{{ */
8101 @interface SourceCell : CYTableViewCell <
8109 - (void) setSource:(Source *)source;
8113 @implementation SourceCell
8115 - (void) clearSource {
8125 - (void) setSource:(Source *)source {
8129 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
8131 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8132 icon_ = [icon_ retain];
8134 origin_ = [[source name] retain];
8135 label_ = [[source uri] retain];
8137 [content_ setNeedsDisplay];
8145 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8146 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8147 UIView *content([self contentView]);
8148 CGRect bounds([content bounds]);
8150 content_ = [[ContentView alloc] initWithFrame:bounds];
8151 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8152 [content_ setBackgroundColor:[UIColor whiteColor]];
8153 [content addSubview:content_];
8155 [content_ setDelegate:self];
8156 [content_ setOpaque:YES];
8160 - (NSString *) accessibilityLabel {
8164 - (void) drawContentRect:(CGRect)rect {
8165 bool highlighted(highlighted_);
8166 float width(rect.size.width);
8169 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8176 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8180 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8185 /* Source Controller {{{ */
8186 @interface SourceController : FilteredPackageListController {
8187 _transient Source *source_;
8191 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8195 @implementation SourceController
8197 - (NSURL *) navigationURL {
8198 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8201 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8202 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8204 key_ = [[source key] retain];
8208 - (void) reloadData {
8209 source_ = [database_ sourceWithKey:key_];
8211 key_ = [[source_ key] retain];
8212 [self setObject:source_];
8213 [[self navigationItem] setTitle:[source_ label]];
8220 /* Sources Controller {{{ */
8221 @interface SourcesController : CYViewController <
8222 UITableViewDataSource,
8225 _transient Database *database_;
8227 NSMutableArray *sources_;
8231 UIProgressHUD *hud_;
8234 //NSURLConnection *installer_;
8235 NSURLConnection *trivial_;
8236 NSURLConnection *trivial_bz2_;
8237 NSURLConnection *trivial_gz_;
8238 //NSURLConnection *automatic_;
8243 - (id) initWithDatabase:(Database *)database;
8244 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8248 @implementation SourcesController
8250 - (void) _releaseConnection:(NSURLConnection *)connection {
8251 if (connection != nil) {
8252 [connection cancel];
8253 //[connection setDelegate:nil];
8254 [connection release];
8259 [self releaseSubviews];
8265 //[self _releaseConnection:installer_];
8266 [self _releaseConnection:trivial_];
8267 [self _releaseConnection:trivial_gz_];
8268 [self _releaseConnection:trivial_bz2_];
8269 //[self _releaseConnection:automatic_];
8275 - (NSURL *) navigationURL {
8276 return [NSURL URLWithString:@"cydia://sources"];
8279 - (void) viewDidAppear:(BOOL)animated {
8280 [super viewDidAppear:animated];
8281 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8284 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8285 return offset_ == 0 ? 1 : 2;
8288 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8289 switch (section + (offset_ == 0 ? 1 : 0)) {
8290 case 0: return UCLocalize("ENTERED_BY_USER");
8291 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8297 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8298 int count = [sources_ count];
8300 case 0: return (offset_ == 0 ? count : offset_);
8301 case 1: return count - offset_;
8307 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8309 switch (indexPath.section) {
8310 case 0: idx = indexPath.row; break;
8311 case 1: idx = indexPath.row + offset_; break;
8315 return [sources_ objectAtIndex:idx];
8318 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8319 static NSString *cellIdentifier = @"SourceCell";
8321 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8322 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8323 [cell setSource:[self sourceAtIndexPath:indexPath]];
8324 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8329 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8330 Source *source = [self sourceAtIndexPath:indexPath];
8332 SourceController *controller = [[[SourceController alloc]
8333 initWithDatabase:database_
8337 [controller setDelegate:delegate_];
8339 [[self navigationController] pushViewController:controller animated:YES];
8342 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8343 Source *source = [self sourceAtIndexPath:indexPath];
8344 return [source record] != nil;
8347 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8348 Source *source = [self sourceAtIndexPath:indexPath];
8349 [Sources_ removeObjectForKey:[source key]];
8350 [delegate_ syncData];
8354 [delegate_ addTrivialSource:href_];
8355 [delegate_ syncData];
8358 - (NSString *) getWarning {
8359 NSString *href(href_);
8360 NSRange colon([href rangeOfString:@"://"]);
8361 if (colon.location != NSNotFound)
8362 href = [href substringFromIndex:(colon.location + 3)];
8363 href = [href stringByAddingPercentEscapes];
8364 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8365 href = [href stringByCachingURLWithCurrentCDN];
8367 NSURL *url([NSURL URLWithString:href]);
8369 NSStringEncoding encoding;
8370 NSError *error(nil);
8372 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8373 return [warning length] == 0 ? nil : warning;
8377 - (void) _endConnection:(NSURLConnection *)connection {
8378 // XXX: the memory management in this method is horribly awkward
8380 NSURLConnection **field = NULL;
8381 if (connection == trivial_)
8383 else if (connection == trivial_bz2_)
8384 field = &trivial_bz2_;
8385 else if (connection == trivial_gz_)
8386 field = &trivial_gz_;
8387 _assert(field != NULL);
8388 [connection release];
8393 trivial_bz2_ == nil &&
8399 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8402 UIAlertView *alert = [[[UIAlertView alloc]
8403 initWithTitle:UCLocalize("SOURCE_WARNING")
8406 cancelButtonTitle:UCLocalize("CANCEL")
8408 UCLocalize("ADD_ANYWAY"),
8412 [alert setContext:@"warning"];
8413 [alert setNumberOfRows:1];
8417 } else if (error_ != nil) {
8418 UIAlertView *alert = [[[UIAlertView alloc]
8419 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8420 message:[error_ localizedDescription]
8422 cancelButtonTitle:UCLocalize("OK")
8423 otherButtonTitles:nil
8426 [alert setContext:@"urlerror"];
8429 UIAlertView *alert = [[[UIAlertView alloc]
8430 initWithTitle:UCLocalize("NOT_REPOSITORY")
8431 message:UCLocalize("NOT_REPOSITORY_EX")
8433 cancelButtonTitle:UCLocalize("OK")
8434 otherButtonTitles:nil
8437 [alert setContext:@"trivial"];
8441 [delegate_ releaseNetworkActivityIndicator];
8443 [delegate_ removeProgressHUD:hud_];
8452 if (error_ != nil) {
8459 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8460 switch ([response statusCode]) {
8466 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8467 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8469 error_ = [error retain];
8470 [self _endConnection:connection];
8473 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8474 [self _endConnection:connection];
8477 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8478 NSMutableURLRequest *request = [NSMutableURLRequest
8479 requestWithURL:[NSURL URLWithString:href]
8480 cachePolicy:NSURLRequestUseProtocolCachePolicy
8481 timeoutInterval:120.0
8484 [request setHTTPMethod:method];
8486 if (Machine_ != NULL)
8487 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8488 if (UniqueID_ != nil)
8489 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8491 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8494 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8495 NSString *context([alert context]);
8497 if ([context isEqualToString:@"source"]) {
8500 NSString *href = [[alert textField] text];
8502 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8504 if (![href hasSuffix:@"/"])
8505 href_ = [href stringByAppendingString:@"/"];
8508 href_ = [href_ retain];
8510 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8511 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8512 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8513 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8517 // XXX: this is stupid
8518 hud_ = [[delegate_ addProgressHUD] retain];
8519 [hud_ setText:UCLocalize("VERIFYING_URL")];
8520 [delegate_ retainNetworkActivityIndicator];
8529 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8530 } else if ([context isEqualToString:@"trivial"])
8531 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8532 else if ([context isEqualToString:@"urlerror"])
8533 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8534 else if ([context isEqualToString:@"warning"]) {
8549 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8554 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8556 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8557 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8558 [list_ setRowHeight:56];
8559 [list_ setDataSource:self];
8560 [list_ setDelegate:self];
8561 [[self view] addSubview:list_];
8564 - (void) viewDidLoad {
8565 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8566 [self updateButtonsForEditingStatus:NO animated:NO];
8569 - (void) releaseSubviews {
8574 - (id) initWithDatabase:(Database *)database {
8575 if ((self = [super init]) != nil) {
8576 database_ = database;
8577 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8581 - (void) reloadData {
8585 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8588 [sources_ removeAllObjects];
8589 [sources_ addObjectsFromArray:[database_ sources]];
8591 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8594 int count([sources_ count]);
8596 for (int i = 0; i != count; i++) {
8597 if ([[sources_ objectAtIndex:i] record] == nil)
8602 [list_ setEditing:NO];
8603 [self updateButtonsForEditingStatus:NO animated:NO];
8607 - (void) showAddSourcePrompt {
8608 UIAlertView *alert = [[[UIAlertView alloc]
8609 initWithTitle:UCLocalize("ENTER_APT_URL")
8612 cancelButtonTitle:UCLocalize("CANCEL")
8614 UCLocalize("ADD_SOURCE"),
8618 [alert setContext:@"source"];
8619 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8621 [alert setNumberOfRows:1];
8622 [alert addTextFieldWithValue:@"http://" label:@""];
8624 UITextInputTraits *traits = [[alert textField] textInputTraits];
8625 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8626 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8627 [traits setKeyboardType:UIKeyboardTypeURL];
8628 // XXX: UIReturnKeyDone
8629 [traits setReturnKeyType:UIReturnKeyNext];
8634 - (void) addButtonClicked {
8635 [self showAddSourcePrompt];
8638 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8639 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8640 initWithTitle:UCLocalize("ADD")
8641 style:UIBarButtonItemStylePlain
8643 action:@selector(addButtonClicked)
8644 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8646 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8647 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8648 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8650 action:@selector(editButtonClicked)
8651 ] autorelease] animated:animated];
8653 if (IsWildcat_ && !editing)
8654 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8655 initWithTitle:UCLocalize("SETTINGS")
8656 style:UIBarButtonItemStylePlain
8658 action:@selector(settingsButtonClicked)
8662 - (void) settingsButtonClicked {
8663 [delegate_ showSettings];
8666 - (void) editButtonClicked {
8667 [list_ setEditing:![list_ isEditing] animated:YES];
8669 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8675 /* Settings Controller {{{ */
8676 @interface SettingsController : CYViewController <
8677 UITableViewDataSource,
8680 _transient Database *database_;
8681 // XXX: ok, "roledelegate_"?...
8682 _transient id roledelegate_;
8683 UITableView *table_;
8684 UISegmentedControl *segment_;
8688 - (void) showDoneButton;
8689 - (void) resizeSegmentedControl;
8693 @implementation SettingsController
8696 [self releaseSubviews];
8702 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8704 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8705 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8706 [table_ setDelegate:self];
8707 [table_ setDataSource:self];
8708 [[self view] addSubview:table_];
8710 NSArray *items = [NSArray arrayWithObjects:
8712 UCLocalize("HACKER"),
8713 UCLocalize("DEVELOPER"),
8715 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8716 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8717 [container_ addSubview:segment_];
8720 - (void) viewDidLoad {
8721 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8724 if ([Role_ isEqualToString:@"User"]) index = 0;
8725 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8726 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8728 [segment_ setSelectedSegmentIndex:index];
8729 [self showDoneButton];
8732 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8733 [self resizeSegmentedControl];
8736 - (void) releaseSubviews {
8743 [container_ release];
8747 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8748 if ((self = [super init]) != nil) {
8749 database_ = database;
8750 roledelegate_ = delegate;
8754 - (void) resizeSegmentedControl {
8755 CGFloat width = [[self view] frame].size.width;
8756 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8759 - (void) viewWillAppear:(BOOL)animated {
8760 [super viewWillAppear:animated];
8762 [self resizeSegmentedControl];
8765 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8766 [self resizeSegmentedControl];
8769 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8770 [self resizeSegmentedControl];
8774 NSString *role(nil);
8776 switch ([segment_ selectedSegmentIndex]) {
8777 case 0: role = @"User"; break;
8778 case 1: role = @"Hacker"; break;
8779 case 2: role = @"Developer"; break;
8784 if (![role isEqualToString:Role_]) {
8785 bool rolling(Role_ == nil);
8788 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8792 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8796 [roledelegate_ loadData];
8798 [roledelegate_ updateData];
8802 - (void) segmentChanged:(UISegmentedControl *)control {
8803 [self showDoneButton];
8806 - (void) saveAndClose {
8809 [[self navigationItem] setRightBarButtonItem:nil];
8810 [[self navigationController] dismissModalViewControllerAnimated:YES];
8813 - (void) doneButtonClicked {
8814 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8815 [spinner startAnimating];
8816 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8817 [[self navigationItem] setRightBarButtonItem:spinItem];
8819 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8822 - (void) showDoneButton {
8823 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8824 initWithTitle:UCLocalize("DONE")
8825 style:UIBarButtonItemStyleDone
8827 action:@selector(doneButtonClicked)
8828 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8831 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8832 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8836 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8840 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8841 return nil; // This method is required by the protocol.
8844 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8846 return UCLocalize("ROLE_EX");
8848 return [NSString stringWithFormat:
8849 @"%@: %@\n%@: %@\n%@: %@",
8850 UCLocalize("USER"), UCLocalize("USER_EX"),
8851 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8852 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8857 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8858 return section == 3 ? 44.0f : 0;
8861 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8862 return section == 3 ? container_ : nil;
8865 - (void) reloadData {
8867 [table_ reloadData];
8872 /* Stash Controller {{{ */
8873 @interface StashController : CYViewController {
8874 UIActivityIndicatorView *spinner_;
8881 @implementation StashController
8884 [self releaseSubviews];
8890 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8891 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8893 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8894 CGRect spinrect = [spinner_ frame];
8895 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8896 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8897 [spinner_ setFrame:spinrect];
8898 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8899 [[self view] addSubview:spinner_];
8900 [spinner_ startAnimating];
8903 captrect.size.width = [[self view] frame].size.width;
8904 captrect.size.height = 40.0f;
8905 captrect.origin.x = 0;
8906 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8907 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8908 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8909 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8910 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8911 [caption_ setTextColor:[UIColor whiteColor]];
8912 [caption_ setBackgroundColor:[UIColor clearColor]];
8913 [caption_ setShadowColor:[UIColor blackColor]];
8914 [caption_ setTextAlignment:UITextAlignmentCenter];
8915 [[self view] addSubview:caption_];
8918 statusrect.size.width = [[self view] frame].size.width;
8919 statusrect.size.height = 30.0f;
8920 statusrect.origin.x = 0;
8921 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8922 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8923 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8924 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8925 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8926 [status_ setTextColor:[UIColor whiteColor]];
8927 [status_ setBackgroundColor:[UIColor clearColor]];
8928 [status_ setShadowColor:[UIColor blackColor]];
8929 [status_ setTextAlignment:UITextAlignmentCenter];
8930 [[self view] addSubview:status_];
8933 - (void) releaseSubviews {
8947 @interface Cydia : UIApplication <
8948 ConfirmationControllerDelegate,
8951 UINavigationControllerDelegate,
8952 UITabBarControllerDelegate
8954 // XXX: evaluate all fields for _transient
8957 CYTabBarController *tabbar_;
8958 CYEmulatedLoadingController *emulated_;
8960 NSMutableArray *essential_;
8961 NSMutableArray *broken_;
8963 Database *database_;
8970 StashController *stash_;
8979 @implementation Cydia
8981 - (void) beginUpdate {
8982 [tabbar_ beginUpdate];
8986 return [tabbar_ updating];
8990 if ([broken_ count] != 0) {
8991 int count = [broken_ count];
8993 UIAlertView *alert = [[[UIAlertView alloc]
8994 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8995 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8997 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8999 UCLocalize("TEMPORARY_IGNORE"),
9003 [alert setContext:@"fixhalf"];
9004 [alert setNumberOfRows:2];
9006 } else if (!Ignored_ && [essential_ count] != 0) {
9007 int count = [essential_ count];
9009 UIAlertView *alert = [[[UIAlertView alloc]
9010 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9011 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9013 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9015 UCLocalize("UPGRADE_ESSENTIAL"),
9016 UCLocalize("COMPLETE_UPGRADE"),
9020 [alert setContext:@"upgrade"];
9025 - (void) _saveConfig {
9031 NSString *error(nil);
9033 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9035 NSError *error(nil);
9036 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9037 NSLog(@"failure to save metadata data: %@", error);
9042 NSLog(@"failure to serialize metadata: %@", error);
9047 // Navigation controller for the queuing badge.
9048 - (CYNavigationController *) queueNavigationController {
9049 NSArray *controllers = [tabbar_ viewControllers];
9050 return [controllers objectAtIndex:3];
9053 - (void) _updateData {
9056 [tabbar_ reloadData];
9058 CYNavigationController *navigation = [self queueNavigationController];
9060 id queuedelegate = nil;
9061 if ([[navigation viewControllers] count] > 0)
9062 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9064 [queuedelegate queueStatusDidChange];
9065 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9068 - (void) _refreshIfPossible:(NSDate *)update {
9069 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9071 bool recently = false;
9072 if (update != nil) {
9073 NSTimeInterval interval([update timeIntervalSinceNow]);
9074 if (interval <= 0 && interval > -(15*60))
9078 // Don't automatic refresh if:
9079 // - We already refreshed recently.
9080 // - We already auto-refreshed this launch.
9081 // - Auto-refresh is disabled.
9082 if (recently || loaded_ || ManualRefresh) {
9083 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9085 // If we are cancelling, we need to make sure it knows it's already loaded.
9089 // We are going to load, so remember that.
9093 SCNetworkReachabilityFlags flags; {
9094 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9095 SCNetworkReachabilityGetFlags(reachability, &flags);
9096 CFRelease(reachability);
9099 // XXX: this elaborate mess is what Apple is using to determine this? :(
9100 // XXX: do we care if the user has to intervene? maybe that's ok?
9102 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9103 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9104 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9105 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9106 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9107 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9111 // If we can reach the server, auto-refresh!
9113 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9118 - (void) refreshIfPossible {
9119 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9122 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
9123 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9124 [hud setText:UCLocalize("RELOADING_DATA")];
9126 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9129 [self removeProgressHUD:hud];
9133 [essential_ removeAllObjects];
9134 [broken_ removeAllObjects];
9136 NSArray *packages([database_ packages]);
9137 for (Package *package in packages) {
9139 [broken_ addObject:package];
9140 if ([package upgradableAndEssential:NO]) {
9141 if ([package essential])
9142 [essential_ addObject:package];
9147 NSLog(@"changes:#%u", changes);
9149 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9152 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9153 [changesItem setBadgeValue:badge];
9154 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9155 [self setApplicationIconBadgeNumber:changes];
9158 [changesItem setBadgeValue:nil];
9159 [changesItem setAnimatedBadge:NO];
9160 [self setApplicationIconBadgeNumber:0];
9165 [self refreshIfPossible];
9168 - (void) updateData {
9177 @synchronized (self) {
9178 [self _reloadDataWithInvocation:nil];
9182 - (void) disemulate {
9183 if (emulated_ == nil)
9186 [window_ addSubview:[tabbar_ view]];
9187 [[emulated_ view] removeFromSuperview];
9188 [emulated_ release];
9190 [window_ setUserInteractionEnabled:YES];
9193 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9194 UINavigationController *navigation([[[CYNavigationController alloc] initWithRootViewController:controller] autorelease]);
9196 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9198 UIViewController *parent;
9199 if (emulated_ == nil)
9208 [parent presentModalViewController:navigation animated:YES];
9211 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9212 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9214 if (navigation != nil)
9215 [navigation pushViewController:progress animated:YES];
9217 [self presentModalViewController:progress force:YES];
9219 [progress invoke:invocation withTitle:title];
9223 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9224 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9227 - (void) repairWithInvocation:(NSInvocation *)invocation {
9229 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9233 - (void) repairWithSelector:(SEL)selector {
9234 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9240 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
9241 _assert(file != NULL);
9243 for (NSString *key in [Sources_ allKeys]) {
9244 NSDictionary *source([Sources_ objectForKey:key]);
9246 fprintf(file, "%s %s %s\n",
9247 [[source objectForKey:@"Type"] UTF8String],
9248 [[source objectForKey:@"URI"] UTF8String],
9249 [[source objectForKey:@"Distribution"] UTF8String]
9255 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9260 - (void) addTrivialSource:(NSString *)href {
9261 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
9264 @"./", @"Distribution",
9265 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
9270 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9271 @synchronized (self) {
9272 [self _reloadDataWithInvocation:invocation];
9276 - (void) reloadData {
9277 [self reloadDataWithInvocation:nil];
9281 pkgProblemResolver *resolver = [database_ resolver];
9283 resolver->InstallProtect();
9284 if (!resolver->Resolve(true))
9289 // XXX: this is a really crappy way of doing this.
9290 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9291 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9292 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9293 if ([tabbar_ updating])
9294 [tabbar_ cancelUpdate];
9296 if (![database_ prepare])
9299 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9300 [page setDelegate:self];
9301 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
9302 [confirm_ setDelegate:self];
9305 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9306 [tabbar_ presentModalViewController:confirm_ animated:YES];
9312 @synchronized (self) {
9317 - (void) clearPackage:(Package *)package {
9318 @synchronized (self) {
9325 - (void) installPackages:(NSArray *)packages {
9326 @synchronized (self) {
9327 for (Package *package in packages)
9334 - (void) installPackage:(Package *)package {
9335 @synchronized (self) {
9342 - (void) removePackage:(Package *)package {
9343 @synchronized (self) {
9350 - (void) distUpgrade {
9351 @synchronized (self) {
9352 if (![database_ upgrade])
9358 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9361 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
9366 - (void) showSettings {
9367 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9368 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9370 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9371 [tabbar_ presentModalViewController:nav animated:YES];
9374 - (void) retainNetworkActivityIndicator {
9375 if (activity_++ == 0)
9376 [self setNetworkActivityIndicatorVisible:YES];
9379 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9383 - (void) releaseNetworkActivityIndicator {
9384 if (--activity_ == 0)
9385 [self setNetworkActivityIndicatorVisible:NO];
9388 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9393 - (void) cancelAndClear:(bool)clear {
9394 @synchronized (self) {
9406 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9407 NSString *context([alert context]);
9409 if ([context isEqualToString:@"conffile"]) {
9410 FILE *input = [database_ input];
9411 if (button == [alert cancelButtonIndex])
9412 fprintf(input, "N\n");
9413 else if (button == [alert firstOtherButtonIndex])
9414 fprintf(input, "Y\n");
9417 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9418 } else if ([context isEqualToString:@"fixhalf"]) {
9419 if (button == [alert cancelButtonIndex]) {
9420 @synchronized (self) {
9421 for (Package *broken in broken_) {
9424 NSString *id = [broken id];
9425 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9426 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9427 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9428 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9434 } else if (button == [alert firstOtherButtonIndex]) {
9435 [broken_ removeAllObjects];
9439 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9440 } else if ([context isEqualToString:@"upgrade"]) {
9441 if (button == [alert firstOtherButtonIndex]) {
9442 @synchronized (self) {
9443 for (Package *essential in essential_)
9444 [essential install];
9449 } else if (button == [alert firstOtherButtonIndex] + 1) {
9451 } else if (button == [alert cancelButtonIndex]) {
9455 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9459 - (void) system:(NSString *)command { _pooled
9461 system([command UTF8String]);
9465 - (void) applicationWillSuspend {
9467 [super applicationWillSuspend];
9470 - (BOOL) isSafeToSuspend {
9473 NSLog(@"isSafeToSuspend: locked_ != 0");
9478 // Use external process status API internally.
9479 // This is probably a really bad idea.
9480 // XXX: what is the point of this? does this solve anything at all?
9481 uint64_t status = 0;
9483 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9484 notify_get_state(notify_token, &status);
9485 notify_cancel(notify_token);
9490 NSLog(@"isSafeToSuspend: status != 0");
9496 NSLog(@"isSafeToSuspend: -> true");
9501 - (void) applicationSuspend:(__GSEvent *)event {
9502 if ([self isSafeToSuspend])
9503 [super applicationSuspend:event];
9506 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9507 if ([self isSafeToSuspend])
9508 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9511 - (void) _setSuspended:(BOOL)value {
9512 if ([self isSafeToSuspend])
9513 [super _setSuspended:value];
9516 - (UIProgressHUD *) addProgressHUD {
9517 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9518 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9520 [window_ setUserInteractionEnabled:NO];
9523 UIViewController *target = tabbar_;
9524 while ([target modalViewController] != nil) target = [target modalViewController];
9525 [[target view] addSubview:hud];
9531 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9533 [hud removeFromSuperview];
9534 [window_ setUserInteractionEnabled:YES];
9538 - (CYViewController *) pageForPackage:(NSString *)name {
9539 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9542 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9543 NSString *scheme([[url scheme] lowercaseString]);
9544 if ([[url absoluteString] length] <= [scheme length] + 3)
9546 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9547 NSArray *components([path pathComponents]);
9549 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9550 return [self pageForPackage:[components objectAtIndex:1]];
9552 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9555 NSString *base([components objectAtIndex:0]);
9557 CYViewController *controller = nil;
9559 if ([base isEqualToString:@"url"]) {
9560 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9561 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9562 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9563 } else if (!external && [components count] == 1) {
9564 if ([base isEqualToString:@"manage"]) {
9565 controller = [[[ManageController alloc] init] autorelease];
9568 if ([base isEqualToString:@"sources"]) {
9569 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9572 if ([base isEqualToString:@"home"]) {
9573 controller = [[[HomeController alloc] init] autorelease];
9576 if ([base isEqualToString:@"sections"]) {
9577 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9580 if ([base isEqualToString:@"search"]) {
9581 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9584 if ([base isEqualToString:@"changes"]) {
9585 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9588 if ([base isEqualToString:@"installed"]) {
9589 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9591 } else if ([components count] == 2) {
9592 NSString *argument = [components objectAtIndex:1];
9594 if ([base isEqualToString:@"package"]) {
9595 controller = [self pageForPackage:argument];
9598 if (!external && [base isEqualToString:@"search"]) {
9599 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9600 [(SearchController *)controller setSearchTerm:argument];
9603 if (!external && [base isEqualToString:@"sections"]) {
9604 if ([argument isEqualToString:@"all"])
9606 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9609 if (!external && [base isEqualToString:@"sources"]) {
9610 if ([argument isEqualToString:@"add"]) {
9611 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9612 [(SourcesController *)controller showAddSourcePrompt];
9614 Source *source = [database_ sourceWithKey:argument];
9615 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9619 if (!external && [base isEqualToString:@"launch"]) {
9620 [self launchApplicationWithIdentifier:argument suspended:NO];
9623 } else if (!external && [components count] == 3) {
9624 NSString *arg1 = [components objectAtIndex:1];
9625 NSString *arg2 = [components objectAtIndex:2];
9627 if ([base isEqualToString:@"package"]) {
9628 if ([arg2 isEqualToString:@"settings"]) {
9629 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9630 } else if ([arg2 isEqualToString:@"files"]) {
9631 if (Package *package = [database_ packageWithName:arg1]) {
9632 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9633 [(FileTable *)controller setPackage:package];
9639 [controller setDelegate:self];
9643 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9644 CYViewController *page([self pageForURL:url forExternal:external]);
9647 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9648 [nav setViewControllers:[NSArray arrayWithObject:page]];
9649 [tabbar_ setUnselectedViewController:nav];
9655 - (void) applicationOpenURL:(NSURL *)url {
9656 [super applicationOpenURL:url];
9658 if (!loaded_) starturl_ = [url retain];
9659 else [self openCydiaURL:url forExternal:YES];
9662 - (void) applicationWillResignActive:(UIApplication *)application {
9663 // Stop refreshing if you get a phone call or lock the device.
9664 if ([tabbar_ updating])
9665 [tabbar_ cancelUpdate];
9667 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9668 [super applicationWillResignActive:application];
9671 - (void) applicationWillTerminate:(UIApplication *)application {
9673 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9674 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9675 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9680 - (void) setConfigurationData:(NSString *)data {
9681 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9683 if (!conffile_r(data)) {
9684 lprintf("E:invalid conffile\n");
9688 NSString *ofile = conffile_r[1];
9689 //NSString *nfile = conffile_r[2];
9691 UIAlertView *alert = [[[UIAlertView alloc]
9692 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9693 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9695 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9697 UCLocalize("ACCEPT_NEW_COPY"),
9698 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9702 [alert setContext:@"conffile"];
9703 [alert setNumberOfRows:2];
9707 - (void) addStashController {
9709 stash_ = [[StashController alloc] init];
9710 [window_ addSubview:[stash_ view]];
9713 - (void) removeStashController {
9714 [[stash_ view] removeFromSuperview];
9720 [self setIdleTimerDisabled:YES];
9722 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9723 UpdateExternalStatus(1);
9724 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9725 UpdateExternalStatus(0);
9727 [self removeStashController];
9729 if (ExecFork() == 0) {
9730 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9731 perror("launchctl stop");
9735 - (void) setupViewControllers {
9736 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9738 NSMutableArray *items([NSMutableArray arrayWithObjects:
9739 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9740 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9741 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9742 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9746 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9747 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9749 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9752 NSMutableArray *controllers([NSMutableArray array]);
9753 for (UITabBarItem *item in items) {
9754 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9755 [controller setTabBarItem:item];
9756 [controllers addObject:controller];
9758 [tabbar_ setViewControllers:controllers];
9760 [tabbar_ setUpdateDelegate:self];
9763 - (void) applicationDidFinishLaunching:(id)unused {
9765 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9766 [self setApplicationSupportsShakeToEdit:NO];
9768 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9770 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9771 initWithMemoryCapacity:524288
9772 diskCapacity:10485760
9773 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9776 [CYBrowserController _initialize];
9778 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9780 Font12_ = [[UIFont systemFontOfSize:12] retain];
9781 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9782 Font14_ = [[UIFont systemFontOfSize:14] retain];
9783 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9784 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9786 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9787 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9789 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9790 [window_ orderFront:self];
9791 [window_ makeKey:self];
9792 [window_ setHidden:NO];
9795 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9796 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9797 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9798 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9799 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9800 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9801 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9802 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9803 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9806 [self addStashController];
9807 // XXX: this would be much cleaner as a yieldToSelector:
9808 // that way the removeStashController could happen right here inline
9809 // we also could no longer require the useless stash_ field anymore
9810 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9814 database_ = [Database sharedInstance];
9815 [database_ setDelegate:self];
9817 [window_ setUserInteractionEnabled:NO];
9818 [self setupViewControllers];
9820 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9821 [window_ addSubview:[emulated_ view]];
9823 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9827 - (NSArray *) defaultStartPages {
9828 NSMutableArray *standard = [NSMutableArray array];
9829 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9830 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9831 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9833 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9835 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9836 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9838 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9845 [window_ setUserInteractionEnabled:YES];
9846 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9849 if ([emulated_ modalViewController] != nil)
9850 [emulated_ dismissModalViewControllerAnimated:YES];
9851 [window_ setUserInteractionEnabled:NO];
9859 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9860 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9861 int standardIndex = 0;
9862 NSArray *standard = [self defaultStartPages];
9869 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9870 if (valid && closed != nil) {
9871 NSTimeInterval interval([closed timeIntervalSinceNow]);
9872 // XXX: Is 15 minutes the optimal time here?
9873 if (interval > 0 && interval <= -(15*60))
9877 if (valid && [saved count] != [standard count])
9881 for (unsigned int i = 0; i < [standard count]; i++) {
9882 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9883 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9884 // but it's good enough for now.
9885 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9892 NSArray *items = nil;
9894 [tabbar_ setSelectedIndex:savedIndex];
9897 [tabbar_ setSelectedIndex:standardIndex];
9901 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9902 NSArray *stack = [items objectAtIndex:tab];
9903 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9904 NSMutableArray *current = [NSMutableArray array];
9906 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9907 NSString *addr = [stack objectAtIndex:nav];
9908 NSURL *url = [NSURL URLWithString:addr];
9909 CYViewController *page = [self pageForURL:url forExternal:NO];
9911 [current addObject:page];
9914 [navigation setViewControllers:current];
9917 // (Try to) show the startup URL.
9918 if (starturl_ != nil) {
9919 [self openCydiaURL:starturl_ forExternal:NO];
9920 [starturl_ release];
9925 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9926 if (item != nil && IsWildcat_) {
9927 [sheet showFromBarButtonItem:item animated:YES];
9929 [sheet showInView:window_];
9933 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9934 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9935 [progress setTitle:task];
9936 [progress addProgressEvent:event];
9939 - (void) addProgressEventForTask:(NSArray *)data {
9940 CydiaProgressEvent *event([data objectAtIndex:0]);
9941 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9942 [self addProgressEvent:event forTask:task];
9945 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9946 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9952 id Alloc_(id self, SEL selector) {
9953 id object = alloc_(self, selector);
9954 lprintf("[%s]A-%p\n", self->isa->name, object);
9959 id Dealloc_(id self, SEL selector) {
9960 id object = dealloc_(self, selector);
9961 lprintf("[%s]D-%p\n", self->isa->name, object);
9965 Class $WebDefaultUIKitDelegate;
9967 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9968 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9969 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9970 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9973 static NSNumber *shouldPlayKeyboardSounds;
9977 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9979 case 1104: // Keyboard Button Clicked
9980 case 1105: // Keyboard Delete Repeated
9981 if (shouldPlayKeyboardSounds == nil) {
9982 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9983 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9986 if (![shouldPlayKeyboardSounds boolValue])
9990 _UIHardware$_playSystemSound$(self, _cmd, sound);
9994 Class $UIApplication;
9996 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9997 static BOOL initialized = NO;
9998 static BOOL started = NO;
10000 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
10001 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
10003 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
10004 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
10005 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
10006 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
10008 if (initialized && !enabled) {
10010 [bundle performSelector:@selector(_accessibilityStopServer)];
10011 } else if (enabled) {
10015 [bundle performSelector:@selector(_accessibilityStartServer)];
10021 Class $NSURLConnection;
10023 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10024 NSMutableURLRequest *copy([request mutableCopy]);
10026 NSURL *url([copy URL]);
10027 NSString *host([url host]);
10029 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10030 if ([BridgedHosts_ containsObject:host])
10031 [copy setHTTPShouldUsePipelining:YES];
10033 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10037 int main(int argc, char *argv[]) { _pooled
10040 UpdateExternalStatus(0);
10042 if (Class $UIDevice = objc_getClass("UIDevice")) {
10043 UIDevice *device([$UIDevice currentDevice]);
10044 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10046 IsWildcat_ = false;
10048 UIScreen *screen([UIScreen mainScreen]);
10049 if ([screen respondsToSelector:@selector(scale)])
10050 ScreenScale_ = [screen scale];
10054 UIDevice *device([UIDevice currentDevice]);
10055 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10056 Idiom_ = @"iphone";
10058 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10059 if (idiom == UIUserInterfaceIdiomPhone)
10060 Idiom_ = @"iphone";
10061 else if (idiom == UIUserInterfaceIdiomPad)
10064 NSLog(@"unknown UIUserInterfaceIdiom!");
10067 BridgedHosts_ = [NSMutableSet setWithCapacity:2];
10069 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
10071 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10073 /* Library Hacks {{{ */
10074 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10076 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10077 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10078 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10079 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10080 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10083 $NSURLConnection = objc_getClass("NSURLConnection");
10084 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10085 if (NSURLConnection$init$ != NULL) {
10086 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10087 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10090 $UIHardware = objc_getClass("UIHardware");
10091 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
10092 if (UIHardware$_playSystemSound$ != NULL) {
10093 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
10094 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
10097 $UIApplication = objc_getClass("UIApplication");
10098 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
10099 if (UIApplication$_updateApplicationAccessibility != NULL) {
10100 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
10101 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
10104 /* Set Locale {{{ */
10105 Locale_ = CFLocaleCopyCurrent();
10106 Languages_ = [NSLocale preferredLanguages];
10108 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10109 //NSLog(@"%@", [Languages_ description]);
10112 if (Locale_ != NULL)
10113 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10114 else if (Languages_ == nil || [Languages_ count] == 0)
10115 // XXX: consider just setting to C and then falling through?
10118 lang = [[Languages_ objectAtIndex:0] UTF8String];
10119 setenv("LANG", lang, true);
10120 std::setlocale(LC_ALL, lang);
10123 NSLog(@"Setting Language: %s", lang);
10126 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10128 /* Parse Arguments {{{ */
10129 bool substrate(false);
10135 for (int argi(1); argi != argc; ++argi)
10136 if (strcmp(argv[argi], "--") == 0) {
10138 argv[argi] = argv[0];
10144 for (int argi(1); argi != arge; ++argi)
10145 if (strcmp(args[argi], "--substrate") == 0)
10148 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10152 App_ = [[NSBundle mainBundle] bundlePath];
10158 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10159 alloc_ = alloc->method_imp;
10160 alloc->method_imp = (IMP) &Alloc_;*/
10162 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10163 dealloc_ = dealloc->method_imp;
10164 dealloc->method_imp = (IMP) &Dealloc_;*/
10166 /* System Information {{{ */
10170 size = sizeof(maxproc);
10171 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10172 perror("sysctlbyname(\"kern.maxproc\", ?)");
10173 else if (maxproc < 64) {
10175 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10176 perror("sysctlbyname(\"kern.maxproc\", #)");
10179 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10180 char *osversion = new char[size];
10181 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10182 perror("sysctlbyname(\"kern.osversion\", ?)");
10184 System_ = [NSString stringWithUTF8String:osversion];
10186 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10187 char *machine = new char[size];
10188 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10189 perror("sysctlbyname(\"hw.machine\", ?)");
10191 Machine_ = machine;
10193 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
10194 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
10195 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
10196 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
10200 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
10201 NSData *data((NSData *) ecid);
10202 size_t length([data length]);
10203 uint8_t bytes[length];
10204 [data getBytes:bytes];
10205 char string[length * 2 + 1];
10206 for (size_t i(0); i != length; ++i)
10207 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
10208 ChipID_ = [NSString stringWithUTF8String:string];
10212 IOObjectRelease(service);
10216 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
10218 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10219 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10220 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10222 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10223 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10224 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10226 if (mcc != NULL && mnc != NULL)
10227 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10234 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10235 Build_ = [system objectForKey:@"ProductBuildVersion"];
10236 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10237 Product_ = [info objectForKey:@"SafariProductVersion"];
10238 Safari_ = [info objectForKey:@"CFBundleVersion"];
10241 /* Load Database {{{ */
10243 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10245 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10247 if (Metadata_ == NULL)
10248 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10250 Settings_ = [Metadata_ objectForKey:@"Settings"];
10252 Packages_ = [Metadata_ objectForKey:@"Packages"];
10253 Sections_ = [Metadata_ objectForKey:@"Sections"];
10254 Sources_ = [Metadata_ objectForKey:@"Sources"];
10256 Token_ = [Metadata_ objectForKey:@"Token"];
10259 if (Settings_ != nil)
10260 Role_ = [Settings_ objectForKey:@"Role"];
10262 if (Sections_ == nil) {
10263 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10264 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10267 if (Sources_ == nil) {
10268 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10269 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10274 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10277 if (Packages_ != nil) {
10279 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10283 [Metadata_ removeObjectForKey:@"Packages"];
10289 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10291 #define MobileSubstrate_(name) \
10292 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10293 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10294 if (handle == NULL) \
10295 NSLog(@"%s", dlerror()); \
10298 MobileSubstrate_(Activator)
10299 MobileSubstrate_(libstatusbar)
10300 MobileSubstrate_(SimulatedKeyEvents)
10301 MobileSubstrate_(WinterBoard)
10303 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10304 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10306 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10308 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10309 unlink("/tmp/.cydia.fw");
10311 } else if (access("/User", F_OK) != 0 || version < 4) {
10314 system("/usr/libexec/cydia/firmware.sh");
10318 _assert([[NSFileManager defaultManager]
10319 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10320 withIntermediateDirectories:YES
10325 if (access("/tmp/cydia.chk", F_OK) == 0) {
10326 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10327 _assert(errno == ENOENT);
10328 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10329 _assert(errno == ENOENT);
10332 /* APT Initialization {{{ */
10333 _assert(pkgInitConfig(*_config));
10334 _assert(pkgInitSystem(*_config, _system));
10337 _config->Set("APT::Acquire::Translation", lang);
10339 // XXX: this timeout might be important :(
10340 //_config->Set("Acquire::http::Timeout", 15);
10342 _config->Set("Acquire::http::MaxParallel", 3);
10344 /* Color Choices {{{ */
10345 space_ = CGColorSpaceCreateDeviceRGB();
10347 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10348 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10349 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10350 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10351 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10352 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10353 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10354 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10355 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10357 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10358 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10360 /* UIKit Configuration {{{ */
10361 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10362 if ($GSFontSetUseLegacyFontMetrics != NULL)
10363 $GSFontSetUseLegacyFontMetrics(YES);
10365 // XXX: I have a feeling this was important
10366 //UIKeyboardDisableAutomaticAppearance();
10369 Colon_ = UCLocalize("COLON_DELIMITED");
10370 Elision_ = UCLocalize("ELISION");
10371 Error_ = UCLocalize("ERROR");
10372 Warning_ = UCLocalize("WARNING");
10375 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10377 CGColorSpaceRelease(space_);
10378 CFRelease(Locale_);