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;
1197 - (void) addBridgedHost:(NSString *)host;
1201 /* ProgressEvent Interface/Delegate {{{ */
1202 @interface CydiaProgressEvent : NSObject {
1203 _H<NSString> message_;
1207 _H<NSString> package_;
1209 _H<NSString> version_;
1212 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type;
1213 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package;
1214 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item;
1216 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type;
1218 - (NSString *) message;
1219 - (NSString *) type;
1222 - (NSString *) package;
1224 - (NSString *) version;
1226 - (void) setItem:(NSArray *)item;
1227 - (void) setPackage:(NSString *)package;
1228 - (void) setURL:(NSString *)url;
1229 - (void) setVersion:(NSString *)version;
1231 - (NSString *) compound:(NSString *)value;
1232 - (NSString *) compoundMessage;
1233 - (NSString *) compoundTitle;
1237 @protocol ProgressDelegate
1238 - (void) addProgressEvent:(CydiaProgressEvent *)event;
1239 - (void) setProgressPercent:(NSNumber *)percent;
1240 - (void) setProgressStatus:(NSDictionary *)status;
1241 - (void) setProgressCancellable:(NSNumber *)cancellable;
1242 - (bool) isProgressCancelled;
1243 - (void) setTitle:(NSString *)title;
1246 /* Status Delegation {{{ */
1248 public pkgAcquireStatus
1251 _transient NSObject<ProgressDelegate> *delegate_;
1261 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1262 delegate_ = delegate;
1265 NSObject<ProgressDelegate> *getDelegate() const {
1269 virtual bool MediaChange(std::string media, std::string drive) {
1273 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1276 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1277 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1278 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
1279 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1282 virtual void Done(pkgAcquire::ItemDesc &item) {
1285 virtual void Fail(pkgAcquire::ItemDesc &item) {
1287 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1288 item.Owner->Status == pkgAcquire::Item::StatDone
1292 std::string &error(item.Owner->ErrorText);
1296 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
1297 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1300 virtual bool Pulse(pkgAcquire *Owner) {
1301 bool value = pkgAcquireStatus::Pulse(Owner);
1304 double(CurrentBytes + CurrentItems) /
1305 double(TotalBytes + TotalItems)
1308 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1309 [NSNumber numberWithDouble:percent], @"Percent",
1311 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1312 [NSNumber numberWithDouble:TotalBytes], @"Total",
1313 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1314 nil] waitUntilDone:YES];
1316 if (value && ![delegate_ isProgressCancelled])
1324 _finline bool WasCancelled() const {
1328 virtual void Start() {
1329 pkgAcquireStatus::Start();
1330 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1333 virtual void Stop() {
1334 pkgAcquireStatus::Stop();
1335 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1336 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1340 /* Database Interface {{{ */
1341 typedef std::map< unsigned long, _H<Source> > SourceMap;
1343 @interface Database : NSObject {
1349 pkgCacheFile cache_;
1350 pkgDepCache::Policy *policy_;
1351 pkgRecords *records_;
1352 pkgProblemResolver *resolver_;
1353 pkgAcquire *fetcher_;
1355 SPtr<pkgPackageManager> manager_;
1356 pkgSourceList *list_;
1358 SourceMap sourceMap_;
1359 NSMutableArray *sourceList_;
1361 CFMutableArrayRef packages_;
1363 _transient NSObject<DatabaseDelegate> *delegate_;
1364 _transient NSObject<ProgressDelegate> *progress_;
1372 std::map<const char *, _H<NSString> > sections_;
1375 + (Database *) sharedInstance;
1378 - (void) _readCydia:(NSNumber *)fd;
1379 - (void) _readStatus:(NSNumber *)fd;
1380 - (void) _readOutput:(NSNumber *)fd;
1384 - (Package *) packageWithName:(NSString *)name;
1386 - (pkgCacheFile &) cache;
1387 - (pkgDepCache::Policy *) policy;
1388 - (pkgRecords *) records;
1389 - (pkgProblemResolver *) resolver;
1390 - (pkgAcquire &) fetcher;
1391 - (pkgSourceList &) list;
1392 - (NSArray *) packages;
1393 - (NSArray *) sources;
1394 - (Source *) sourceWithKey:(NSString *)key;
1395 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1403 - (void) updateWithStatus:(Status &)status;
1405 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1407 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1408 - (NSObject<ProgressDelegate> *) progressDelegate;
1410 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1412 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1416 /* ProgressEvent Implementation {{{ */
1417 @implementation CydiaProgressEvent
1419 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1420 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1423 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1424 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1425 [event setPackage:package];
1429 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1430 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1432 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1433 NSArray *fields([description componentsSeparatedByString:@" "]);
1434 [event setItem:fields];
1436 if ([fields count] > 3) {
1437 [event setPackage:[fields objectAtIndex:2]];
1438 [event setVersion:[fields objectAtIndex:3]];
1441 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1446 + (NSArray *) _attributeKeys {
1447 return [NSArray arrayWithObjects:
1457 - (NSArray *) attributeKeys {
1458 return [[self class] _attributeKeys];
1461 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1462 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1465 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1466 if ((self = [super init]) != nil) {
1472 - (NSString *) message {
1476 - (NSString *) type {
1480 - (NSArray *) item {
1481 return (id) item_ ?: [NSNull null];
1484 - (void) setItem:(NSArray *)item {
1488 - (NSString *) package {
1489 return (id) package_ ?: [NSNull null];
1492 - (void) setPackage:(NSString *)package {
1496 - (NSString *) url {
1497 return (id) url_ ?: [NSNull null];
1500 - (void) setURL:(NSString *)url {
1504 - (void) setVersion:(NSString *)version {
1508 - (NSString *) version {
1509 return (id) version_ ?: [NSNull null];
1512 - (NSString *) compound:(NSString *)value {
1514 NSString *mode(nil); {
1515 NSString *type([self type]);
1516 if ([type isEqualToString:kCydiaProgressEventTypeError])
1517 mode = UCLocalize("ERROR");
1518 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1519 mode = UCLocalize("WARNING");
1523 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1529 - (NSString *) compoundMessage {
1530 return [self compound:[self message]];
1533 - (NSString *) compoundTitle {
1536 if (package_ == nil)
1538 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1539 title = [package name];
1543 return [self compound:title];
1549 // Cytore Definitions {{{
1550 struct PackageValue :
1553 Cytore::Offset<PackageValue> next_;
1555 uint32_t index_ : 23;
1556 uint32_t subscribed_ : 1;
1573 Cytore::Offset<PackageValue> packages_[1 << 16];
1576 static Cytore::File<MetaValue> MetaFile_;
1578 // Cytore Helper Functions {{{
1579 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1580 SplitHash nhash = { hashlittle(name, length) };
1582 PackageValue *metadata;
1584 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1585 offset: if (offset->IsNull()) {
1586 *offset = MetaFile_.New<PackageValue>(length + 1);
1587 metadata = &MetaFile_.Get(*offset);
1589 if (metadata == NULL) {
1593 metadata = new PackageValue();
1594 memset(metadata, 0, sizeof(*metadata));
1597 memcpy(metadata->name_, name, length + 1);
1598 metadata->nhash_ = nhash.u16[1];
1600 metadata = &MetaFile_.Get(*offset);
1602 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1603 offset = &metadata->next_;
1611 static void PackageImport(const void *key, const void *value, void *context) {
1612 bool &fail(*reinterpret_cast<bool *>(context));
1615 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1616 NSLog(@"failed to import package %@", key);
1620 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1621 NSDictionary *package((NSDictionary *) value);
1623 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1624 if ([subscribed boolValue] && !metadata->subscribed_)
1625 metadata->subscribed_ = true;
1627 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1628 time_t time([date timeIntervalSince1970]);
1629 if (metadata->first_ > time || metadata->first_ == 0)
1630 metadata->first_ = time;
1633 NSDate *date([package objectForKey:@"LastSeen"]);
1634 NSString *version([package objectForKey:@"LastVersion"]);
1636 if (date != nil && version != nil) {
1637 time_t time([date timeIntervalSince1970]);
1638 if (metadata->last_ < time || metadata->last_ == 0)
1639 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1640 size_t length(strlen(buffer));
1641 uint16_t vhash(hashlittle(buffer, length));
1643 size_t capped(std::min<size_t>(8, length));
1644 char *latest(buffer + length - capped);
1646 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1647 metadata->vhash_ = vhash;
1649 metadata->last_ = time;
1655 /* Source Class {{{ */
1656 @interface Source : NSObject {
1657 CYString depiction_;
1658 CYString description_;
1664 CYString distribution_;
1669 _H<NSString> authority_;
1671 CYString defaultIcon_;
1673 _H<NSDictionary> record_;
1677 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1679 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1681 - (NSString *) depictionForPackage:(NSString *)package;
1682 - (NSString *) supportForPackage:(NSString *)package;
1684 - (NSDictionary *) record;
1688 - (NSString *) distribution;
1689 - (NSString *) type;
1691 - (NSString *) host;
1693 - (NSString *) name;
1694 - (NSString *) description;
1695 - (NSString *) label;
1696 - (NSString *) origin;
1697 - (NSString *) version;
1699 - (NSString *) defaultIcon;
1703 @implementation Source
1707 distribution_.clear();
1710 description_.clear();
1716 defaultIcon_.clear();
1724 // XXX: this is a very inefficient way to call these deconstructors
1729 + (NSArray *) _attributeKeys {
1730 return [NSArray arrayWithObjects:
1745 - (NSArray *) attributeKeys {
1746 return [[self class] _attributeKeys];
1749 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1750 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1753 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1756 trusted_ = index->IsTrusted();
1758 uri_.set(pool, index->GetURI());
1759 distribution_.set(pool, index->GetDist());
1760 type_.set(pool, index->GetType());
1762 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1763 if (dindex != NULL) {
1765 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1768 pkgTagFile tags(&fd);
1770 pkgTagSection section;
1777 {"default-icon", &defaultIcon_},
1778 {"depiction", &depiction_},
1779 {"description", &description_},
1781 {"origin", &origin_},
1782 {"support", &support_},
1783 {"version", &version_},
1786 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1787 const char *start, *end;
1789 if (section.Find(names[i].name_, start, end)) {
1790 CYString &value(*names[i].value_);
1791 value.set(pool, start, end - start);
1797 record_ = [Sources_ objectForKey:[self key]];
1799 NSURL *url([NSURL URLWithString:uri_]);
1803 host_ = [host_ lowercaseString];
1806 // XXX: this is due to a bug in _H<>
1807 authority_ = (id) host_;
1809 authority_ = [url path];
1812 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1813 if ((self = [super init]) != nil) {
1814 [self setMetaIndex:index inPool:pool];
1818 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1819 NSDictionary *lhr = [self record];
1820 NSDictionary *rhr = [source record];
1823 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1825 NSString *lhs = [self name];
1826 NSString *rhs = [source name];
1828 if ([lhs length] != 0 && [rhs length] != 0) {
1829 unichar lhc = [lhs characterAtIndex:0];
1830 unichar rhc = [rhs characterAtIndex:0];
1832 if (isalpha(lhc) && !isalpha(rhc))
1833 return NSOrderedAscending;
1834 else if (!isalpha(lhc) && isalpha(rhc))
1835 return NSOrderedDescending;
1838 return [lhs compare:rhs options:LaxCompareOptions_];
1841 - (NSString *) depictionForPackage:(NSString *)package {
1842 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1845 - (NSString *) supportForPackage:(NSString *)package {
1846 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1849 - (NSDictionary *) record {
1857 - (NSString *) uri {
1861 - (NSString *) distribution {
1862 return distribution_;
1865 - (NSString *) type {
1869 - (NSString *) key {
1870 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1873 - (NSString *) host {
1877 - (NSString *) name {
1878 return origin_.empty() ? (id) authority_ : origin_;
1881 - (NSString *) description {
1882 return description_;
1885 - (NSString *) label {
1886 return label_.empty() ? (id) authority_ : label_;
1889 - (NSString *) origin {
1893 - (NSString *) version {
1897 - (NSString *) defaultIcon {
1898 return defaultIcon_;
1903 /* CydiaOperation Class {{{ */
1904 @interface CydiaOperation : NSObject {
1905 NSString *operator_;
1909 - (NSString *) operator;
1910 - (NSString *) value;
1914 @implementation CydiaOperation
1917 [operator_ release];
1922 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1923 if ((self = [super init]) != nil) {
1924 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1925 value_ = [[NSString alloc] initWithUTF8String:value];
1929 + (NSArray *) _attributeKeys {
1930 return [NSArray arrayWithObjects:
1936 - (NSArray *) attributeKeys {
1937 return [[self class] _attributeKeys];
1940 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1941 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1944 - (NSString *) operator {
1948 - (NSString *) value {
1954 /* CydiaClause Class {{{ */
1955 @interface CydiaClause : NSObject {
1957 CydiaOperation *version_;
1960 - (NSString *) package;
1961 - (CydiaOperation *) version;
1965 @implementation CydiaClause
1973 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1974 if ((self = [super init]) != nil) {
1975 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1977 if (const char *version = dep.TargetVer())
1978 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1980 version_ = [[NSNull null] retain];
1984 + (NSArray *) _attributeKeys {
1985 return [NSArray arrayWithObjects:
1991 - (NSArray *) attributeKeys {
1992 return [[self class] _attributeKeys];
1995 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1996 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1999 - (NSString *) package {
2003 - (CydiaOperation *) version {
2009 /* CydiaRelation Class {{{ */
2010 @interface CydiaRelation : NSObject {
2011 NSString *relationship_;
2012 NSMutableArray *clauses_;
2015 - (NSString *) relationship;
2016 - (NSArray *) clauses;
2020 @implementation CydiaRelation
2023 [relationship_ release];
2028 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2029 if ((self = [super init]) != nil) {
2030 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
2031 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
2033 pkgCache::DepIterator start;
2034 pkgCache::DepIterator end;
2035 dep.GlobOr(start, end); // ++dep
2038 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2040 // yes, seriously. (wtf?)
2048 + (NSArray *) _attributeKeys {
2049 return [NSArray arrayWithObjects:
2055 - (NSArray *) attributeKeys {
2056 return [[self class] _attributeKeys];
2059 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2060 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2063 - (NSString *) relationship {
2064 return relationship_;
2067 - (NSArray *) clauses {
2071 - (void) addClause:(CydiaClause *)clause {
2072 [clauses_ addObject:clause];
2077 /* Package Class {{{ */
2078 struct ParsedPackage {
2083 CYString depiction_;
2093 @interface Package : NSObject {
2096 uint32_t essential_ : 1;
2097 uint32_t obsolete_ : 1;
2098 uint32_t ignored_ : 1;
2102 _transient Database *database_;
2104 pkgCache::VerIterator version_;
2105 pkgCache::PkgIterator iterator_;
2106 pkgCache::VerFileIterator file_;
2112 CYString installed_;
2114 const char *section_;
2115 _transient NSString *section$_;
2119 PackageValue *metadata_;
2120 ParsedPackage *parsed_;
2122 NSMutableArray *tags_;
2125 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2126 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2128 - (pkgCache::PkgIterator) iterator;
2131 - (NSString *) section;
2132 - (NSString *) simpleSection;
2134 - (NSString *) longSection;
2135 - (NSString *) shortSection;
2139 - (Address *) maintainer;
2141 - (NSString *) longDescription;
2142 - (NSString *) shortDescription;
2145 - (PackageValue *) metadata;
2148 - (bool) subscribed;
2149 - (bool) setSubscribed:(bool)subscribed;
2153 - (NSString *) latest;
2154 - (NSString *) installed;
2155 - (BOOL) uninstalled;
2158 - (BOOL) upgradableAndEssential:(BOOL)essential;
2161 - (BOOL) unfiltered;
2165 - (BOOL) halfConfigured;
2166 - (BOOL) halfInstalled;
2168 - (NSString *) mode;
2171 - (NSString *) name;
2173 - (NSString *) homepage;
2174 - (NSString *) depiction;
2175 - (Address *) author;
2177 - (NSString *) support;
2179 - (NSArray *) files;
2180 - (NSArray *) warnings;
2181 - (NSArray *) applications;
2183 - (Source *) source;
2185 - (BOOL) matches:(NSString *)text;
2187 - (bool) hasSupportingRole;
2188 - (BOOL) hasTag:(NSString *)tag;
2189 - (NSString *) primaryPurpose;
2190 - (NSArray *) purposes;
2191 - (bool) isCommercial;
2193 - (void) setIndex:(size_t)index;
2195 - (CYString &) cyname;
2197 - (uint32_t) compareBySection:(NSArray *)sections;
2202 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2203 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2204 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2205 - (bool) isVisibleInSection:(NSString *)section;
2206 - (bool) isVisibleInSource:(Source *)source;
2210 uint32_t PackageChangesRadix(Package *self, void *) {
2215 uint32_t timestamp : 30;
2216 uint32_t ignored : 1;
2217 uint32_t upgradable : 1;
2221 bool upgradable([self upgradableAndEssential:YES]);
2222 value.bits.upgradable = upgradable ? 1 : 0;
2225 value.bits.timestamp = 0;
2226 value.bits.ignored = [self ignored] ? 0 : 1;
2227 value.bits.upgradable = 1;
2229 value.bits.timestamp = [self seen] >> 2;
2230 value.bits.ignored = 0;
2231 value.bits.upgradable = 0;
2234 return _not(uint32_t) - value.key;
2237 uint32_t PackagePrefixRadix(Package *self, void *context) {
2238 size_t offset(reinterpret_cast<size_t>(context));
2239 CYString &name([self cyname]);
2241 size_t size(name.size());
2244 char *text(name.data());
2247 if (!isdigit(text[0]))
2251 while (size != digits && isdigit(text[digits]))
2259 if (offset == 0 && zeros != 0) {
2260 memset(data, '0', zeros);
2261 memcpy(data + zeros, text, 4 - zeros);
2263 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2264 if (size <= offset - zeros)
2267 text += offset - zeros;
2268 size -= offset - zeros;
2271 memcpy(data, text, 4);
2273 memcpy(data, text, size);
2274 memset(data + size, 0, 4 - size);
2277 for (size_t i(0); i != 4; ++i)
2278 if (isalpha(data[i]))
2286 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2288 /* XXX: ntohl may be more honest */
2289 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2292 CYString &(*PackageName)(Package *self, SEL sel);
2294 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2295 _profile(PackageNameCompare)
2296 CYString &lhi(PackageName(lhs, @selector(cyname)));
2297 CYString &rhi(PackageName(rhs, @selector(cyname)));
2298 CFStringRef lhn(lhi), rhn(rhi);
2301 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2302 else if (rhn == NULL)
2303 return NSOrderedDescending;
2305 _profile(PackageNameCompare$NumbersLast)
2306 if (!lhi.empty() && !rhi.empty()) {
2307 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2308 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2309 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2310 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2311 return lha ? NSOrderedAscending : NSOrderedDescending;
2315 CFIndex length = CFStringGetLength(lhn);
2317 _profile(PackageNameCompare$Compare)
2318 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2323 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2324 return PackageNameCompare(*lhs, *rhs, context);
2327 struct PackageNameOrdering :
2328 std::binary_function<Package *, Package *, bool>
2330 _finline bool operator ()(Package *lhs, Package *rhs) const {
2331 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2335 @implementation Package
2337 - (NSString *) description {
2338 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2342 if (parsed_ != NULL)
2351 + (NSString *) webScriptNameForSelector:(SEL)selector {
2353 else if (selector == @selector(clear))
2355 else if (selector == @selector(getField:))
2357 else if (selector == @selector(hasTag:))
2359 else if (selector == @selector(install))
2361 else if (selector == @selector(remove))
2367 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2368 return [self webScriptNameForSelector:selector] == nil;
2371 + (NSArray *) _attributeKeys {
2372 return [NSArray arrayWithObjects:
2391 @"shortDescription",
2404 - (NSArray *) attributeKeys {
2405 return [[self class] _attributeKeys];
2408 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2409 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2412 - (NSArray *) relations {
2413 @synchronized (database_) {
2414 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2415 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2416 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2420 - (NSString *) getField:(NSString *)name {
2421 @synchronized (database_) {
2422 if ([database_ era] != era_ || file_.end())
2425 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2427 const char *start, *end;
2428 if (!parser.Find([name UTF8String], start, end))
2429 return (NSString *) [NSNull null];
2431 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2435 if (parsed_ != NULL)
2437 @synchronized (database_) {
2438 if ([database_ era] != era_ || file_.end())
2441 ParsedPackage *parsed(new ParsedPackage);
2444 _profile(Package$parse)
2445 pkgRecords::Parser *parser;
2447 _profile(Package$parse$Lookup)
2448 parser = &[database_ records]->Lookup(file_);
2453 _profile(Package$parse$Find)
2458 {"icon", &parsed->icon_},
2459 {"depiction", &parsed->depiction_},
2460 {"homepage", &parsed->homepage_},
2461 {"website", &website},
2462 {"bugs", &parsed->bugs_},
2463 {"support", &parsed->support_},
2464 {"sponsor", &parsed->sponsor_},
2465 {"author", &parsed->author_},
2468 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2469 const char *start, *end;
2471 if (parser->Find(names[i].name_, start, end)) {
2472 CYString &value(*names[i].value_);
2473 _profile(Package$parse$Value)
2474 value.set(pool_, start, end - start);
2480 _profile(Package$parse$Tagline)
2481 const char *start, *end;
2482 if (parser->ShortDesc(start, end)) {
2483 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2486 while (stop != start && stop[-1] == '\r')
2488 parsed->tagline_.set(pool_, start, stop - start);
2492 _profile(Package$parse$Retain)
2493 if (parsed->homepage_.empty())
2494 parsed->homepage_ = website;
2495 if (parsed->homepage_ == parsed->depiction_)
2496 parsed->homepage_.clear();
2501 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2502 if ((self = [super init]) != nil) {
2503 _profile(Package$initWithVersion)
2506 database_ = database;
2507 era_ = [database era];
2511 pkgCache::PkgIterator iterator(version.ParentPkg());
2512 iterator_ = iterator;
2514 _profile(Package$initWithVersion$Version)
2515 if (!version_.end())
2516 file_ = version_.FileList();
2518 pkgCache &cache([database_ cache]);
2519 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2523 _profile(Package$initWithVersion$Cache)
2524 name_.set(NULL, iterator.Display());
2526 latest_.set(NULL, StripVersion_(version_.VerStr()));
2528 pkgCache::VerIterator current(iterator.CurrentVer());
2530 installed_.set(NULL, StripVersion_(current.VerStr()));
2533 _profile(Package$initWithVersion$Tags)
2534 pkgCache::TagIterator tag(iterator.TagList());
2536 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2538 const char *name(tag.Name());
2539 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2541 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2542 if (strcmp(name + 6, "enduser") == 0)
2544 else if (strcmp(name + 6, "hacker") == 0)
2546 else if (strcmp(name + 6, "developer") == 0)
2548 else if (strcmp(name + 6, "cydia") == 0)
2554 if (strncmp(name, "cydia::", 7) == 0) {
2555 if (strcmp(name + 7, "essential") == 0)
2557 else if (strcmp(name + 7, "obsolete") == 0)
2562 } while (!tag.end());
2566 _profile(Package$initWithVersion$Metadata)
2567 const char *mixed(iterator.Name());
2568 size_t size(strlen(mixed));
2569 char lower[size + 1];
2571 for (size_t i(0); i != size; ++i)
2572 lower[i] = mixed[i] | 0x20;
2575 PackageValue *metadata(PackageFind(lower, size));
2576 metadata_ = metadata;
2578 id_.set(NULL, metadata->name_, size);
2580 const char *latest(version_.VerStr());
2581 size_t length(strlen(latest));
2583 uint16_t vhash(hashlittle(latest, length));
2585 size_t capped(std::min<size_t>(8, length));
2586 latest = latest + length - capped;
2588 if (metadata->first_ == 0)
2589 metadata->first_ = now_;
2591 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2592 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2593 metadata->vhash_ = vhash;
2594 metadata->last_ = now_;
2595 } else if (metadata->last_ == 0)
2596 metadata->last_ = metadata->first_;
2599 _profile(Package$initWithVersion$Section)
2600 section_ = iterator.Section();
2603 _profile(Package$initWithVersion$Flags)
2604 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2605 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2610 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2611 pkgCache::VerIterator version;
2613 _profile(Package$packageWithIterator$GetCandidateVer)
2614 version = [database policy]->GetCandidateVer(iterator);
2622 _profile(Package$packageWithIterator$Allocate)
2623 package = [Package allocWithZone:zone];
2626 _profile(Package$packageWithIterator$Initialize)
2628 initWithVersion:version
2635 _profile(Package$packageWithIterator$Autorelease)
2636 package = [package autorelease];
2642 - (pkgCache::PkgIterator) iterator {
2646 - (NSString *) section {
2647 if (section$_ == nil) {
2648 if (section_ == NULL)
2651 _profile(Package$section$mappedSectionForPointer)
2652 section$_ = [database_ mappedSectionForPointer:section_];
2657 - (NSString *) simpleSection {
2658 if (NSString *section = [self section])
2659 return Simplify(section);
2664 - (NSString *) longSection {
2665 return LocalizeSection([self section]);
2668 - (NSString *) shortSection {
2669 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2672 - (NSString *) uri {
2675 pkgIndexFile *index;
2676 pkgCache::PkgFileIterator file(file_.File());
2677 if (![database_ list].FindIndex(file, index))
2679 return [NSString stringWithUTF8String:iterator_->Path];
2680 //return [NSString stringWithUTF8String:file.Site()];
2681 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2685 - (Address *) maintainer {
2686 @synchronized (database_) {
2687 if ([database_ era] != era_ || file_.end())
2690 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2691 const std::string &maintainer(parser->Maintainer());
2692 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2696 @synchronized (database_) {
2697 if ([database_ era] != era_ || version_.end())
2700 return version_->InstalledSize;
2703 - (NSString *) longDescription {
2704 @synchronized (database_) {
2705 if ([database_ era] != era_ || file_.end())
2708 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2709 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2711 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2712 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2713 if ([lines count] < 2)
2716 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2717 for (size_t i(1), e([lines count]); i != e; ++i) {
2718 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2719 [trimmed addObject:trim];
2722 return [trimmed componentsJoinedByString:@"\n"];
2725 - (NSString *) shortDescription {
2726 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2730 _profile(Package$index)
2731 CFStringRef name((CFStringRef) [self name]);
2732 if (CFStringGetLength(name) == 0)
2734 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2735 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2737 return toupper(character);
2741 - (PackageValue *) metadata {
2746 PackageValue *metadata([self metadata]);
2747 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2750 - (bool) subscribed {
2751 return [self metadata]->subscribed_;
2754 - (bool) setSubscribed:(bool)subscribed {
2755 PackageValue *metadata([self metadata]);
2756 if (metadata->subscribed_ == subscribed)
2758 metadata->subscribed_ = subscribed;
2766 - (NSString *) latest {
2770 - (NSString *) installed {
2774 - (BOOL) uninstalled {
2775 return installed_.empty();
2779 return !version_.end();
2782 - (BOOL) upgradableAndEssential:(BOOL)essential {
2783 _profile(Package$upgradableAndEssential)
2784 pkgCache::VerIterator current(iterator_.CurrentVer());
2786 return essential && essential_;
2788 return !version_.end() && version_ != current;
2792 - (BOOL) essential {
2797 return [database_ cache][iterator_].InstBroken();
2800 - (BOOL) unfiltered {
2801 _profile(Package$unfiltered$obsolete)
2802 if (_unlikely(obsolete_))
2806 _profile(Package$unfiltered$hasSupportingRole)
2807 if (_unlikely(![self hasSupportingRole]))
2815 if (![self unfiltered])
2820 _profile(Package$visible$section)
2821 section = [self section];
2824 _profile(Package$visible$isSectionVisible)
2825 if (!isSectionVisible(section))
2833 unsigned char current(iterator_->CurrentState);
2834 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2837 - (BOOL) halfConfigured {
2838 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2841 - (BOOL) halfInstalled {
2842 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2846 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2847 return state.Mode != pkgDepCache::ModeKeep;
2850 - (NSString *) mode {
2851 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2853 switch (state.Mode) {
2854 case pkgDepCache::ModeDelete:
2855 if ((state.iFlags & pkgDepCache::Purge) != 0)
2859 case pkgDepCache::ModeKeep:
2860 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2861 return @"REINSTALL";
2862 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2866 case pkgDepCache::ModeInstall:
2867 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2868 return @"REINSTALL";
2869 else*/ switch (state.Status) {
2871 return @"DOWNGRADE";
2877 return @"NEW_INSTALL";
2888 - (NSString *) name {
2889 return name_.empty() ? id_ : name_;
2892 - (UIImage *) icon {
2893 NSString *section = [self simpleSection];
2896 if (parsed_ != NULL)
2897 if (NSString *href = parsed_->icon_)
2898 if ([href hasPrefix:@"file:///"])
2899 // XXX: correct escaping
2900 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2901 if (icon == nil) if (section != nil)
2902 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2903 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2904 if ([dicon hasPrefix:@"file:///"])
2905 // XXX: correct escaping
2906 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2908 icon = [UIImage applicationImageNamed:@"unknown.png"];
2912 - (NSString *) homepage {
2913 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2916 - (NSString *) depiction {
2917 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2920 - (Address *) sponsor {
2921 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2924 - (Address *) author {
2925 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2928 - (NSString *) support {
2929 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2932 - (NSArray *) files {
2933 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2934 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2937 fin.open([path UTF8String]);
2942 while (std::getline(fin, line))
2943 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2948 - (NSString *) state {
2949 @synchronized (database_) {
2950 if ([database_ era] != era_ || file_.end())
2953 switch (iterator_->CurrentState) {
2954 case pkgCache::State::NotInstalled:
2955 return @"NotInstalled";
2956 case pkgCache::State::UnPacked:
2958 case pkgCache::State::HalfConfigured:
2959 return @"HalfConfigured";
2960 case pkgCache::State::HalfInstalled:
2961 return @"HalfInstalled";
2962 case pkgCache::State::ConfigFiles:
2963 return @"ConfigFiles";
2964 case pkgCache::State::Installed:
2965 return @"Installed";
2966 case pkgCache::State::TriggersAwaited:
2967 return @"TriggersAwaited";
2968 case pkgCache::State::TriggersPending:
2969 return @"TriggersPending";
2972 return (NSString *) [NSNull null];
2975 - (NSString *) selection {
2976 @synchronized (database_) {
2977 if ([database_ era] != era_ || file_.end())
2980 switch (iterator_->SelectedState) {
2981 case pkgCache::State::Unknown:
2983 case pkgCache::State::Install:
2985 case pkgCache::State::Hold:
2987 case pkgCache::State::DeInstall:
2988 return @"DeInstall";
2989 case pkgCache::State::Purge:
2993 return (NSString *) [NSNull null];
2996 - (NSArray *) warnings {
2997 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2998 const char *name(iterator_.Name());
3000 size_t length(strlen(name));
3001 if (length < 2) invalid:
3002 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3003 else for (size_t i(0); i != length; ++i)
3005 /* XXX: technically this is not allowed */
3006 (name[i] < 'A' || name[i] > 'Z') &&
3007 (name[i] < 'a' || name[i] > 'z') &&
3008 (name[i] < '0' || name[i] > '9') &&
3009 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3012 if (strcmp(name, "cydia") != 0) {
3015 bool _private = false;
3018 bool repository = [[self section] isEqualToString:@"Repositories"];
3020 if (NSArray *files = [self files])
3021 for (NSString *file in files)
3022 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3024 else if (!user && [file isEqualToString:@"/User"])
3026 else if (!_private && [file isEqualToString:@"/private"])
3028 else if (!stash && [file isEqualToString:@"/var/stash"])
3031 /* XXX: this is not sensitive enough. only some folders are valid. */
3032 if (cydia && !repository)
3033 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3035 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3037 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3039 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3042 return [warnings count] == 0 ? nil : warnings;
3045 - (NSArray *) applications {
3046 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3048 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3050 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
3051 if (NSArray *files = [self files])
3052 for (NSString *file in files)
3053 if (application_r(file)) {
3054 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3055 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3056 if ([id isEqualToString:me])
3059 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3061 display = application_r[1];
3063 NSString *bundle([file stringByDeletingLastPathComponent]);
3064 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3065 if (icon == nil || [icon length] == 0)
3067 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3069 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3070 [applications addObject:application];
3072 [application addObject:id];
3073 [application addObject:display];
3074 [application addObject:url];
3077 return [applications count] == 0 ? nil : applications;
3080 - (Source *) source {
3081 if (source_ == nil) {
3082 @synchronized (database_) {
3083 if ([database_ era] != era_ || file_.end())
3084 source_ = (Source *) [NSNull null];
3086 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
3090 return source_ == (Source *) [NSNull null] ? nil : source_;
3093 - (BOOL) matches:(NSString *)text {
3099 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
3100 if (range.location != NSNotFound)
3103 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
3104 if (range.location != NSNotFound)
3109 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
3110 if (range.location != NSNotFound)
3116 - (bool) hasSupportingRole {
3121 if ([Role_ isEqualToString:@"User"])
3125 if ([Role_ isEqualToString:@"Hacker"])
3129 if ([Role_ isEqualToString:@"Developer"])
3134 - (NSArray *) tags {
3138 - (BOOL) hasTag:(NSString *)tag {
3139 return tags_ == nil ? NO : [tags_ containsObject:tag];
3142 - (NSString *) primaryPurpose {
3143 for (NSString *tag in tags_)
3144 if ([tag hasPrefix:@"purpose::"])
3145 return [tag substringFromIndex:9];
3149 - (NSArray *) purposes {
3150 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3151 for (NSString *tag in tags_)
3152 if ([tag hasPrefix:@"purpose::"])
3153 [purposes addObject:[tag substringFromIndex:9]];
3154 return [purposes count] == 0 ? nil : purposes;
3157 - (bool) isCommercial {
3158 return [self hasTag:@"cydia::commercial"];
3161 - (void) setIndex:(size_t)index {
3162 if (metadata_->index_ != index)
3163 metadata_->index_ = index;
3166 - (CYString &) cyname {
3167 return name_.empty() ? id_ : name_;
3170 - (uint32_t) compareBySection:(NSArray *)sections {
3171 NSString *section([self section]);
3172 for (size_t i(0), e([sections count]); i != e; ++i) {
3173 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3177 return _not(uint32_t);
3181 @synchronized (database_) {
3182 pkgProblemResolver *resolver = [database_ resolver];
3183 resolver->Clear(iterator_);
3185 pkgCacheFile &cache([database_ cache]);
3186 cache->SetReInstall(iterator_, false);
3187 cache->MarkKeep(iterator_, false);
3191 @synchronized (database_) {
3192 pkgProblemResolver *resolver = [database_ resolver];
3193 resolver->Clear(iterator_);
3194 resolver->Protect(iterator_);
3196 pkgCacheFile &cache([database_ cache]);
3197 cache->SetReInstall(iterator_, false);
3198 cache->MarkInstall(iterator_, false);
3200 pkgDepCache::StateCache &state((*cache)[iterator_]);
3201 if (!state.Install())
3202 cache->SetReInstall(iterator_, true);
3206 @synchronized (database_) {
3207 pkgProblemResolver *resolver = [database_ resolver];
3208 resolver->Clear(iterator_);
3209 resolver->Remove(iterator_);
3210 resolver->Protect(iterator_);
3212 pkgCacheFile &cache([database_ cache]);
3213 cache->SetReInstall(iterator_, false);
3214 cache->MarkDelete(iterator_, true);
3217 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3218 _profile(Package$isUnfilteredAndSearchedForBy)
3221 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3222 value &= [self unfiltered];
3225 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3226 value &= [self matches:search];
3233 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3234 if ([search length] == 0)
3237 _profile(Package$isUnfilteredAndSelectedForBy)
3240 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3241 value &= [self unfiltered];
3244 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3245 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3252 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3253 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3256 - (bool) isVisibleInSection:(NSString *)name {
3257 NSString *section([self section]);
3261 section == nil && [name length] == 0 ||
3262 [name isEqualToString:section]
3263 ) && [self visible];
3266 - (bool) isVisibleInSource:(Source *)source {
3267 return [self source] == source && [self visible];
3272 /* Section Class {{{ */
3273 @interface Section : NSObject {
3278 NSString *localized_;
3281 - (NSComparisonResult) compareByLocalized:(Section *)section;
3282 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3283 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3284 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3285 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3286 - (NSString *) name;
3293 - (void) addToCount;
3295 - (void) setCount:(size_t)count;
3296 - (NSString *) localized;
3300 @implementation Section
3304 if (localized_ != nil)
3305 [localized_ release];
3309 - (NSComparisonResult) compareByLocalized:(Section *)section {
3310 NSString *lhs(localized_);
3311 NSString *rhs([section localized]);
3313 /*if ([lhs length] != 0 && [rhs length] != 0) {
3314 unichar lhc = [lhs characterAtIndex:0];
3315 unichar rhc = [rhs characterAtIndex:0];
3317 if (isalpha(lhc) && !isalpha(rhc))
3318 return NSOrderedAscending;
3319 else if (!isalpha(lhc) && isalpha(rhc))
3320 return NSOrderedDescending;
3323 return [lhs compare:rhs options:LaxCompareOptions_];
3326 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3327 if ((self = [self initWithName:name localize:NO]) != nil) {
3328 if (localized != nil)
3329 localized_ = [localized retain];
3333 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3334 return [self initWithName:name row:0 localize:localize];
3337 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3338 if ((self = [super init]) != nil) {
3339 name_ = [name retain];
3343 localized_ = [LocalizeSection(name_) retain];
3347 /* XXX: localize the index thingees */
3348 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3349 if ((self = [super init]) != nil) {
3350 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3356 - (NSString *) name {
3376 - (void) addToCount {
3380 - (void) setCount:(size_t)count {
3384 - (NSString *) localized {
3391 static NSString *Colon_;
3392 static NSString *Elision_;
3393 static NSString *Error_;
3394 static NSString *Warning_;
3396 /* Database Implementation {{{ */
3397 @implementation Database
3399 + (Database *) sharedInstance {
3400 static Database *instance;
3401 if (instance == nil)
3402 instance = [[Database alloc] init];
3410 - (void) releasePackages {
3411 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3412 CFArrayRemoveAllValues(packages_);
3416 // XXX: actually implement this thing
3418 [sourceList_ release];
3419 [self releasePackages];
3420 apr_pool_destroy(pool_);
3421 NSRecycleZone(zone_);
3425 - (void) _readCydia:(NSNumber *)fd { _pooled
3426 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3427 std::istream is(&ib);
3430 static Pcre finish_r("^finish:([^:]*)$");
3432 while (std::getline(is, line)) {
3433 const char *data(line.c_str());
3434 size_t size = line.size();
3435 lprintf("C:%s\n", data);
3437 if (finish_r(data, size)) {
3438 NSString *finish = finish_r[1];
3439 int index = [Finishes_ indexOfObject:finish];
3440 if (index != INT_MAX && index > Finish_)
3448 - (void) _readStatus:(NSNumber *)fd { _pooled
3449 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3450 std::istream is(&ib);
3453 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3454 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3456 while (std::getline(is, line)) {
3457 const char *data(line.c_str());
3458 size_t size(line.size());
3459 lprintf("S:%s\n", data);
3461 if (conffile_r(data, size)) {
3462 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3463 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3464 } else if (strncmp(data, "status: ", 8) == 0) {
3465 // status: <package>: {unpacked,half-configured,installed}
3466 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3467 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3468 } else if (strncmp(data, "processing: ", 12) == 0) {
3469 // processing: configure: config-test
3470 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3471 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3472 } else if (pmstatus_r(data, size)) {
3473 std::string type([pmstatus_r[1] UTF8String]);
3475 NSString *package = pmstatus_r[2];
3476 if ([package isEqualToString:@"dpkg-exec"])
3479 float percent([pmstatus_r[3] floatValue]);
3480 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3482 NSString *string = pmstatus_r[4];
3484 if (type == "pmerror") {
3485 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3486 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3487 } else if (type == "pmstatus") {
3488 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3489 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3490 } else if (type == "pmconffile")
3491 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3493 lprintf("E:unknown pmstatus\n");
3495 lprintf("E:unknown status\n");
3501 - (void) _readOutput:(NSNumber *)fd { _pooled
3502 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3503 std::istream is(&ib);
3506 while (std::getline(is, line)) {
3507 lprintf("O:%s\n", line.c_str());
3509 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3510 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3520 - (Package *) packageWithName:(NSString *)name {
3521 @synchronized (self) {
3522 if (static_cast<pkgDepCache *>(cache_) == NULL)
3524 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3525 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3529 if ((self = [super init]) != nil) {
3536 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3537 apr_pool_create(&pool_, NULL);
3539 size_t capacity(MetaFile_->active_);
3545 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3546 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3550 _assert(pipe(fds) != -1);
3553 _config->Set("APT::Keep-Fds::", cydiafd_);
3554 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3557 detachNewThreadSelector:@selector(_readCydia:)
3559 withObject:[NSNumber numberWithInt:fds[0]]
3562 _assert(pipe(fds) != -1);
3566 detachNewThreadSelector:@selector(_readStatus:)
3568 withObject:[NSNumber numberWithInt:fds[0]]
3571 _assert(pipe(fds) != -1);
3572 _assert(dup2(fds[0], 0) != -1);
3573 _assert(close(fds[0]) != -1);
3575 input_ = fdopen(fds[1], "a");
3577 _assert(pipe(fds) != -1);
3578 _assert(dup2(fds[1], 1) != -1);
3579 _assert(close(fds[1]) != -1);
3582 detachNewThreadSelector:@selector(_readOutput:)
3584 withObject:[NSNumber numberWithInt:fds[0]]
3589 - (pkgCacheFile &) cache {
3593 - (pkgDepCache::Policy *) policy {
3597 - (pkgRecords *) records {
3601 - (pkgProblemResolver *) resolver {
3605 - (pkgAcquire &) fetcher {
3609 - (pkgSourceList &) list {
3613 - (NSArray *) packages {
3614 return (NSArray *) packages_;
3617 - (NSArray *) sources {
3621 - (Source *) sourceWithKey:(NSString *)key {
3622 for (Source *source in [self sources]) {
3623 if ([[source key] isEqualToString:key])
3628 - (bool) popErrorWithTitle:(NSString *)title {
3631 while (!_error->empty()) {
3633 bool warning(!_error->PopMessage(error));
3638 size_t size(error.size());
3639 if (size == 0 || error[size - 1] != '\n')
3641 error.resize(size - 1);
3644 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3646 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3652 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3653 return [self popErrorWithTitle:title] || !success;
3656 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3657 @synchronized (self) {
3660 [self releasePackages];
3663 [sourceList_ removeAllObjects];
3683 apr_pool_clear(pool_);
3685 NSRecycleZone(zone_);
3686 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3688 int chk(creat("/tmp/cydia.chk", 0644));
3692 if (invocation != nil)
3693 [invocation invoke];
3695 NSString *title(UCLocalize("DATABASE"));
3698 OpProgress progress;
3699 while (!cache_.Open(progress, true)) { pop:
3701 bool warning(!_error->PopMessage(error));
3702 lprintf("cache_.Open():[%s]\n", error.c_str());
3704 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3705 [delegate_ repairWithSelector:@selector(configure)];
3706 else if (error == "The package lists or status file could not be parsed or opened.")
3707 [delegate_ repairWithSelector:@selector(update)];
3708 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3709 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3710 // else if (error == "Malformed Status line")
3711 // else if (error == "The list of sources could not be read.")
3713 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3723 unlink("/tmp/cydia.chk");
3725 now_ = [[NSDate date] timeIntervalSince1970];
3727 policy_ = new pkgDepCache::Policy();
3728 records_ = new pkgRecords(cache_);
3729 resolver_ = new pkgProblemResolver(cache_);
3730 fetcher_ = new pkgAcquire(&status_);
3733 list_ = new pkgSourceList();
3734 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3737 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3738 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3742 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3745 if (cache_->BrokenCount() != 0) {
3746 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3749 if (cache_->BrokenCount() != 0) {
3750 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3754 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3758 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3759 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3760 [sourceList_ addObject:object];
3762 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3763 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3764 // XXX: this could be more intelligent
3765 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3766 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3768 sourceMap_[cached->ID] = object;
3773 /*std::vector<Package *> packages;
3774 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3775 [packages_ release];
3780 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3781 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3782 //packages.push_back(package);
3783 CFArrayAppendValue(packages_, [package retain]);
3787 /*if (packages.empty())
3788 packages_ = [[NSArray alloc] init];
3790 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3793 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3794 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3795 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3803 /*if (!packages.empty())
3804 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3805 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3807 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3809 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3811 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3815 size_t count(CFArrayGetCount(packages_));
3816 MetaFile_->active_ = count;
3818 for (size_t index(0); index != count; ++index)
3819 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3823 } } CYPoolEnd() _trace(); }
3826 @synchronized (self) {
3828 resolver_ = new pkgProblemResolver(cache_);
3830 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3831 if (!cache_[iterator].Keep())
3832 cache_->MarkKeep(iterator, false);
3833 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3834 cache_->SetReInstall(iterator, false);
3837 - (void) configure {
3838 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3840 system([dpkg UTF8String]);
3845 // XXX: I don't remember this condition
3850 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3852 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3854 if ([self popErrorWithTitle:title])
3858 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3861 public pkgArchiveCleaner
3864 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3869 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3876 fetcher_->Shutdown();
3878 pkgRecords records(cache_);
3880 lock_ = new FileFd();
3881 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3883 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3885 if ([self popErrorWithTitle:title])
3889 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3892 manager_ = (_system->CreatePM(cache_));
3893 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3900 bool substrate(RestartSubstrate_);
3901 RestartSubstrate_ = false;
3903 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3905 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3907 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3909 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3910 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3913 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3915 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3917 [self popErrorWithTitle:title];
3921 bool failed = false;
3922 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3923 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3925 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3931 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3939 RestartSubstrate_ = true;
3942 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3944 if (_error->PendingError()) {
3949 if (result == pkgPackageManager::Failed) {
3954 if (result != pkgPackageManager::Completed) {
3959 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3961 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3963 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3964 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3967 if (![before isEqualToArray:after])
3972 NSString *title(UCLocalize("UPGRADE"));
3973 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3979 [self updateWithStatus:status_];
3982 - (void) updateWithStatus:(Status &)status {
3983 NSString *title(UCLocalize("REFRESHING_DATA"));
3986 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3990 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3991 if ([self popErrorWithTitle:title])
3994 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3996 bool success(ListUpdate(status, list, PulseInterval_));
3997 if (status.WasCancelled())
4000 [self popErrorWithTitle:title forOperation:success];
4002 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4004 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
4008 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4009 delegate_ = delegate;
4012 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4013 progress_ = delegate;
4014 status_.setDelegate(delegate);
4017 - (NSObject<ProgressDelegate> *) progressDelegate {
4021 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4022 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4023 return i == sourceMap_.end() ? nil : i->second;
4026 - (NSString *) mappedSectionForPointer:(const char *)section {
4027 _H<NSString> *mapped;
4029 _profile(Database$mappedSectionForPointer$Cache)
4030 mapped = §ions_[section];
4033 if (*mapped == NULL) {
4034 size_t length(strlen(section));
4035 char spaced[length + 1];
4037 _profile(Database$mappedSectionForPointer$Replace)
4038 for (size_t index(0); index != length; ++index)
4039 spaced[index] = section[index] == '_' ? ' ' : section[index];
4040 spaced[length] = '\0';
4045 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4046 string = [NSString stringWithUTF8String:spaced];
4049 _profile(Database$mappedSectionForPointer$Map)
4050 string = [SectionMap_ objectForKey:string] ?: string;
4060 @interface Diversion : NSObject {
4063 _H<NSString> format_;
4068 @implementation Diversion
4070 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4071 if ((self = [super init]) != nil) {
4072 pattern_ = [from UTF8String];
4078 - (NSString *) divert:(NSString *)url {
4082 size_t count(pattern_.size());
4084 for (size_t i(0); i != count; ++i)
4085 values[i] = pattern_[i + 1];
4087 return [[[NSString alloc] initWithFormat:format_ arguments:reinterpret_cast<va_list>(values)] autorelease];
4090 - (NSString *) key {
4094 - (NSUInteger) hash {
4098 - (BOOL) isEqual:(Diversion *)object {
4099 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4104 @interface CydiaObject : NSObject {
4106 _transient id delegate_;
4109 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4113 @interface CYBrowserController : BrowserController {
4114 CydiaObject *cydia_;
4117 + (void) addDiversion:(Diversion *)diversion;
4121 static NSMutableSet *Diversions_;
4123 /* Web Scripting {{{ */
4124 @implementation CydiaObject
4127 [indirect_ release];
4131 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4132 if ((self = [super init]) != nil) {
4133 indirect_ = [indirect retain];
4137 - (void) setDelegate:(id)delegate {
4138 delegate_ = delegate;
4141 + (NSArray *) _attributeKeys {
4142 return [NSArray arrayWithObjects:
4157 - (NSArray *) attributeKeys {
4158 return [[self class] _attributeKeys];
4161 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4162 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4165 - (NSString *) version {
4169 - (NSString *) device {
4170 return [[UIDevice currentDevice] uniqueIdentifier];
4173 - (NSString *) firmware {
4174 return [[UIDevice currentDevice] systemVersion];
4177 - (NSString *) hostname {
4178 return [[UIDevice currentDevice] name];
4181 - (NSString *) idiom {
4182 return (id) Idiom_ ?: [NSNull null];
4185 - (NSString *) plmn {
4186 return (id) PLMN_ ?: [NSNull null];
4189 - (NSString *) ecid {
4190 return (id) ChipID_ ?: [NSNull null];
4193 - (NSString *) serial {
4194 return SerialNumber_;
4197 - (NSString *) role {
4198 return (id) Role_ ?: [NSNull null];
4201 - (NSString *) model {
4202 return [NSString stringWithUTF8String:Machine_];
4205 - (NSString *) token {
4206 return (id) Token_ ?: [NSNull null];
4209 + (NSString *) webScriptNameForSelector:(SEL)selector {
4211 else if (selector == @selector(addBridgedHost:))
4212 return @"addBridgedHost";
4213 else if (selector == @selector(addTrivialSource:))
4214 return @"addTrivialSource";
4215 else if (selector == @selector(close))
4217 else if (selector == @selector(divert::))
4219 else if (selector == @selector(du:))
4221 else if (selector == @selector(stringWithFormat:arguments:))
4223 else if (selector == @selector(getAllSources))
4224 return @"getAllSourcs";
4225 else if (selector == @selector(getKernelNumber:))
4226 return @"getKernelNumber";
4227 else if (selector == @selector(getKernelString:))
4228 return @"getKernelString";
4229 else if (selector == @selector(getInstalledPackages))
4230 return @"getInstalledPackages";
4231 else if (selector == @selector(getPackageById:))
4232 return @"getPackageById";
4233 else if (selector == @selector(installPackages:))
4234 return @"installPackages";
4235 else if (selector == @selector(localizedStringForKey:value:table:))
4237 else if (selector == @selector(popViewController:))
4238 return @"popViewController";
4239 else if (selector == @selector(refreshSources))
4240 return @"refreshSources";
4241 else if (selector == @selector(removeButton))
4242 return @"removeButton";
4243 else if (selector == @selector(substitutePackageNames:))
4244 return @"substitutePackageNames";
4245 else if (selector == @selector(scrollToBottom:))
4246 return @"scrollToBottom";
4247 else if (selector == @selector(setAllowsNavigationAction:))
4248 return @"setAllowsNavigationAction";
4249 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4250 return @"setButtonImage";
4251 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4252 return @"setButtonTitle";
4253 else if (selector == @selector(setHidesBackButton:))
4254 return @"setHidesBackButton";
4255 else if (selector == @selector(setHidesNavigationBar:))
4256 return @"setHidesNavigationBar";
4257 else if (selector == @selector(setNavigationBarStyle:))
4258 return @"setNavigationBarStyle";
4259 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4260 return @"setNavigationBarTintColor";
4261 else if (selector == @selector(setPopupHook:))
4262 return @"setPopupHook";
4263 else if (selector == @selector(setToken:))
4265 else if (selector == @selector(setViewportWidth:))
4266 return @"setViewportWidth";
4267 else if (selector == @selector(statfs:))
4269 else if (selector == @selector(supports:))
4275 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4276 return [self webScriptNameForSelector:selector] == nil;
4279 - (BOOL) supports:(NSString *)feature {
4280 return [feature isEqualToString:@"window.open"];
4283 - (void) divert:(NSString *)from :(NSString *)to {
4284 [CYBrowserController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4287 - (NSNumber *) getKernelNumber:(NSString *)name {
4288 const char *string([name UTF8String]);
4291 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4292 return (id) [NSNull null];
4294 if (size != sizeof(int))
4295 return (id) [NSNull null];
4298 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4299 return (id) [NSNull null];
4301 return [NSNumber numberWithInt:value];
4304 - (NSString *) getKernelString:(NSString *)name {
4305 const char *string([name UTF8String]);
4308 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4309 return (id) [NSNull null];
4311 char value[size + 1];
4312 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4313 return (id) [NSNull null];
4315 // XXX: just in case you request something ludicrous
4318 return [NSString stringWithCString:value];
4321 - (void) addBridgedHost:(NSString *)host {
4322 [delegate_ performSelectorOnMainThread:@selector(addBridgedHost:) withObject:host waitUntilDone:NO];
4325 - (void) popViewController:(NSNumber *)value {
4326 if (value == (id) [WebUndefined undefined])
4327 value = [NSNumber numberWithBool:YES];
4328 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4331 - (void) addTrivialSource:(NSString *)href {
4332 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4335 - (void) refreshSources {
4336 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4339 - (NSArray *) getAllSources {
4340 return [[Database sharedInstance] sources];
4343 - (NSArray *) getInstalledPackages {
4344 Database *database([Database sharedInstance]);
4345 @synchronized (database) {
4346 NSArray *packages([database packages]);
4347 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4348 for (Package *package in packages)
4349 if (![package uninstalled])
4350 [installed addObject:package];
4354 - (Package *) getPackageById:(NSString *)id {
4355 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4359 return (Package *) [NSNull null];
4362 - (NSArray *) statfs:(NSString *)path {
4365 if (path == nil || statfs([path UTF8String], &stat) == -1)
4368 return [NSArray arrayWithObjects:
4369 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4370 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4371 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4375 - (NSNumber *) du:(NSString *)path {
4376 NSNumber *value(nil);
4379 _assert(pipe(fds) != -1);
4381 pid_t pid(ExecFork());
4383 _assert(dup2(fds[1], 1) != -1);
4384 _assert(close(fds[0]) != -1);
4385 _assert(close(fds[1]) != -1);
4386 /* XXX: this should probably not use du */
4387 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4392 _assert(close(fds[1]) != -1);
4394 if (FILE *du = fdopen(fds[0], "r")) {
4396 while (fgets(line, sizeof(line), du) != NULL) {
4397 size_t length(strlen(line));
4398 while (length != 0 && line[length - 1] == '\n')
4399 line[--length] = '\0';
4400 if (char *tab = strchr(line, '\t')) {
4402 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4407 } else _assert(close(fds[0]));
4411 if (waitpid(pid, &status, 0) == -1)
4414 else _assert(false);
4420 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4423 - (void) installPackages:(NSArray *)packages {
4424 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4427 - (NSString *) substitutePackageNames:(NSString *)message {
4428 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4429 for (size_t i(0), e([words count]); i != e; ++i) {
4430 NSString *word([words objectAtIndex:i]);
4431 if (Package *package = [[Database sharedInstance] packageWithName:word])
4432 [words replaceObjectAtIndex:i withObject:[package name]];
4435 return [words componentsJoinedByString:@" "];
4438 - (void) removeButton {
4439 [indirect_ removeButton];
4442 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4443 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4446 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4447 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4450 - (void) setAllowsNavigationAction:(NSString *)value {
4451 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4454 - (void) setHidesBackButton:(NSString *)value {
4455 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4458 - (void) setHidesNavigationBar:(NSString *)value {
4459 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4462 - (void) setNavigationBarStyle:(NSString *)value {
4463 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4466 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4467 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4468 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4469 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4472 - (void) _setToken:(NSString *)token {
4476 [Metadata_ removeObjectForKey:@"Token"];
4478 [Metadata_ setObject:Token_ forKey:@"Token"];
4483 - (void) setToken:(NSString *)token {
4484 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4487 - (void) setPopupHook:(id)function {
4488 [indirect_ setPopupHook:function];
4491 - (void) scrollToBottom:(NSNumber *)animated {
4492 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4495 - (void) setViewportWidth:(float)width {
4496 [indirect_ setViewportWidthOnMainThread:width];
4499 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4500 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4501 unsigned count([arguments count]);
4503 for (unsigned i(0); i != count; ++i)
4504 values[i] = [arguments objectAtIndex:i];
4505 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4508 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4509 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4511 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4513 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4519 /* @ Loading... Indicator {{{ */
4520 @interface CYLoadingIndicator : UIView {
4521 _H<UIActivityIndicatorView> spinner_;
4523 _H<UIView> container_;
4526 @property (readonly, nonatomic) UILabel *label;
4527 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4531 @implementation CYLoadingIndicator
4533 - (id) initWithFrame:(CGRect)frame {
4534 if ((self = [super initWithFrame:frame]) != nil) {
4535 container_ = [[[UIView alloc] init] autorelease];
4536 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4538 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4539 [spinner_ startAnimating];
4540 [container_ addSubview:spinner_];
4542 label_ = [[[UILabel alloc] init] autorelease];
4543 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4544 [label_ setBackgroundColor:[UIColor clearColor]];
4545 [label_ setTextColor:[UIColor blackColor]];
4546 [label_ setShadowColor:[UIColor whiteColor]];
4547 [label_ setShadowOffset:CGSizeMake(0, 1)];
4548 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4549 [container_ addSubview:label_];
4551 CGSize viewsize = frame.size;
4552 CGSize spinnersize = [spinner_ bounds].size;
4553 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4554 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4556 CGRect containrect = {
4557 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4558 CGSizeMake(bothwidth, spinnersize.height)
4561 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4569 [container_ setFrame:containrect];
4570 [spinner_ setFrame:spinrect];
4571 [label_ setFrame:textrect];
4572 [self addSubview:container_];
4576 - (UILabel *) label {
4580 - (UIActivityIndicatorView *) activityIndicatorView {
4586 /* Emulated Loading Controller {{{ */
4587 @interface CYEmulatedLoadingController : CYViewController {
4588 _transient Database *database_;
4589 _H<CYLoadingIndicator> indicator_;
4590 _H<UITabBar> tabbar_;
4591 _H<UINavigationBar> navbar_;
4596 @implementation CYEmulatedLoadingController
4598 - (id) initWithDatabase:(Database *)database {
4599 if ((self = [super init]) != nil) {
4600 database_ = database;
4605 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4607 UITableView *table([[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]);
4608 [table setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4609 [[self view] addSubview:table];
4611 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4612 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4613 [[self view] addSubview:indicator_];
4615 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4616 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4617 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4618 [[self view] addSubview:tabbar_];
4620 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4621 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4622 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4623 [[self view] addSubview:navbar_];
4626 - (void) releaseSubviews {
4635 /* Cydia Browser Controller {{{ */
4636 @implementation CYBrowserController
4643 - (NSURL *) navigationURL {
4644 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4647 + (void) initialize {
4648 Diversions_ = [[NSMutableSet alloc] initWithCapacity:0];
4651 + (void) addDiversion:(Diversion *)diversion {
4652 [Diversions_ addObject:diversion];
4655 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4656 [super webView:view didClearWindowObject:window forFrame:frame];
4658 WebDataSource *source([frame dataSource]);
4659 NSURLResponse *response([source response]);
4660 NSURL *url([response URL]);
4662 if ([[[url scheme] lowercaseString] isEqualToString:@"https"])
4663 if ([BridgedHosts_ containsObject:[url host]])
4664 [window setValue:cydia_ forKey:@"cydia"];
4667 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4668 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4671 NSURL *url([copy URL]);
4672 NSString *href([url absoluteString]);
4674 for (Diversion *diversion in Diversions_)
4675 if (NSString *diverted = [diversion divert:href]) {
4676 [copy setURL:[NSURL URLWithString:diverted]];
4680 if (System_ != NULL)
4681 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4682 if (Machine_ != NULL)
4683 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4685 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4690 - (void) setDelegate:(id)delegate {
4691 [super setDelegate:delegate];
4692 [cydia_ setDelegate:delegate];
4696 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4697 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4699 WebView *webview([[webview_ _documentView] webView]);
4701 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4704 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4706 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4707 if (Product_ != nil)
4708 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4710 [webview setApplicationNameForUserAgent:application];
4718 @interface NSObject (CydiaScript)
4719 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4722 @implementation NSObject (CydiaScript)
4724 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4730 @implementation NSArray (CydiaScript)
4732 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4733 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4734 for (size_t i(0), e([self count]); i != e; ++i)
4735 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4741 @implementation NSDictionary (CydiaScript)
4743 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4744 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4746 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4753 /* Confirmation Controller {{{ */
4754 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4755 if (!iterator.end())
4756 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4757 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4759 pkgCache::PkgIterator package(dep.TargetPkg());
4762 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4769 @protocol ConfirmationControllerDelegate
4770 - (void) cancelAndClear:(bool)clear;
4771 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4775 @interface ConfirmationController : CYBrowserController {
4776 _transient Database *database_;
4778 UIAlertView *essential_;
4780 NSDictionary *changes_;
4781 NSMutableArray *issues_;
4782 NSDictionary *sizes_;
4787 - (id) initWithDatabase:(Database *)database;
4791 @implementation ConfirmationController
4798 if (essential_ != nil)
4799 [essential_ release];
4806 RestartSubstrate_ = true;
4807 [delegate_ confirmWithNavigationController:[self navigationController]];
4810 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4811 NSString *context([alert context]);
4813 if ([context isEqualToString:@"remove"]) {
4814 if (button == [alert cancelButtonIndex])
4815 [self dismissModalViewControllerAnimated:YES];
4816 else if (button == [alert firstOtherButtonIndex]) {
4820 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4821 } else if ([context isEqualToString:@"unable"]) {
4822 [self dismissModalViewControllerAnimated:YES];
4823 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4825 [super alertView:alert clickedButtonAtIndex:button];
4829 - (void) _doContinue {
4830 [self dismissModalViewControllerAnimated:YES];
4831 [delegate_ cancelAndClear:NO];
4834 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4835 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4839 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4840 [super webView:view didClearWindowObject:window forFrame:frame];
4842 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4843 changes_, @"changes",
4847 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4850 - (id) initWithDatabase:(Database *)database {
4851 if ((self = [super init]) != nil) {
4852 database_ = database;
4854 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4855 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4856 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4857 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4858 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4862 pkgCacheFile &cache([database_ cache]);
4863 NSArray *packages([database_ packages]);
4864 pkgDepCache::Policy *policy([database_ policy]);
4866 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4868 for (Package *package in packages) {
4869 pkgCache::PkgIterator iterator([package iterator]);
4870 NSString *name([package id]);
4872 if ([package broken]) {
4873 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4875 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4877 reasons, @"reasons",
4880 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4884 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4885 pkgCache::DepIterator start;
4886 pkgCache::DepIterator end;
4887 dep.GlobOr(start, end); // ++dep
4889 if (!cache->IsImportantDep(end))
4891 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4894 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4896 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4897 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4898 clauses, @"clauses",
4902 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4904 pkgCache::PkgIterator target(start.TargetPkg());
4905 if (target->ProvidesList != 0)
4906 reason = @"missing";
4908 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4910 reason = @"installed";
4911 installed = [NSString stringWithUTF8String:ver.VerStr()];
4912 } else if (!cache[target].CandidateVerIter(cache).end())
4913 reason = @"uninstalled";
4914 else if (target->ProvidesList == 0)
4915 reason = @"uninstallable";
4917 reason = @"virtual";
4920 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4921 [NSString stringWithUTF8String:start.CompType()], @"operator",
4922 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4925 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4926 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4927 version, @"version",
4929 installed, @"installed",
4932 // yes, seriously. (wtf?)
4940 pkgDepCache::StateCache &state(cache[iterator]);
4942 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4944 if (state.NewInstall())
4945 [installs addObject:name];
4946 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4947 [reinstalls addObject:name];
4948 else if (state.Upgrade())
4949 [upgrades addObject:name];
4950 else if (state.Downgrade())
4951 [downgrades addObject:name];
4952 else if (!state.Delete())
4954 else if (special_r(name))
4955 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4956 [NSNull null], @"package",
4957 [NSArray arrayWithObjects:
4958 [NSDictionary dictionaryWithObjectsAndKeys:
4959 @"Conflicts", @"relationship",
4960 [NSArray arrayWithObjects:
4961 [NSDictionary dictionaryWithObjectsAndKeys:
4963 [NSNull null], @"version",
4964 @"installed", @"reason",
4971 if ([package essential])
4973 [removes addObject:name];
4976 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4977 substrate_ |= DepSubstrate(iterator.CurrentVer());
4982 else if (Advanced_) {
4983 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4985 essential_ = [[UIAlertView alloc]
4986 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4987 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4989 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4991 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4995 [essential_ setContext:@"remove"];
4997 essential_ = [[UIAlertView alloc]
4998 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4999 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5001 cancelButtonTitle:UCLocalize("OKAY")
5002 otherButtonTitles:nil
5005 [essential_ setContext:@"unable"];
5008 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
5009 installs, @"installs",
5010 reinstalls, @"reinstalls",
5011 upgrades, @"upgrades",
5012 downgrades, @"downgrades",
5013 removes, @"removes",
5016 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
5017 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5018 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5021 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5023 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
5024 initWithTitle:UCLocalize("CANCEL")
5025 style:UIBarButtonItemStylePlain
5027 action:@selector(cancelButtonClicked)
5033 - (void) applyRightButton {
5034 if ([issues_ count] == 0 && ![self isLoading])
5035 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5036 initWithTitle:UCLocalize("CONFIRM")
5037 style:UIBarButtonItemStyleDone
5039 action:@selector(confirmButtonClicked)
5042 [[self navigationItem] setRightBarButtonItem:nil];
5046 - (void) cancelButtonClicked {
5047 [self dismissModalViewControllerAnimated:YES];
5048 [delegate_ cancelAndClear:YES];
5052 - (void) confirmButtonClicked {
5053 if (essential_ != nil)
5063 /* Progress Data {{{ */
5064 @interface CydiaProgressData : NSObject {
5065 _transient id delegate_;
5074 _H<NSMutableArray> events_;
5075 _H<NSString> title_;
5077 _H<NSString> status_;
5078 _H<NSString> finish_;
5083 @implementation CydiaProgressData
5085 + (NSArray *) _attributeKeys {
5086 return [NSArray arrayWithObjects:
5098 - (NSArray *) attributeKeys {
5099 return [[self class] _attributeKeys];
5102 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5103 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5107 if ((self = [super init]) != nil) {
5108 events_ = [NSMutableArray arrayWithCapacity:32];
5112 - (void) setDelegate:(id)delegate {
5113 delegate_ = delegate;
5116 - (void) setPercent:(float)value {
5120 - (NSNumber *) percent {
5121 return [NSNumber numberWithFloat:percent_];
5124 - (void) setCurrent:(float)value {
5128 - (NSNumber *) current {
5129 return [NSNumber numberWithFloat:current_];
5132 - (void) setTotal:(float)value {
5136 - (NSNumber *) total {
5137 return [NSNumber numberWithFloat:total_];
5140 - (void) setSpeed:(float)value {
5144 - (NSNumber *) speed {
5145 return [NSNumber numberWithFloat:speed_];
5148 - (NSArray *) events {
5152 - (void) removeAllEvents {
5153 [events_ removeAllObjects];
5156 - (void) addEvent:(CydiaProgressEvent *)event {
5157 [events_ addObject:event];
5160 - (void) setTitle:(NSString *)text {
5164 - (NSString *) title {
5168 - (void) setFinish:(NSString *)text {
5172 - (NSString *) finish {
5173 return (id) finish_ ?: [NSNull null];
5176 - (void) setRunning:(bool)running {
5180 - (NSNumber *) running {
5181 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5186 /* Progress Controller {{{ */
5187 @interface ProgressController : CYBrowserController <
5190 _transient Database *database_;
5191 _H<CydiaProgressData> progress_;
5195 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5197 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5199 - (void) setTitle:(NSString *)title;
5200 - (void) setCancellable:(bool)cancellable;
5204 @implementation ProgressController
5207 [database_ setProgressDelegate:nil];
5208 [progress_ setDelegate:nil];
5212 - (void) updateCancel {
5213 [[self navigationItem] setLeftBarButtonItem:(cancel_ == 1 ? [[[UIBarButtonItem alloc]
5214 initWithTitle:UCLocalize("CANCEL")
5215 style:UIBarButtonItemStylePlain
5217 action:@selector(cancel)
5218 ] autorelease] : nil)];
5221 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5222 if ((self = [super init]) != nil) {
5223 database_ = database;
5224 delegate_ = delegate;
5226 [database_ setProgressDelegate:self];
5228 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5229 [progress_ setDelegate:self];
5231 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5233 [scroller_ setBackgroundColor:[UIColor blackColor]];
5235 [[self navigationItem] setHidesBackButton:YES];
5237 [self updateCancel];
5241 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5242 [super webView:view didClearWindowObject:window forFrame:frame];
5243 [window setValue:progress_ forKey:@"cydiaProgress"];
5246 - (void) updateProgress {
5247 [self dispatchEvent:@"CydiaProgressUpdate"];
5250 - (void) viewWillAppear:(BOOL)animated {
5251 if (![self hasLoaded])
5252 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5254 [super viewWillAppear:animated];
5258 UpdateExternalStatus(0);
5265 [delegate_ terminateWithSuccess];
5266 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5267 [delegate_ suspendWithAnimation:YES];
5269 [delegate_ suspend];*/
5281 system("/usr/bin/sbreload");
5287 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5288 SBReboot(SBSSpringBoardServerPort());
5290 reboot2(RB_AUTOBOOT);
5297 - (void) setTitle:(NSString *)title {
5298 [progress_ setTitle:title];
5299 [self updateProgress];
5302 - (UIBarButtonItem *) rightButton {
5303 return [[progress_ running] boolValue] ? nil : [[[UIBarButtonItem alloc]
5304 initWithTitle:UCLocalize("CLOSE")
5305 style:UIBarButtonItemStylePlain
5307 action:@selector(close)
5311 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5312 UpdateExternalStatus(1);
5314 [progress_ setRunning:true];
5315 [self setTitle:title];
5316 // implicit updateProgress
5318 SHA1SumValue notifyconf; {
5320 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5323 MMap mmap(file, MMap::ReadOnly);
5325 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5326 notifyconf = sha1.Result();
5330 SHA1SumValue springlist; {
5332 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5335 MMap mmap(file, MMap::ReadOnly);
5337 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5338 springlist = sha1.Result();
5342 if (invocation != nil) {
5343 [invocation yieldToSelector:@selector(invoke)];
5344 [self setTitle:@"COMPLETE"];
5349 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5352 MMap mmap(file, MMap::ReadOnly);
5354 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5355 if (!(notifyconf == sha1.Result()))
5362 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5365 MMap mmap(file, MMap::ReadOnly);
5367 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5368 if (!(springlist == sha1.Result()))
5374 if (RestartSubstrate_)
5378 RestartSubstrate_ = false;
5381 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5382 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5383 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5384 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5385 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5389 system("su -c /usr/bin/uicache mobile");
5392 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5394 [progress_ setRunning:false];
5395 [self updateProgress];
5397 [self applyRightButton];
5400 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5401 [progress_ addEvent:event];
5402 [self updateProgress];
5405 - (bool) isProgressCancelled {
5406 return cancel_ == 2;
5411 [self updateCancel];
5414 - (void) setCancellable:(bool)cancellable {
5415 unsigned cancel(cancel_);
5419 else if (cancel_ == 0)
5422 if (cancel != cancel_)
5423 [self updateCancel];
5426 - (void) setProgressCancellable:(NSNumber *)cancellable {
5427 [self setCancellable:[cancellable boolValue]];
5430 - (void) setProgressPercent:(NSNumber *)percent {
5431 [progress_ setPercent:[percent floatValue]];
5432 [self updateProgress];
5435 - (void) setProgressStatus:(NSDictionary *)status {
5436 if (status == nil) {
5437 [progress_ setCurrent:0];
5438 [progress_ setTotal:0];
5439 [progress_ setSpeed:0];
5441 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5443 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5444 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5445 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5448 [self updateProgress];
5454 /* Cell Content View {{{ */
5455 @protocol ContentDelegate
5456 - (void) drawContentRect:(CGRect)rect;
5459 @interface ContentView : UIView {
5460 _transient id<ContentDelegate> delegate_;
5465 @implementation ContentView
5467 - (id) initWithFrame:(CGRect)frame {
5468 if ((self = [super initWithFrame:frame]) != nil) {
5469 [self setNeedsDisplayOnBoundsChange:YES];
5473 - (void) setDelegate:(id<ContentDelegate>)delegate {
5474 delegate_ = delegate;
5477 - (void) drawRect:(CGRect)rect {
5478 [super drawRect:rect];
5479 [delegate_ drawContentRect:rect];
5484 /* Cydia TableView Cell {{{ */
5485 @interface CYTableViewCell : UITableViewCell {
5486 ContentView *content_;
5492 @implementation CYTableViewCell
5499 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5500 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5502 if (view == content_) {
5503 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5504 highlighted_ = highlighted;
5507 [super _updateHighlightColorsForView:view highlighted:highlighted];
5510 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5511 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5512 highlighted_ = selected;
5514 [super setSelected:selected animated:animated];
5515 [content_ setNeedsDisplay];
5521 /* Package Cell {{{ */
5522 @interface PackageCell : CYTableViewCell <
5527 NSString *description_;
5535 - (PackageCell *) init;
5536 - (void) setPackage:(Package *)package;
5538 - (void) drawContentRect:(CGRect)rect;
5542 @implementation PackageCell
5544 - (void) clearPackage {
5555 if (description_ != nil) {
5556 [description_ release];
5560 if (source_ != nil) {
5565 if (badge_ != nil) {
5570 if (placard_ != nil) {
5580 [self clearPackage];
5584 - (PackageCell *) init {
5585 CGRect frame(CGRectMake(0, 0, 320, 74));
5586 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5587 UIView *content([self contentView]);
5588 CGRect bounds([content bounds]);
5590 content_ = [[ContentView alloc] initWithFrame:bounds];
5591 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5592 [content addSubview:content_];
5594 [content_ setDelegate:self];
5595 [content_ setOpaque:YES];
5599 - (NSString *) accessibilityLabel {
5600 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5603 - (void) setPackage:(Package *)package {
5604 [self clearPackage];
5607 Source *source = [package source];
5609 icon_ = [[package icon] retain];
5610 name_ = [[package name] retain];
5613 description_ = [package longDescription];
5614 if (description_ == nil)
5615 description_ = [package shortDescription];
5616 if (description_ != nil)
5617 description_ = [description_ retain];
5619 commercial_ = [package isCommercial];
5621 package_ = [package retain];
5623 NSString *label = nil;
5624 bool trusted = false;
5626 if (source != nil) {
5627 label = [source label];
5628 trusted = [source trusted];
5629 } else if ([[package id] isEqualToString:@"firmware"])
5630 label = UCLocalize("APPLE");
5632 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5634 NSString *from(label);
5636 NSString *section = [package simpleSection];
5637 if (section != nil && ![section isEqualToString:label]) {
5638 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5639 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5642 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5643 source_ = [from retain];
5645 if (NSString *purpose = [package primaryPurpose])
5646 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5647 badge_ = [badge_ retain];
5652 if (NSString *mode = [package_ mode]) {
5653 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5654 color = RemovingColor_;
5655 //placard = @"removing";
5657 color = InstallingColor_;
5658 //placard = @"installing";
5661 // XXX: the removing/installing placards are not @2x
5664 color = [UIColor whiteColor];
5666 if ([package installed] != nil)
5667 placard = @"installed";
5672 [content_ setBackgroundColor:color];
5675 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5676 placard_ = [placard_ retain];
5678 [self setNeedsDisplay];
5679 [content_ setNeedsDisplay];
5682 - (void) drawContentRect:(CGRect)rect {
5683 bool highlighted(highlighted_);
5684 float width([self bounds].size.width);
5687 CGContextRef context(UIGraphicsGetCurrentContext());
5688 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5689 CGContextFillRect(context, rect);
5694 rect.size = [icon_ size];
5696 rect.size.width /= 2;
5697 rect.size.height /= 2;
5699 rect.origin.x = 25 - rect.size.width / 2;
5700 rect.origin.y = 25 - rect.size.height / 2;
5702 [icon_ drawInRect:rect];
5705 if (badge_ != nil) {
5707 rect.size = [badge_ size];
5709 rect.size.width /= 2;
5710 rect.size.height /= 2;
5712 rect.origin.x = 36 - rect.size.width / 2;
5713 rect.origin.y = 36 - rect.size.height / 2;
5715 [badge_ drawInRect:rect];
5722 UISetColor(commercial_ ? Purple_ : Black_);
5723 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5724 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5727 UISetColor(commercial_ ? Purplish_ : Gray_);
5728 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5730 if (placard_ != nil)
5731 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5736 /* Section Cell {{{ */
5737 @interface SectionCell : CYTableViewCell <
5749 - (void) setSection:(Section *)section editing:(BOOL)editing;
5753 @implementation SectionCell
5755 - (void) clearSection {
5756 if (basic_ != nil) {
5761 if (section_ != nil) {
5771 if (count_ != nil) {
5778 [self clearSection];
5784 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5785 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5786 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5787 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5788 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5790 UIView *content([self contentView]);
5791 CGRect bounds([content bounds]);
5793 content_ = [[ContentView alloc] initWithFrame:bounds];
5794 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5795 [content addSubview:content_];
5796 [content_ setBackgroundColor:[UIColor whiteColor]];
5798 [content_ setDelegate:self];
5802 - (void) onSwitch:(id)sender {
5803 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5804 if (metadata == nil) {
5805 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5806 [Sections_ setObject:metadata forKey:basic_];
5809 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5813 - (void) setSection:(Section *)section editing:(BOOL)editing {
5814 if (editing != editing_) {
5816 [switch_ removeFromSuperview];
5818 [self addSubview:switch_];
5822 [self clearSection];
5824 if (section == nil) {
5825 name_ = [UCLocalize("ALL_PACKAGES") retain];
5828 basic_ = [section name];
5830 basic_ = [basic_ retain];
5832 section_ = [section localized];
5833 if (section_ != nil)
5834 section_ = [section_ retain];
5836 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5837 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5840 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5843 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5844 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5846 [content_ setNeedsDisplay];
5849 - (void) setFrame:(CGRect)frame {
5850 [super setFrame:frame];
5852 CGRect rect([switch_ frame]);
5853 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5856 - (NSString *) accessibilityLabel {
5860 - (void) drawContentRect:(CGRect)rect {
5861 bool highlighted(highlighted_ && !editing_);
5863 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5868 float width(rect.size.width);
5874 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5876 CGSize size = [count_ sizeWithFont:Font14_];
5880 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5886 /* File Table {{{ */
5887 @interface FileTable : CYViewController <
5888 UITableViewDataSource,
5891 _transient Database *database_;
5894 NSMutableArray *files_;
5898 - (id) initWithDatabase:(Database *)database;
5899 - (void) setPackage:(Package *)package;
5903 @implementation FileTable
5906 [self releaseSubviews];
5915 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5916 return files_ == nil ? 0 : [files_ count];
5919 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5923 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5924 static NSString *reuseIdentifier = @"Cell";
5926 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5928 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5929 [cell setFont:[UIFont systemFontOfSize:16]];
5931 [cell setText:[files_ objectAtIndex:indexPath.row]];
5932 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5937 - (NSURL *) navigationURL {
5938 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5942 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5944 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5945 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5946 [list_ setRowHeight:24.0f];
5947 [list_ setDataSource:self];
5948 [list_ setDelegate:self];
5949 [[self view] addSubview:list_];
5952 - (void) viewDidLoad {
5953 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5956 - (void) releaseSubviews {
5961 - (id) initWithDatabase:(Database *)database {
5962 if ((self = [super init]) != nil) {
5963 database_ = database;
5965 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5969 - (void) setPackage:(Package *)package {
5970 if (package_ != nil) {
5971 [package_ autorelease];
5980 [files_ removeAllObjects];
5982 if (package != nil) {
5983 package_ = [package retain];
5984 name_ = [[package id] retain];
5986 if (NSArray *files = [package files])
5987 [files_ addObjectsFromArray:files];
5989 if ([files_ count] != 0) {
5990 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5991 [files_ removeObjectAtIndex:0];
5992 [files_ sortUsingSelector:@selector(compareByPath:)];
5994 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5995 [stack addObject:@"/"];
5997 for (int i(0), e([files_ count]); i != e; ++i) {
5998 NSString *file = [files_ objectAtIndex:i];
5999 while (![file hasPrefix:[stack lastObject]])
6000 [stack removeLastObject];
6001 NSString *directory = [stack lastObject];
6002 [stack addObject:[file stringByAppendingString:@"/"]];
6003 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6004 ([stack count] - 2) * 3, "",
6005 [file substringFromIndex:[directory length]]
6014 - (void) reloadData {
6017 [self setPackage:[database_ packageWithName:name_]];
6022 /* Package Controller {{{ */
6023 @interface CYPackageController : CYBrowserController <
6024 UIActionSheetDelegate
6026 _transient Database *database_;
6027 _H<Package> package_;
6030 _H<NSMutableArray> buttons_;
6031 _H<UIBarButtonItem> button_;
6034 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
6038 @implementation CYPackageController
6040 - (NSURL *) navigationURL {
6041 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6044 /* XXX: this is not safe at all... localization of /fail/ */
6045 - (void) _clickButtonWithName:(NSString *)name {
6046 if ([name isEqualToString:UCLocalize("CLEAR")])
6047 [delegate_ clearPackage:package_];
6048 else if ([name isEqualToString:UCLocalize("INSTALL")])
6049 [delegate_ installPackage:package_];
6050 else if ([name isEqualToString:UCLocalize("REINSTALL")])
6051 [delegate_ installPackage:package_];
6052 else if ([name isEqualToString:UCLocalize("REMOVE")])
6053 [delegate_ removePackage:package_];
6054 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6055 [delegate_ installPackage:package_];
6056 else _assert(false);
6059 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6060 NSString *context([sheet context]);
6062 if ([context isEqualToString:@"modify"]) {
6063 if (button != [sheet cancelButtonIndex]) {
6064 NSString *buttonName = [buttons_ objectAtIndex:button];
6065 [self _clickButtonWithName:buttonName];
6068 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6072 - (bool) _allowJavaScriptPanel {
6077 - (void) _customButtonClicked {
6078 int count([buttons_ count]);
6083 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6085 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6086 [buttons addObjectsFromArray:buttons_];
6088 UIActionSheet *sheet = [[[UIActionSheet alloc]
6091 cancelButtonTitle:nil
6092 destructiveButtonTitle:nil
6093 otherButtonTitles:nil
6096 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6098 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6099 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6101 [sheet setContext:@"modify"];
6103 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6107 // We don't want to allow non-commercial packages to do custom things to the install button,
6108 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6109 - (void) customButtonClicked {
6111 [super customButtonClicked];
6113 [self _customButtonClicked];
6116 - (void) reloadButtonClicked {
6117 // Don't reload a commerical package by tapping the loading button,
6118 // but if it's not an Install button, we should forward it on.
6119 if (![package_ uninstalled])
6120 [self _customButtonClicked];
6123 - (void) applyLoadingTitle {
6124 // Don't show "Loading" as the title. Ever.
6127 - (UIBarButtonItem *) rightButton {
6132 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
6133 if ((self = [super init]) != nil) {
6134 database_ = database;
6135 buttons_ = [NSMutableArray arrayWithCapacity:4];
6136 name_ = [NSString stringWithString:name];
6137 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
6141 - (void) reloadData {
6142 package_ = [database_ packageWithName:name_];
6144 [buttons_ removeAllObjects];
6146 if (package_ != nil) {
6147 [(Package *) package_ parse];
6149 commercial_ = [package_ isCommercial];
6151 if ([package_ mode] != nil)
6152 [buttons_ addObject:UCLocalize("CLEAR")];
6153 if ([package_ source] == nil);
6154 else if ([package_ upgradableAndEssential:NO])
6155 [buttons_ addObject:UCLocalize("UPGRADE")];
6156 else if ([package_ uninstalled])
6157 [buttons_ addObject:UCLocalize("INSTALL")];
6159 [buttons_ addObject:UCLocalize("REINSTALL")];
6160 if (![package_ uninstalled])
6161 [buttons_ addObject:UCLocalize("REMOVE")];
6165 switch ([buttons_ count]) {
6166 case 0: title = nil; break;
6167 case 1: title = [buttons_ objectAtIndex:0]; break;
6168 default: title = UCLocalize("MODIFY"); break;
6171 button_ = [[[UIBarButtonItem alloc]
6173 style:UIBarButtonItemStylePlain
6175 action:@selector(customButtonClicked)
6181 - (bool) isLoading {
6182 return commercial_ ? [super isLoading] : false;
6188 /* Package List Controller {{{ */
6189 @interface PackageListController : CYViewController <
6190 UITableViewDataSource,
6193 _transient Database *database_;
6195 NSMutableArray *packages_;
6196 NSMutableArray *sections_;
6198 NSMutableArray *index_;
6199 NSMutableDictionary *indices_;
6203 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6204 - (void) setDelegate:(id)delegate;
6205 - (void) resetCursor;
6209 @implementation PackageListController
6212 [packages_ release];
6213 [sections_ release];
6222 - (void) deselectWithAnimation:(BOOL)animated {
6223 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6226 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6227 CGRect base = [[self view] bounds];
6228 base.size.height -= bounds.size.height;
6229 base.origin = [list_ frame].origin;
6231 [UIView beginAnimations:nil context:NULL];
6232 [UIView setAnimationBeginsFromCurrentState:YES];
6233 [UIView setAnimationCurve:curve];
6234 [UIView setAnimationDuration:duration];
6235 [list_ setFrame:base];
6236 [UIView commitAnimations];
6239 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6240 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6243 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6244 [self resizeForKeyboardBounds:bounds duration:0];
6247 - (void) keyboardWillShow:(NSNotification *)notification {
6250 NSTimeInterval duration;
6251 UIViewAnimationCurve curve;
6252 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6253 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6254 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6255 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6257 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);
6258 UIViewController *base = self;
6259 while ([base parentViewController] != nil)
6260 base = [base parentViewController];
6261 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6262 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6264 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6267 - (void) keyboardWillHide:(NSNotification *)notification {
6268 NSTimeInterval duration;
6269 UIViewAnimationCurve curve;
6270 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6271 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6273 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6276 - (void) viewWillAppear:(BOOL)animated {
6277 [super viewWillAppear:animated];
6279 [self resizeForKeyboardBounds:CGRectZero];
6280 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6281 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6284 - (void) viewWillDisappear:(BOOL)animated {
6285 [super viewWillDisappear:animated];
6287 [self resizeForKeyboardBounds:CGRectZero];
6288 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6289 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6292 - (void) viewDidAppear:(BOOL)animated {
6293 [super viewDidAppear:animated];
6294 [self deselectWithAnimation:animated];
6297 - (void) didSelectPackage:(Package *)package {
6298 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6299 [view setDelegate:delegate_];
6300 [[self navigationController] pushViewController:view animated:YES];
6303 #if TryIndexedCollation
6304 + (BOOL) hasIndexedCollation {
6305 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6309 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6310 NSInteger count([sections_ count]);
6311 return count == 0 ? 1 : count;
6314 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6315 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6317 return [[sections_ objectAtIndex:section] name];
6320 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6321 if ([sections_ count] == 0)
6323 return [[sections_ objectAtIndex:section] count];
6326 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6327 @synchronized (database_) {
6328 if ([database_ era] != era_)
6331 Section *section([sections_ objectAtIndex:[path section]]);
6332 NSInteger row([path row]);
6333 Package *package([packages_ objectAtIndex:([section row] + row)]);
6334 return [[package retain] autorelease];
6337 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6338 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6340 cell = [[[PackageCell alloc] init] autorelease];
6341 [cell setPackage:[self packageAtIndexPath:path]];
6345 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6346 Package *package([self packageAtIndexPath:path]);
6347 package = [database_ packageWithName:[package id]];
6348 [self didSelectPackage:package];
6351 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6352 // XXX: is 20 the most optimal number here?
6353 return [packages_ count] > 20 ? index_ : nil;
6356 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6357 #if TryIndexedCollation
6358 if ([[self class] hasIndexedCollation]) {
6359 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6366 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6367 if ((self = [super init]) != nil) {
6368 database_ = database;
6369 title_ = [title copy];
6370 [[self navigationItem] setTitle:title_];
6372 #if TryIndexedCollation
6373 if ([[self class] hasIndexedCollation])
6374 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6377 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6379 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6381 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6382 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6384 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6385 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6386 [list_ setRowHeight:73];
6387 [[self view] addSubview:list_];
6389 [list_ setDataSource:self];
6390 [list_ setDelegate:self];
6394 - (void) setDelegate:(id)delegate {
6395 delegate_ = delegate;
6398 - (bool) hasPackage:(Package *)package {
6402 - (void) reloadData {
6405 era_ = [database_ era];
6406 NSArray *packages = [database_ packages];
6408 [packages_ removeAllObjects];
6409 [sections_ removeAllObjects];
6411 _profile(PackageTable$reloadData$Filter)
6412 for (Package *package in packages)
6413 if ([self hasPackage:package])
6414 [packages_ addObject:package];
6417 [indices_ removeAllObjects];
6419 Section *section = nil;
6421 #if TryIndexedCollation
6422 if ([[self class] hasIndexedCollation]) {
6423 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6424 NSArray *titles = [collation sectionIndexTitles];
6427 _profile(PackageTable$reloadData$Section)
6428 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6432 _profile(PackageTable$reloadData$Section$Package)
6433 package = [packages_ objectAtIndex:offset];
6434 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6437 while (secidx < index) {
6440 _profile(PackageTable$reloadData$Section$Allocate)
6441 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6444 _profile(PackageTable$reloadData$Section$Add)
6445 [sections_ addObject:section];
6449 [section addToCount];
6455 [index_ removeAllObjects];
6457 _profile(PackageTable$reloadData$Section)
6458 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6462 _profile(PackageTable$reloadData$Section$Package)
6463 package = [packages_ objectAtIndex:offset];
6464 index = [package index];
6467 if (section == nil || [section index] != index) {
6468 _profile(PackageTable$reloadData$Section$Allocate)
6469 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6472 [index_ addObject:[section name]];
6473 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6475 _profile(PackageTable$reloadData$Section$Add)
6476 [sections_ addObject:section];
6480 [section addToCount];
6485 _profile(PackageTable$reloadData$List)
6490 - (void) resetCursor {
6491 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6496 /* Filtered Package List Controller {{{ */
6497 @interface FilteredPackageListController : PackageListController {
6503 - (void) setObject:(id)object;
6504 - (void) setObject:(id)object forFilter:(SEL)filter;
6506 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6510 @implementation FilteredPackageListController
6518 - (void) setFilter:(SEL)filter {
6521 /* XXX: this is an unsafe optimization of doomy hell */
6522 Method method(class_getInstanceMethod([Package class], filter));
6523 _assert(method != NULL);
6524 imp_ = method_getImplementation(method);
6525 _assert(imp_ != NULL);
6528 - (void) setObject:(id)object {
6534 object_ = [object retain];
6537 - (void) setObject:(id)object forFilter:(SEL)filter {
6538 [self setFilter:filter];
6539 [self setObject:object];
6542 - (bool) hasPackage:(Package *)package {
6543 _profile(FilteredPackageTable$hasPackage)
6544 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6548 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6549 if ((self = [super initWithDatabase:database title:title]) != nil) {
6550 [self setFilter:filter];
6551 [self setObject:object];
6558 /* Home Controller {{{ */
6559 @interface HomeController : CYBrowserController {
6564 @implementation HomeController
6567 if ((self = [super init]) != nil) {
6568 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6572 - (NSURL *) navigationURL {
6573 return [NSURL URLWithString:@"cydia://home"];
6576 - (void) aboutButtonClicked {
6577 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6579 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6580 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6581 [alert setCancelButtonIndex:0];
6584 @"Copyright (C) 2008-2011\n"
6585 "Jay Freeman (saurik)\n"
6586 "saurik@saurik.com\n"
6587 "http://www.saurik.com/"
6593 - (void) viewDidLoad {
6594 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6595 initWithTitle:UCLocalize("ABOUT")
6596 style:UIBarButtonItemStylePlain
6598 action:@selector(aboutButtonClicked)
6604 /* Manage Controller {{{ */
6605 @interface ManageController : CYBrowserController {
6608 - (void) queueStatusDidChange;
6612 @implementation ManageController
6615 if ((self = [super init]) != nil) {
6616 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6620 - (NSURL *) navigationURL {
6621 return [NSURL URLWithString:@"cydia://manage"];
6624 - (void) viewDidLoad {
6625 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6626 initWithTitle:UCLocalize("SETTINGS")
6627 style:UIBarButtonItemStylePlain
6629 action:@selector(settingsButtonClicked)
6632 [self queueStatusDidChange];
6635 - (void) settingsButtonClicked {
6636 [delegate_ showSettings];
6640 - (void) queueButtonClicked {
6644 - (void) applyLoadingTitle {
6645 // Disable "Loading" title.
6648 - (void) applyRightButton {
6649 // Disable right button.
6653 - (void) queueStatusDidChange {
6655 if (!IsWildcat_ && Queuing_) {
6656 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6657 initWithTitle:UCLocalize("QUEUE")
6658 style:UIBarButtonItemStyleDone
6660 action:@selector(queueButtonClicked)
6663 [[self navigationItem] setRightBarButtonItem:nil];
6668 - (bool) isLoading {
6669 // Never show as loading.
6676 /* Refresh Bar {{{ */
6677 @interface RefreshBar : UINavigationBar {
6678 UIProgressIndicator *indicator_;
6679 UITextLabel *prompt_;
6680 UIProgressBar *progress_;
6681 UINavigationButton *cancel_;
6686 @implementation RefreshBar
6689 [indicator_ release];
6691 [progress_ release];
6696 - (void) positionViews {
6697 CGRect frame = [cancel_ frame];
6698 frame.size = [cancel_ sizeThatFits:frame.size];
6699 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6700 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6701 [cancel_ setFrame:frame];
6703 CGSize prgsize = {75, 100};
6705 [self frame].size.width - prgsize.width - 10,
6706 ([self frame].size.height - prgsize.height) / 2
6708 [progress_ setFrame:prgrect];
6710 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6711 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6712 CGRect indrect = {{indoffset, indoffset}, indsize};
6713 [indicator_ setFrame:indrect];
6715 CGSize prmsize = {215, indsize.height + 4};
6717 indoffset * 2 + indsize.width,
6718 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6720 [prompt_ setFrame:prmrect];
6723 - (void) setFrame:(CGRect)frame {
6724 [super setFrame:frame];
6725 [self positionViews];
6728 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6729 if ((self = [super initWithFrame:frame]) != nil) {
6730 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6732 [self setBarStyle:UIBarStyleBlack];
6734 UIBarStyle barstyle([self _barStyle:NO]);
6735 bool ugly(barstyle == UIBarStyleDefault);
6737 UIProgressIndicatorStyle style = ugly ?
6738 UIProgressIndicatorStyleMediumBrown :
6739 UIProgressIndicatorStyleMediumWhite;
6741 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6742 [indicator_ setStyle:style];
6743 [indicator_ startAnimation];
6744 [self addSubview:indicator_];
6746 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6747 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6748 [prompt_ setBackgroundColor:[UIColor clearColor]];
6749 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6750 [self addSubview:prompt_];
6752 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6753 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6754 [progress_ setStyle:0];
6755 [self addSubview:progress_];
6757 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6758 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6759 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6760 [cancel_ setBarStyle:barstyle];
6762 [self positionViews];
6766 - (void) setCancellable:(bool)cancellable {
6768 [self addSubview:cancel_];
6770 [cancel_ removeFromSuperview];
6774 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6775 [progress_ setProgress:0];
6779 [self setCancellable:NO];
6782 - (void) setPrompt:(NSString *)prompt {
6783 [prompt_ setText:prompt];
6786 - (void) setProgress:(float)progress {
6787 [progress_ setProgress:progress];
6793 @class CYNavigationController;
6795 /* Cydia Tab Bar Controller {{{ */
6796 @interface CYTabBarController : UITabBarController <
6797 UITabBarControllerDelegate,
6800 _transient Database *database_;
6801 RefreshBar *refreshbar_;
6805 // XXX: ok, "updatedelegate_"?...
6806 _transient NSObject<CydiaDelegate> *updatedelegate_;
6809 UIViewController *remembered_;
6810 _transient UIViewController *transient_;
6813 - (NSArray *) navigationURLCollection;
6814 - (void) dropBar:(BOOL)animated;
6815 - (void) beginUpdate;
6816 - (void) raiseBar:(BOOL)animated;
6821 @implementation CYTabBarController
6823 - (void) setUnselectedViewController:(UIViewController *)transient {
6824 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6825 if (transient != nil) {
6826 if (transient_ == nil)
6827 remembered_ = [[controllers objectAtIndex:0] retain];
6828 transient_ = transient;
6829 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6830 [controllers replaceObjectAtIndex:0 withObject:transient_];
6831 [self setSelectedIndex:0];
6832 [self setViewControllers:controllers];
6833 [self concealTabBarSelection];
6834 } else if (remembered_ != nil) {
6835 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6836 transient_ = transient;
6837 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6838 [remembered_ release];
6840 [self setViewControllers:controllers];
6841 [self revealTabBarSelection];
6845 - (UIViewController *) unselectedViewController {
6849 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6850 if ([self unselectedViewController])
6851 [self setUnselectedViewController:nil];
6854 - (NSArray *) navigationURLCollection {
6855 NSMutableArray *items([NSMutableArray array]);
6857 // XXX: Should this deal with transient view controllers?
6858 for (id navigation in [self viewControllers]) {
6859 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6861 [items addObject:stack];
6867 - (void) reloadData {
6868 for (CYViewController *controller in [self viewControllers])
6869 [controller reloadData];
6871 [(CYNavigationController *)[self unselectedViewController] reloadData];
6875 [refreshbar_ release];
6876 [[NSNotificationCenter defaultCenter] removeObserver:self];
6881 - (id) initWithDatabase:(Database *)database {
6882 if ((self = [super init]) != nil) {
6883 database_ = database;
6884 [self setDelegate:self];
6886 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6887 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6889 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6893 - (void) setUpdate:(NSDate *)date {
6897 - (void) beginUpdate {
6898 [refreshbar_ start];
6901 [updatedelegate_ retainNetworkActivityIndicator];
6905 detachNewThreadSelector:@selector(performUpdate)
6911 - (void) performUpdate { _pooled
6913 status.setDelegate(self);
6914 [database_ updateWithStatus:status];
6917 performSelectorOnMainThread:@selector(completeUpdate)
6923 - (void) stopUpdateWithSelector:(SEL)selector {
6925 [updatedelegate_ releaseNetworkActivityIndicator];
6927 [self raiseBar:YES];
6930 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6933 - (void) completeUpdate {
6936 [self stopUpdateWithSelector:@selector(reloadData)];
6939 - (void) cancelUpdate {
6940 [self stopUpdateWithSelector:@selector(updateData)];
6943 - (void) cancelPressed {
6944 [self cancelUpdate];
6951 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6952 [refreshbar_ setPrompt:[event compoundMessage]];
6955 - (bool) isProgressCancelled {
6959 - (void) setProgressCancellable:(NSNumber *)cancellable {
6960 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6963 - (void) setProgressPercent:(NSNumber *)percent {
6964 [refreshbar_ setProgress:[percent floatValue]];
6967 - (void) setProgressStatus:(NSDictionary *)status {
6969 [self setProgressPercent:[status objectForKey:@"Percent"]];
6972 - (void) setUpdateDelegate:(id)delegate {
6973 updatedelegate_ = delegate;
6976 - (CGFloat) statusBarHeight {
6977 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6978 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6980 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6984 - (UIView *) transitionView {
6985 if ([self respondsToSelector:@selector(_transitionView)])
6986 return [self _transitionView];
6988 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6991 - (void) dropBar:(BOOL)animated {
6996 UIView *transition([self transitionView]);
6997 [[self view] addSubview:refreshbar_];
6999 CGRect barframe([refreshbar_ frame]);
7001 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
7002 barframe.origin.y = [self statusBarHeight];
7004 barframe.origin.y = 0;
7006 [refreshbar_ setFrame:barframe];
7009 [UIView beginAnimations:nil context:NULL];
7011 CGRect viewframe = [transition frame];
7012 viewframe.origin.y += barframe.size.height;
7013 viewframe.size.height -= barframe.size.height;
7014 [transition setFrame:viewframe];
7017 [UIView commitAnimations];
7019 // Ensure bar has the proper width for our view, it might have changed
7020 barframe.size.width = viewframe.size.width;
7021 [refreshbar_ setFrame:barframe];
7023 // XXX: fix Apple's layout bug
7024 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7027 - (void) raiseBar:(BOOL)animated {
7032 UIView *transition([self transitionView]);
7033 [refreshbar_ removeFromSuperview];
7035 CGRect barframe([refreshbar_ frame]);
7038 [UIView beginAnimations:nil context:NULL];
7040 CGRect viewframe = [transition frame];
7041 viewframe.origin.y -= barframe.size.height;
7042 viewframe.size.height += barframe.size.height;
7043 [transition setFrame:viewframe];
7046 [UIView commitAnimations];
7048 // XXX: fix Apple's layout bug
7049 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7053 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7054 // XXX: fix Apple's layout bug
7055 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7059 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7060 bool dropped(dropped_);
7065 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7070 // XXX: fix Apple's layout bug
7071 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7074 - (void) statusBarFrameChanged:(NSNotification *)notification {
7083 /* Cydia Navigation Controller {{{ */
7084 @interface CYNavigationController : UINavigationController {
7085 _transient Database *database_;
7086 _transient id<UINavigationControllerDelegate> delegate_;
7089 - (NSArray *) navigationURLCollection;
7090 - (id) initWithDatabase:(Database *)database;
7091 - (void) reloadData;
7096 @implementation CYNavigationController
7098 - (NSArray *) navigationURLCollection {
7099 NSMutableArray *stack([NSMutableArray array]);
7101 for (CYViewController *controller in [self viewControllers]) {
7102 NSString *url = [[controller navigationURL] absoluteString];
7104 [stack addObject:url];
7110 - (void) reloadData {
7111 for (CYViewController *page in [self viewControllers]) {
7112 // Only reload controllers that have already loaded.
7113 // This prevents a page from accidentally loading too
7114 // early if it hasn't been shown on the screen yet.
7115 if ([page hasLoaded])
7120 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
7121 delegate_ = delegate;
7124 - (id) initWithDatabase:(Database *)database {
7125 if ((self = [super init]) != nil) {
7126 database_ = database;
7133 /* Cydia:// Protocol {{{ */
7134 @interface CydiaURLProtocol : NSURLProtocol {
7139 @implementation CydiaURLProtocol
7141 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7142 NSURL *url([request URL]);
7146 NSString *scheme([[url scheme] lowercaseString]);
7147 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7149 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7155 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7159 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7160 id<NSURLProtocolClient> client([self client]);
7162 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7164 NSData *data(UIImagePNGRepresentation(icon));
7166 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7167 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7168 [client URLProtocol:self didLoadData:data];
7169 [client URLProtocolDidFinishLoading:self];
7173 - (void) startLoading {
7174 id<NSURLProtocolClient> client([self client]);
7175 NSURLRequest *request([self request]);
7177 NSURL *url([request URL]);
7178 NSString *href([url absoluteString]);
7179 NSString *scheme([[url scheme] lowercaseString]);
7183 if ([scheme isEqualToString:@"cydia"])
7184 path = [href substringFromIndex:8];
7185 else if ([scheme isEqualToString:@"about"])
7186 path = [href substringFromIndex:12];
7187 else _assert(false);
7189 NSRange slash([path rangeOfString:@"/"]);
7192 if (slash.location == NSNotFound) {
7196 command = [path substringToIndex:slash.location];
7197 path = [path substringFromIndex:(slash.location + 1)];
7200 Database *database([Database sharedInstance]);
7202 if ([command isEqualToString:@"package-icon"]) {
7205 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7206 Package *package([database packageWithName:path]);
7209 UIImage *icon([package icon]);
7210 [self _returnPNGWithImage:icon forRequest:request];
7211 } else if ([command isEqualToString:@"source-icon"]) {
7214 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7215 NSString *source(Simplify(path));
7216 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7218 icon = [UIImage applicationImageNamed:@"unknown.png"];
7219 [self _returnPNGWithImage:icon forRequest:request];
7220 } else if ([command isEqualToString:@"uikit-image"]) {
7223 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7224 UIImage *icon(_UIImageWithName(path));
7225 [self _returnPNGWithImage:icon forRequest:request];
7226 } else if ([command isEqualToString:@"section-icon"]) {
7229 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7230 NSString *section(Simplify(path));
7231 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7233 icon = [UIImage applicationImageNamed:@"unknown.png"];
7234 [self _returnPNGWithImage:icon forRequest:request];
7236 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7240 - (void) stopLoading {
7246 /* Section Controller {{{ */
7247 @interface SectionController : FilteredPackageListController {
7248 _H<NSString> section_;
7251 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7255 @implementation SectionController
7257 - (NSURL *) navigationURL {
7258 NSString *name = section_;
7262 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7265 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7268 title = UCLocalize("ALL_PACKAGES");
7269 else if (![name isEqual:@""])
7270 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7272 title = UCLocalize("NO_SECTION");
7274 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7281 /* Sections Controller {{{ */
7282 @interface SectionsController : CYViewController <
7283 UITableViewDataSource,
7286 _transient Database *database_;
7287 NSMutableArray *sections_;
7288 NSMutableArray *filtered_;
7292 - (id) initWithDatabase:(Database *)database;
7293 - (void) editButtonClicked;
7297 @implementation SectionsController
7300 [self releaseSubviews];
7301 [sections_ release];
7302 [filtered_ release];
7307 - (NSURL *) navigationURL {
7308 return [NSURL URLWithString:@"cydia://sections"];
7311 - (void) updateNavigationItem {
7312 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7313 if ([sections_ count] == 0) {
7314 [[self navigationItem] setRightBarButtonItem:nil];
7316 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7317 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7319 action:@selector(editButtonClicked)
7320 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7324 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7325 [super setEditing:editing animated:animated];
7330 [delegate_ updateData];
7332 [self updateNavigationItem];
7335 - (void) viewDidAppear:(BOOL)animated {
7336 [super viewDidAppear:animated];
7337 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7340 - (void) viewWillDisappear:(BOOL)animated {
7341 [super viewWillDisappear:animated];
7342 if ([self isEditing]) [self setEditing:NO];
7345 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7346 Section *section = nil;
7347 int index = [indexPath row];
7348 if (![self isEditing]) {
7351 section = [filtered_ objectAtIndex:index];
7353 section = [sections_ objectAtIndex:index];
7358 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7359 if ([self isEditing])
7360 return [sections_ count];
7362 return [filtered_ count] + 1;
7365 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7369 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7370 static NSString *reuseIdentifier = @"SectionCell";
7372 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7374 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7376 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7381 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7382 if ([self isEditing])
7385 Section *section = [self sectionAtIndexPath:indexPath];
7387 SectionController *controller = [[[SectionController alloc]
7388 initWithDatabase:database_
7389 section:[section name]
7391 [controller setDelegate:delegate_];
7393 [[self navigationController] pushViewController:controller animated:YES];
7397 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7399 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7400 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7401 [list_ setRowHeight:45.0f];
7402 [list_ setDataSource:self];
7403 [list_ setDelegate:self];
7404 [[self view] addSubview:list_];
7407 - (void) viewDidLoad {
7408 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7411 - (void) releaseSubviews {
7416 - (id) initWithDatabase:(Database *)database {
7417 if ((self = [super init]) != nil) {
7418 database_ = database;
7420 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7421 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7425 - (void) reloadData {
7428 NSArray *packages = [database_ packages];
7430 [sections_ removeAllObjects];
7431 [filtered_ removeAllObjects];
7433 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7436 for (Package *package in packages) {
7437 NSString *name([package section]);
7438 NSString *key(name == nil ? @"" : name);
7442 _profile(SectionsView$reloadData$Section)
7443 section = [sections objectForKey:key];
7444 if (section == nil) {
7445 _profile(SectionsView$reloadData$Section$Allocate)
7446 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7447 [sections setObject:section forKey:key];
7452 [section addToCount];
7454 _profile(SectionsView$reloadData$Filter)
7455 if (![package valid] || ![package visible])
7463 [sections_ addObjectsFromArray:[sections allValues]];
7465 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7467 for (Section *section in sections_) {
7468 size_t count([section row]);
7472 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7473 [section setCount:count];
7474 [filtered_ addObject:section];
7477 [self updateNavigationItem];
7482 - (void) editButtonClicked {
7483 [self setEditing:![self isEditing] animated:YES];
7489 /* Changes Controller {{{ */
7490 @interface ChangesController : CYViewController <
7491 UITableViewDataSource,
7494 _transient Database *database_;
7496 CFMutableArrayRef packages_;
7497 NSMutableArray *sections_;
7500 BOOL hasSentFirstLoad_;
7503 - (id) initWithDatabase:(Database *)database;
7507 @implementation ChangesController
7510 [self releaseSubviews];
7511 CFRelease(packages_);
7512 [sections_ release];
7517 - (NSURL *) navigationURL {
7518 return [NSURL URLWithString:@"cydia://changes"];
7521 - (void) viewWillAppear:(BOOL)animated {
7522 // Loads after it appears, so don't load beforehand.
7524 [super viewWillAppear:animated];
7527 - (void) viewDidAppear:(BOOL)animated {
7528 [super viewDidAppear:animated];
7530 if (!hasSentFirstLoad_) {
7531 hasSentFirstLoad_ = YES;
7532 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7534 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7538 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7539 NSInteger count([sections_ count]);
7540 return count == 0 ? 1 : count;
7543 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7544 if ([sections_ count] == 0)
7546 return [[sections_ objectAtIndex:section] name];
7549 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7550 if ([sections_ count] == 0)
7552 return [[sections_ objectAtIndex:section] count];
7555 - (Package *) packageAtIndex:(NSUInteger)index {
7556 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7559 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7560 @synchronized (database_) {
7561 if ([database_ era] != era_)
7564 NSUInteger sectionIndex([path section]);
7565 if (sectionIndex >= [sections_ count])
7567 Section *section([sections_ objectAtIndex:sectionIndex]);
7568 NSInteger row([path row]);
7569 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7572 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7573 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7575 cell = [[[PackageCell alloc] init] autorelease];
7576 [cell setPackage:[self packageAtIndexPath:path]];
7580 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7581 Package *package([self packageAtIndexPath:path]);
7582 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7583 [view setDelegate:delegate_];
7584 [[self navigationController] pushViewController:view animated:YES];
7588 - (void) refreshButtonClicked {
7589 [delegate_ beginUpdate];
7590 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7593 - (void) upgradeButtonClicked {
7594 [delegate_ distUpgrade];
7598 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7600 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7601 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7602 [list_ setRowHeight:73];
7603 [list_ setDataSource:self];
7604 [list_ setDelegate:self];
7605 [[self view] addSubview:list_];
7608 - (void) viewDidLoad {
7609 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7612 - (void) releaseSubviews {
7617 - (id) initWithDatabase:(Database *)database {
7618 if ((self = [super init]) != nil) {
7619 database_ = database;
7621 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7622 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7626 // this mostly works because reloadData (below) is @synchronized (database_)
7627 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7628 - (void) _reloadPackages:(NSArray *)packages {
7629 CFRelease(packages_);
7630 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7633 _profile(ChangesController$_reloadPackages$Filter)
7634 for (Package *package in packages)
7635 if ([package upgradableAndEssential:YES] || [package visible])
7636 CFArrayAppendValue(packages_, package);
7639 _profile(ChangesController$_reloadPackages$radixSort)
7640 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7645 - (void) reloadData {
7646 @synchronized (database_) {
7647 era_ = [database_ era];
7648 NSArray *packages = [database_ packages];
7650 [sections_ removeAllObjects];
7653 UIProgressHUD *hud([delegate_ addProgressHUD]);
7654 [hud setText:UCLocalize("LOADING")];
7655 //NSLog(@"HUD:%@::%@", delegate_, hud);
7656 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7657 [delegate_ removeProgressHUD:hud];
7659 [self _reloadPackages:packages];
7662 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7663 Section *ignored = nil;
7664 Section *section = nil;
7668 bool unseens = false;
7670 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7672 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7673 Package *package = [self packageAtIndex:offset];
7675 BOOL uae = [package upgradableAndEssential:YES];
7679 time_t seen([package seen]);
7681 if (section == nil || last != seen) {
7685 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7688 _profile(ChangesController$reloadData$Allocate)
7689 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7690 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7691 [sections_ addObject:section];
7695 [section addToCount];
7696 } else if ([package ignored]) {
7697 if (ignored == nil) {
7698 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7700 [ignored addToCount];
7703 [upgradable addToCount];
7708 CFRelease(formatter);
7711 Section *last = [sections_ lastObject];
7712 size_t count = [last count];
7713 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7714 [sections_ removeLastObject];
7717 if ([ignored count] != 0)
7718 [sections_ insertObject:ignored atIndex:0];
7720 [sections_ insertObject:upgradable atIndex:0];
7725 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7726 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7727 style:UIBarButtonItemStylePlain
7729 action:@selector(upgradeButtonClicked)
7732 if (![delegate_ updating])
7733 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7734 initWithTitle:UCLocalize("REFRESH")
7735 style:UIBarButtonItemStylePlain
7737 action:@selector(refreshButtonClicked)
7745 /* Search Controller {{{ */
7746 @interface SearchController : FilteredPackageListController <
7749 _H<UISearchBar> search_;
7753 - (id) initWithDatabase:(Database *)database;
7754 - (void) setSearchTerm:(NSString *)term;
7755 - (void) reloadData;
7759 @implementation SearchController
7762 [search_ setDelegate:nil];
7766 - (NSURL *) navigationURL {
7767 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7768 return [NSURL URLWithString:@"cydia://search"];
7770 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7773 - (void) setSearchTerm:(NSString *)searchTerm {
7774 [search_ setText:searchTerm];
7778 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7779 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7780 [search_ resignFirstResponder];
7784 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7785 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7789 - (id) initWithDatabase:(Database *)database {
7790 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7791 search_ = [[[UISearchBar alloc] init] autorelease];
7792 [search_ setDelegate:self];
7796 - (void) viewDidAppear:(BOOL)animated {
7797 [super viewDidAppear:animated];
7799 if (!searchloaded_) {
7800 searchloaded_ = YES;
7801 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7802 [search_ layoutSubviews];
7803 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7805 UITextField *textField;
7806 if ([search_ respondsToSelector:@selector(searchField)])
7807 textField = [search_ searchField];
7809 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7811 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7812 [textField setEnablesReturnKeyAutomatically:NO];
7813 [[self navigationItem] setTitleView:textField];
7817 - (void) reloadData {
7818 [self setObject:[search_ text]];
7823 - (void) didSelectPackage:(Package *)package {
7824 [search_ resignFirstResponder];
7825 [super didSelectPackage:package];
7830 /* Package Settings Controller {{{ */
7831 @interface PackageSettingsController : CYViewController <
7832 UITableViewDataSource,
7835 _transient Database *database_;
7838 UITableView *table_;
7839 UISwitch *subscribedSwitch_;
7840 UISwitch *ignoredSwitch_;
7841 UITableViewCell *subscribedCell_;
7842 UITableViewCell *ignoredCell_;
7845 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7849 @implementation PackageSettingsController
7852 [self releaseSubviews];
7859 - (NSURL *) navigationURL {
7860 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7863 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7864 if (package_ == nil)
7867 if ([package_ installed] == nil)
7873 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7874 if (package_ == nil)
7877 // both sections contain just one item right now.
7881 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7885 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7887 return UCLocalize("SHOW_ALL_CHANGES_EX");
7889 return UCLocalize("IGNORE_UPGRADES_EX");
7892 - (void) onSubscribed:(id)control {
7893 bool value([control isOn]);
7894 if (package_ == nil)
7896 if ([package_ setSubscribed:value])
7897 [delegate_ updateData];
7900 - (void) _updateIgnored {
7901 const char *package([name_ UTF8String]);
7902 bool on([ignoredSwitch_ isOn]);
7904 pid_t pid(ExecFork());
7906 FILE *dpkg(popen("dpkg --set-selections", "w"));
7907 fwrite(package, strlen(package), 1, dpkg);
7910 fwrite(" hold\n", 6, 1, dpkg);
7912 fwrite(" install\n", 9, 1, dpkg);
7922 int result(waitpid(pid, &status, 0));
7925 _assert(result == pid);
7931 - (void) onIgnored:(id)control {
7932 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7933 [invocation setTarget:self];
7934 [invocation setSelector:@selector(_updateIgnored)];
7936 [delegate_ reloadDataWithInvocation:invocation];
7939 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7940 if (package_ == nil)
7943 switch ([indexPath section]) {
7944 case 0: return subscribedCell_;
7945 case 1: return ignoredCell_;
7954 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7956 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7957 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7958 [table_ setDataSource:self];
7959 [table_ setDelegate:self];
7960 [[self view] addSubview:table_];
7962 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7963 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7964 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7966 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7967 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7968 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7970 subscribedCell_ = [[UITableViewCell alloc] init];
7971 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7972 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7973 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7975 ignoredCell_ = [[UITableViewCell alloc] init];
7976 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7977 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7978 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7981 - (void) viewDidLoad {
7982 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7985 - (void) releaseSubviews {
7986 [ignoredCell_ release];
7989 [subscribedCell_ release];
7990 subscribedCell_ = nil;
7995 [ignoredSwitch_ release];
7996 ignoredSwitch_ = nil;
7998 [subscribedSwitch_ release];
7999 subscribedSwitch_ = nil;
8002 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8003 if ((self = [super init]) != nil) {
8004 database_ = database;
8005 name_ = [package retain];
8009 - (void) reloadData {
8012 if (package_ != nil)
8013 [package_ autorelease];
8014 package_ = [database_ packageWithName:name_];
8016 if (package_ != nil) {
8017 package_ = [package_ retain];
8018 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8019 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8020 } // XXX: what now, G?
8022 [table_ reloadData];
8028 /* Installed Controller {{{ */
8029 @interface InstalledController : FilteredPackageListController {
8033 - (id) initWithDatabase:(Database *)database;
8035 - (void) updateRoleButton;
8036 - (void) queueStatusDidChange;
8040 @implementation InstalledController
8046 - (NSURL *) navigationURL {
8047 return [NSURL URLWithString:@"cydia://installed"];
8050 - (id) initWithDatabase:(Database *)database {
8051 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8052 [self updateRoleButton];
8053 [self queueStatusDidChange];
8058 - (void) queueButtonClicked {
8063 - (void) queueStatusDidChange {
8067 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8068 initWithTitle:UCLocalize("QUEUE")
8069 style:UIBarButtonItemStyleDone
8071 action:@selector(queueButtonClicked)
8074 [[self navigationItem] setLeftBarButtonItem:nil];
8080 - (void) updateRoleButton {
8081 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8082 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8083 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8084 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8086 action:@selector(roleButtonClicked)
8090 - (void) roleButtonClicked {
8091 [self setObject:[NSNumber numberWithBool:expert_]];
8095 [self updateRoleButton];
8101 /* Source Cell {{{ */
8102 @interface SourceCell : CYTableViewCell <
8110 - (void) setSource:(Source *)source;
8114 @implementation SourceCell
8116 - (void) clearSource {
8126 - (void) setSource:(Source *)source {
8130 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
8132 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8133 icon_ = [icon_ retain];
8135 origin_ = [[source name] retain];
8136 label_ = [[source uri] retain];
8138 [content_ setNeedsDisplay];
8146 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8147 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8148 UIView *content([self contentView]);
8149 CGRect bounds([content bounds]);
8151 content_ = [[ContentView alloc] initWithFrame:bounds];
8152 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8153 [content_ setBackgroundColor:[UIColor whiteColor]];
8154 [content addSubview:content_];
8156 [content_ setDelegate:self];
8157 [content_ setOpaque:YES];
8161 - (NSString *) accessibilityLabel {
8165 - (void) drawContentRect:(CGRect)rect {
8166 bool highlighted(highlighted_);
8167 float width(rect.size.width);
8170 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8177 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8181 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8186 /* Source Controller {{{ */
8187 @interface SourceController : FilteredPackageListController {
8188 _transient Source *source_;
8192 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8196 @implementation SourceController
8198 - (NSURL *) navigationURL {
8199 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8202 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8203 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8205 key_ = [[source key] retain];
8209 - (void) reloadData {
8210 source_ = [database_ sourceWithKey:key_];
8212 key_ = [[source_ key] retain];
8213 [self setObject:source_];
8214 [[self navigationItem] setTitle:[source_ label]];
8221 /* Sources Controller {{{ */
8222 @interface SourcesController : CYViewController <
8223 UITableViewDataSource,
8226 _transient Database *database_;
8228 NSMutableArray *sources_;
8232 UIProgressHUD *hud_;
8235 //NSURLConnection *installer_;
8236 NSURLConnection *trivial_;
8237 NSURLConnection *trivial_bz2_;
8238 NSURLConnection *trivial_gz_;
8239 //NSURLConnection *automatic_;
8244 - (id) initWithDatabase:(Database *)database;
8245 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8249 @implementation SourcesController
8251 - (void) _releaseConnection:(NSURLConnection *)connection {
8252 if (connection != nil) {
8253 [connection cancel];
8254 //[connection setDelegate:nil];
8255 [connection release];
8260 [self releaseSubviews];
8266 //[self _releaseConnection:installer_];
8267 [self _releaseConnection:trivial_];
8268 [self _releaseConnection:trivial_gz_];
8269 [self _releaseConnection:trivial_bz2_];
8270 //[self _releaseConnection:automatic_];
8276 - (NSURL *) navigationURL {
8277 return [NSURL URLWithString:@"cydia://sources"];
8280 - (void) viewDidAppear:(BOOL)animated {
8281 [super viewDidAppear:animated];
8282 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8285 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8286 return offset_ == 0 ? 1 : 2;
8289 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8290 switch (section + (offset_ == 0 ? 1 : 0)) {
8291 case 0: return UCLocalize("ENTERED_BY_USER");
8292 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8298 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8299 int count = [sources_ count];
8301 case 0: return (offset_ == 0 ? count : offset_);
8302 case 1: return count - offset_;
8308 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8310 switch (indexPath.section) {
8311 case 0: idx = indexPath.row; break;
8312 case 1: idx = indexPath.row + offset_; break;
8316 return [sources_ objectAtIndex:idx];
8319 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8320 static NSString *cellIdentifier = @"SourceCell";
8322 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8323 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8324 [cell setSource:[self sourceAtIndexPath:indexPath]];
8325 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8330 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8331 Source *source = [self sourceAtIndexPath:indexPath];
8333 SourceController *controller = [[[SourceController alloc]
8334 initWithDatabase:database_
8338 [controller setDelegate:delegate_];
8340 [[self navigationController] pushViewController:controller animated:YES];
8343 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8344 Source *source = [self sourceAtIndexPath:indexPath];
8345 return [source record] != nil;
8348 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8349 Source *source = [self sourceAtIndexPath:indexPath];
8350 [Sources_ removeObjectForKey:[source key]];
8351 [delegate_ syncData];
8355 [delegate_ addTrivialSource:href_];
8356 [delegate_ syncData];
8359 - (NSString *) getWarning {
8360 NSString *href(href_);
8361 NSRange colon([href rangeOfString:@"://"]);
8362 if (colon.location != NSNotFound)
8363 href = [href substringFromIndex:(colon.location + 3)];
8364 href = [href stringByAddingPercentEscapes];
8365 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8366 href = [href stringByCachingURLWithCurrentCDN];
8368 NSURL *url([NSURL URLWithString:href]);
8370 NSStringEncoding encoding;
8371 NSError *error(nil);
8373 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8374 return [warning length] == 0 ? nil : warning;
8378 - (void) _endConnection:(NSURLConnection *)connection {
8379 // XXX: the memory management in this method is horribly awkward
8381 NSURLConnection **field = NULL;
8382 if (connection == trivial_)
8384 else if (connection == trivial_bz2_)
8385 field = &trivial_bz2_;
8386 else if (connection == trivial_gz_)
8387 field = &trivial_gz_;
8388 _assert(field != NULL);
8389 [connection release];
8394 trivial_bz2_ == nil &&
8400 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8403 UIAlertView *alert = [[[UIAlertView alloc]
8404 initWithTitle:UCLocalize("SOURCE_WARNING")
8407 cancelButtonTitle:UCLocalize("CANCEL")
8409 UCLocalize("ADD_ANYWAY"),
8413 [alert setContext:@"warning"];
8414 [alert setNumberOfRows:1];
8418 } else if (error_ != nil) {
8419 UIAlertView *alert = [[[UIAlertView alloc]
8420 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8421 message:[error_ localizedDescription]
8423 cancelButtonTitle:UCLocalize("OK")
8424 otherButtonTitles:nil
8427 [alert setContext:@"urlerror"];
8430 UIAlertView *alert = [[[UIAlertView alloc]
8431 initWithTitle:UCLocalize("NOT_REPOSITORY")
8432 message:UCLocalize("NOT_REPOSITORY_EX")
8434 cancelButtonTitle:UCLocalize("OK")
8435 otherButtonTitles:nil
8438 [alert setContext:@"trivial"];
8442 [delegate_ releaseNetworkActivityIndicator];
8444 [delegate_ removeProgressHUD:hud_];
8453 if (error_ != nil) {
8460 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8461 switch ([response statusCode]) {
8467 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8468 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8470 error_ = [error retain];
8471 [self _endConnection:connection];
8474 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8475 [self _endConnection:connection];
8478 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8479 NSMutableURLRequest *request = [NSMutableURLRequest
8480 requestWithURL:[NSURL URLWithString:href]
8481 cachePolicy:NSURLRequestUseProtocolCachePolicy
8482 timeoutInterval:120.0
8485 [request setHTTPMethod:method];
8487 if (Machine_ != NULL)
8488 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8489 if (UniqueID_ != nil)
8490 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8492 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8495 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8496 NSString *context([alert context]);
8498 if ([context isEqualToString:@"source"]) {
8501 NSString *href = [[alert textField] text];
8503 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8505 if (![href hasSuffix:@"/"])
8506 href_ = [href stringByAppendingString:@"/"];
8509 href_ = [href_ retain];
8511 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8512 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8513 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8514 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8518 // XXX: this is stupid
8519 hud_ = [[delegate_ addProgressHUD] retain];
8520 [hud_ setText:UCLocalize("VERIFYING_URL")];
8521 [delegate_ retainNetworkActivityIndicator];
8530 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8531 } else if ([context isEqualToString:@"trivial"])
8532 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8533 else if ([context isEqualToString:@"urlerror"])
8534 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8535 else if ([context isEqualToString:@"warning"]) {
8550 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8555 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8557 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8558 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8559 [list_ setRowHeight:56];
8560 [list_ setDataSource:self];
8561 [list_ setDelegate:self];
8562 [[self view] addSubview:list_];
8565 - (void) viewDidLoad {
8566 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8567 [self updateButtonsForEditingStatus:NO animated:NO];
8570 - (void) releaseSubviews {
8575 - (id) initWithDatabase:(Database *)database {
8576 if ((self = [super init]) != nil) {
8577 database_ = database;
8578 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8582 - (void) reloadData {
8586 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8589 [sources_ removeAllObjects];
8590 [sources_ addObjectsFromArray:[database_ sources]];
8592 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8595 int count([sources_ count]);
8597 for (int i = 0; i != count; i++) {
8598 if ([[sources_ objectAtIndex:i] record] == nil)
8603 [list_ setEditing:NO];
8604 [self updateButtonsForEditingStatus:NO animated:NO];
8608 - (void) showAddSourcePrompt {
8609 UIAlertView *alert = [[[UIAlertView alloc]
8610 initWithTitle:UCLocalize("ENTER_APT_URL")
8613 cancelButtonTitle:UCLocalize("CANCEL")
8615 UCLocalize("ADD_SOURCE"),
8619 [alert setContext:@"source"];
8620 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8622 [alert setNumberOfRows:1];
8623 [alert addTextFieldWithValue:@"http://" label:@""];
8625 UITextInputTraits *traits = [[alert textField] textInputTraits];
8626 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8627 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8628 [traits setKeyboardType:UIKeyboardTypeURL];
8629 // XXX: UIReturnKeyDone
8630 [traits setReturnKeyType:UIReturnKeyNext];
8635 - (void) addButtonClicked {
8636 [self showAddSourcePrompt];
8639 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8640 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8641 initWithTitle:UCLocalize("ADD")
8642 style:UIBarButtonItemStylePlain
8644 action:@selector(addButtonClicked)
8645 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8647 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8648 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8649 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8651 action:@selector(editButtonClicked)
8652 ] autorelease] animated:animated];
8654 if (IsWildcat_ && !editing)
8655 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8656 initWithTitle:UCLocalize("SETTINGS")
8657 style:UIBarButtonItemStylePlain
8659 action:@selector(settingsButtonClicked)
8663 - (void) settingsButtonClicked {
8664 [delegate_ showSettings];
8667 - (void) editButtonClicked {
8668 [list_ setEditing:![list_ isEditing] animated:YES];
8670 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8676 /* Settings Controller {{{ */
8677 @interface SettingsController : CYViewController <
8678 UITableViewDataSource,
8681 _transient Database *database_;
8682 // XXX: ok, "roledelegate_"?...
8683 _transient id roledelegate_;
8684 UITableView *table_;
8685 UISegmentedControl *segment_;
8689 - (void) showDoneButton;
8690 - (void) resizeSegmentedControl;
8694 @implementation SettingsController
8697 [self releaseSubviews];
8703 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8705 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8706 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8707 [table_ setDelegate:self];
8708 [table_ setDataSource:self];
8709 [[self view] addSubview:table_];
8711 NSArray *items = [NSArray arrayWithObjects:
8713 UCLocalize("HACKER"),
8714 UCLocalize("DEVELOPER"),
8716 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8717 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8718 [container_ addSubview:segment_];
8721 - (void) viewDidLoad {
8722 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8725 if ([Role_ isEqualToString:@"User"]) index = 0;
8726 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8727 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8729 [segment_ setSelectedSegmentIndex:index];
8730 [self showDoneButton];
8733 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8734 [self resizeSegmentedControl];
8737 - (void) releaseSubviews {
8744 [container_ release];
8748 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8749 if ((self = [super init]) != nil) {
8750 database_ = database;
8751 roledelegate_ = delegate;
8755 - (void) resizeSegmentedControl {
8756 CGFloat width = [[self view] frame].size.width;
8757 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8760 - (void) viewWillAppear:(BOOL)animated {
8761 [super viewWillAppear:animated];
8763 [self resizeSegmentedControl];
8766 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8767 [self resizeSegmentedControl];
8770 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8771 [self resizeSegmentedControl];
8775 NSString *role(nil);
8777 switch ([segment_ selectedSegmentIndex]) {
8778 case 0: role = @"User"; break;
8779 case 1: role = @"Hacker"; break;
8780 case 2: role = @"Developer"; break;
8785 if (![role isEqualToString:Role_]) {
8786 bool rolling(Role_ == nil);
8789 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8793 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8797 [roledelegate_ loadData];
8799 [roledelegate_ updateData];
8803 - (void) segmentChanged:(UISegmentedControl *)control {
8804 [self showDoneButton];
8807 - (void) saveAndClose {
8810 [[self navigationItem] setRightBarButtonItem:nil];
8811 [[self navigationController] dismissModalViewControllerAnimated:YES];
8814 - (void) doneButtonClicked {
8815 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8816 [spinner startAnimating];
8817 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8818 [[self navigationItem] setRightBarButtonItem:spinItem];
8820 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8823 - (void) showDoneButton {
8824 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8825 initWithTitle:UCLocalize("DONE")
8826 style:UIBarButtonItemStyleDone
8828 action:@selector(doneButtonClicked)
8829 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8832 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8833 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8837 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8841 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8842 return nil; // This method is required by the protocol.
8845 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8847 return UCLocalize("ROLE_EX");
8849 return [NSString stringWithFormat:
8850 @"%@: %@\n%@: %@\n%@: %@",
8851 UCLocalize("USER"), UCLocalize("USER_EX"),
8852 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8853 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8858 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8859 return section == 3 ? 44.0f : 0;
8862 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8863 return section == 3 ? container_ : nil;
8866 - (void) reloadData {
8868 [table_ reloadData];
8873 /* Stash Controller {{{ */
8874 @interface StashController : CYViewController {
8875 UIActivityIndicatorView *spinner_;
8882 @implementation StashController
8885 [self releaseSubviews];
8891 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8892 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8894 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8895 CGRect spinrect = [spinner_ frame];
8896 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8897 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8898 [spinner_ setFrame:spinrect];
8899 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8900 [[self view] addSubview:spinner_];
8901 [spinner_ startAnimating];
8904 captrect.size.width = [[self view] frame].size.width;
8905 captrect.size.height = 40.0f;
8906 captrect.origin.x = 0;
8907 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8908 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8909 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8910 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8911 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8912 [caption_ setTextColor:[UIColor whiteColor]];
8913 [caption_ setBackgroundColor:[UIColor clearColor]];
8914 [caption_ setShadowColor:[UIColor blackColor]];
8915 [caption_ setTextAlignment:UITextAlignmentCenter];
8916 [[self view] addSubview:caption_];
8919 statusrect.size.width = [[self view] frame].size.width;
8920 statusrect.size.height = 30.0f;
8921 statusrect.origin.x = 0;
8922 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8923 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8924 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8925 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8926 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8927 [status_ setTextColor:[UIColor whiteColor]];
8928 [status_ setBackgroundColor:[UIColor clearColor]];
8929 [status_ setShadowColor:[UIColor blackColor]];
8930 [status_ setTextAlignment:UITextAlignmentCenter];
8931 [[self view] addSubview:status_];
8934 - (void) releaseSubviews {
8948 @interface Cydia : UIApplication <
8949 ConfirmationControllerDelegate,
8952 UINavigationControllerDelegate,
8953 UITabBarControllerDelegate
8955 // XXX: evaluate all fields for _transient
8958 CYTabBarController *tabbar_;
8959 CYEmulatedLoadingController *emulated_;
8961 NSMutableArray *essential_;
8962 NSMutableArray *broken_;
8964 Database *database_;
8971 StashController *stash_;
8980 @implementation Cydia
8982 - (void) beginUpdate {
8983 [tabbar_ beginUpdate];
8987 return [tabbar_ updating];
8991 if ([broken_ count] != 0) {
8992 int count = [broken_ count];
8994 UIAlertView *alert = [[[UIAlertView alloc]
8995 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8996 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8998 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
9000 UCLocalize("TEMPORARY_IGNORE"),
9004 [alert setContext:@"fixhalf"];
9005 [alert setNumberOfRows:2];
9007 } else if (!Ignored_ && [essential_ count] != 0) {
9008 int count = [essential_ count];
9010 UIAlertView *alert = [[[UIAlertView alloc]
9011 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9012 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9014 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9016 UCLocalize("UPGRADE_ESSENTIAL"),
9017 UCLocalize("COMPLETE_UPGRADE"),
9021 [alert setContext:@"upgrade"];
9026 - (void) _saveConfig {
9032 NSString *error(nil);
9034 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9036 NSError *error(nil);
9037 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9038 NSLog(@"failure to save metadata data: %@", error);
9043 NSLog(@"failure to serialize metadata: %@", error);
9048 // Navigation controller for the queuing badge.
9049 - (CYNavigationController *) queueNavigationController {
9050 NSArray *controllers = [tabbar_ viewControllers];
9051 return [controllers objectAtIndex:3];
9054 - (void) _updateData {
9057 [tabbar_ reloadData];
9059 CYNavigationController *navigation = [self queueNavigationController];
9061 id queuedelegate = nil;
9062 if ([[navigation viewControllers] count] > 0)
9063 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9065 [queuedelegate queueStatusDidChange];
9066 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9069 - (void) _refreshIfPossible:(NSDate *)update {
9070 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9072 bool recently = false;
9073 if (update != nil) {
9074 NSTimeInterval interval([update timeIntervalSinceNow]);
9075 if (interval <= 0 && interval > -(15*60))
9079 // Don't automatic refresh if:
9080 // - We already refreshed recently.
9081 // - We already auto-refreshed this launch.
9082 // - Auto-refresh is disabled.
9083 if (recently || loaded_ || ManualRefresh) {
9084 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9086 // If we are cancelling, we need to make sure it knows it's already loaded.
9090 // We are going to load, so remember that.
9094 SCNetworkReachabilityFlags flags; {
9095 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9096 SCNetworkReachabilityGetFlags(reachability, &flags);
9097 CFRelease(reachability);
9100 // XXX: this elaborate mess is what Apple is using to determine this? :(
9101 // XXX: do we care if the user has to intervene? maybe that's ok?
9103 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9104 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9105 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9106 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9107 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9108 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9112 // If we can reach the server, auto-refresh!
9114 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9119 - (void) refreshIfPossible {
9120 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9123 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
9124 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9125 [hud setText:UCLocalize("RELOADING_DATA")];
9127 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9130 [self removeProgressHUD:hud];
9134 [essential_ removeAllObjects];
9135 [broken_ removeAllObjects];
9137 NSArray *packages([database_ packages]);
9138 for (Package *package in packages) {
9140 [broken_ addObject:package];
9141 if ([package upgradableAndEssential:NO]) {
9142 if ([package essential])
9143 [essential_ addObject:package];
9148 NSLog(@"changes:#%u", changes);
9150 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9153 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9154 [changesItem setBadgeValue:badge];
9155 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9156 [self setApplicationIconBadgeNumber:changes];
9159 [changesItem setBadgeValue:nil];
9160 [changesItem setAnimatedBadge:NO];
9161 [self setApplicationIconBadgeNumber:0];
9166 [self refreshIfPossible];
9169 - (void) updateData {
9178 @synchronized (self) {
9179 [self _reloadDataWithInvocation:nil];
9183 - (void) disemulate {
9184 if (emulated_ == nil)
9187 [window_ addSubview:[tabbar_ view]];
9188 [[emulated_ view] removeFromSuperview];
9189 [emulated_ release];
9191 [window_ setUserInteractionEnabled:YES];
9194 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9195 UINavigationController *navigation([[[CYNavigationController alloc] initWithRootViewController:controller] autorelease]);
9197 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9199 UIViewController *parent;
9200 if (emulated_ == nil)
9209 [parent presentModalViewController:navigation animated:YES];
9212 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9213 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9215 if (navigation != nil)
9216 [navigation pushViewController:progress animated:YES];
9218 [self presentModalViewController:progress force:YES];
9220 [progress invoke:invocation withTitle:title];
9224 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9225 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9228 - (void) repairWithInvocation:(NSInvocation *)invocation {
9230 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9234 - (void) repairWithSelector:(SEL)selector {
9235 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9241 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
9242 _assert(file != NULL);
9244 for (NSString *key in [Sources_ allKeys]) {
9245 NSDictionary *source([Sources_ objectForKey:key]);
9247 fprintf(file, "%s %s %s\n",
9248 [[source objectForKey:@"Type"] UTF8String],
9249 [[source objectForKey:@"URI"] UTF8String],
9250 [[source objectForKey:@"Distribution"] UTF8String]
9256 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9261 - (void) addTrivialSource:(NSString *)href {
9262 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
9265 @"./", @"Distribution",
9266 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
9271 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9272 @synchronized (self) {
9273 [self _reloadDataWithInvocation:invocation];
9277 - (void) reloadData {
9278 [self reloadDataWithInvocation:nil];
9282 pkgProblemResolver *resolver = [database_ resolver];
9284 resolver->InstallProtect();
9285 if (!resolver->Resolve(true))
9290 // XXX: this is a really crappy way of doing this.
9291 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9292 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9293 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9294 if ([tabbar_ updating])
9295 [tabbar_ cancelUpdate];
9297 if (![database_ prepare])
9300 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9301 [page setDelegate:self];
9302 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
9303 [confirm_ setDelegate:self];
9306 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9307 [tabbar_ presentModalViewController:confirm_ animated:YES];
9313 @synchronized (self) {
9318 - (void) clearPackage:(Package *)package {
9319 @synchronized (self) {
9326 - (void) installPackages:(NSArray *)packages {
9327 @synchronized (self) {
9328 for (Package *package in packages)
9335 - (void) installPackage:(Package *)package {
9336 @synchronized (self) {
9343 - (void) removePackage:(Package *)package {
9344 @synchronized (self) {
9351 - (void) distUpgrade {
9352 @synchronized (self) {
9353 if (![database_ upgrade])
9359 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9362 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
9367 - (void) showSettings {
9368 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9369 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9371 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9372 [tabbar_ presentModalViewController:nav animated:YES];
9375 - (void) retainNetworkActivityIndicator {
9376 if (activity_++ == 0)
9377 [self setNetworkActivityIndicatorVisible:YES];
9380 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9384 - (void) releaseNetworkActivityIndicator {
9385 if (--activity_ == 0)
9386 [self setNetworkActivityIndicatorVisible:NO];
9389 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9394 - (void) cancelAndClear:(bool)clear {
9395 @synchronized (self) {
9407 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9408 NSString *context([alert context]);
9410 if ([context isEqualToString:@"conffile"]) {
9411 FILE *input = [database_ input];
9412 if (button == [alert cancelButtonIndex])
9413 fprintf(input, "N\n");
9414 else if (button == [alert firstOtherButtonIndex])
9415 fprintf(input, "Y\n");
9418 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9419 } else if ([context isEqualToString:@"fixhalf"]) {
9420 if (button == [alert cancelButtonIndex]) {
9421 @synchronized (self) {
9422 for (Package *broken in broken_) {
9425 NSString *id = [broken id];
9426 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9427 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9428 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9429 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9435 } else if (button == [alert firstOtherButtonIndex]) {
9436 [broken_ removeAllObjects];
9440 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9441 } else if ([context isEqualToString:@"upgrade"]) {
9442 if (button == [alert firstOtherButtonIndex]) {
9443 @synchronized (self) {
9444 for (Package *essential in essential_)
9445 [essential install];
9450 } else if (button == [alert firstOtherButtonIndex] + 1) {
9452 } else if (button == [alert cancelButtonIndex]) {
9456 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9460 - (void) system:(NSString *)command { _pooled
9462 system([command UTF8String]);
9466 - (void) applicationWillSuspend {
9468 [super applicationWillSuspend];
9471 - (BOOL) isSafeToSuspend {
9474 NSLog(@"isSafeToSuspend: locked_ != 0");
9479 // Use external process status API internally.
9480 // This is probably a really bad idea.
9481 // XXX: what is the point of this? does this solve anything at all?
9482 uint64_t status = 0;
9484 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9485 notify_get_state(notify_token, &status);
9486 notify_cancel(notify_token);
9491 NSLog(@"isSafeToSuspend: status != 0");
9497 NSLog(@"isSafeToSuspend: -> true");
9502 - (void) applicationSuspend:(__GSEvent *)event {
9503 if ([self isSafeToSuspend])
9504 [super applicationSuspend:event];
9507 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9508 if ([self isSafeToSuspend])
9509 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9512 - (void) _setSuspended:(BOOL)value {
9513 if ([self isSafeToSuspend])
9514 [super _setSuspended:value];
9517 - (UIProgressHUD *) addProgressHUD {
9518 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9519 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9521 [window_ setUserInteractionEnabled:NO];
9524 UIViewController *target = tabbar_;
9525 while ([target modalViewController] != nil) target = [target modalViewController];
9526 [[target view] addSubview:hud];
9532 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9534 [hud removeFromSuperview];
9535 [window_ setUserInteractionEnabled:YES];
9539 - (CYViewController *) pageForPackage:(NSString *)name {
9540 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9543 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9544 NSString *scheme([[url scheme] lowercaseString]);
9545 if ([[url absoluteString] length] <= [scheme length] + 3)
9547 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9548 NSArray *components([path pathComponents]);
9550 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9551 return [self pageForPackage:[components objectAtIndex:1]];
9553 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9556 NSString *base([components objectAtIndex:0]);
9558 CYViewController *controller = nil;
9560 if ([base isEqualToString:@"url"]) {
9561 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9562 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9563 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9564 } else if (!external && [components count] == 1) {
9565 if ([base isEqualToString:@"manage"]) {
9566 controller = [[[ManageController alloc] init] autorelease];
9569 if ([base isEqualToString:@"sources"]) {
9570 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9573 if ([base isEqualToString:@"home"]) {
9574 controller = [[[HomeController alloc] init] autorelease];
9577 if ([base isEqualToString:@"sections"]) {
9578 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9581 if ([base isEqualToString:@"search"]) {
9582 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9585 if ([base isEqualToString:@"changes"]) {
9586 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9589 if ([base isEqualToString:@"installed"]) {
9590 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9592 } else if ([components count] == 2) {
9593 NSString *argument = [components objectAtIndex:1];
9595 if ([base isEqualToString:@"package"]) {
9596 controller = [self pageForPackage:argument];
9599 if (!external && [base isEqualToString:@"search"]) {
9600 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9601 [(SearchController *)controller setSearchTerm:argument];
9604 if (!external && [base isEqualToString:@"sections"]) {
9605 if ([argument isEqualToString:@"all"])
9607 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9610 if (!external && [base isEqualToString:@"sources"]) {
9611 if ([argument isEqualToString:@"add"]) {
9612 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9613 [(SourcesController *)controller showAddSourcePrompt];
9615 Source *source = [database_ sourceWithKey:argument];
9616 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9620 if (!external && [base isEqualToString:@"launch"]) {
9621 [self launchApplicationWithIdentifier:argument suspended:NO];
9624 } else if (!external && [components count] == 3) {
9625 NSString *arg1 = [components objectAtIndex:1];
9626 NSString *arg2 = [components objectAtIndex:2];
9628 if ([base isEqualToString:@"package"]) {
9629 if ([arg2 isEqualToString:@"settings"]) {
9630 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9631 } else if ([arg2 isEqualToString:@"files"]) {
9632 if (Package *package = [database_ packageWithName:arg1]) {
9633 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9634 [(FileTable *)controller setPackage:package];
9640 [controller setDelegate:self];
9644 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9645 CYViewController *page([self pageForURL:url forExternal:external]);
9648 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9649 [nav setViewControllers:[NSArray arrayWithObject:page]];
9650 [tabbar_ setUnselectedViewController:nav];
9656 - (void) applicationOpenURL:(NSURL *)url {
9657 [super applicationOpenURL:url];
9659 if (!loaded_) starturl_ = [url retain];
9660 else [self openCydiaURL:url forExternal:YES];
9663 - (void) applicationWillResignActive:(UIApplication *)application {
9664 // Stop refreshing if you get a phone call or lock the device.
9665 if ([tabbar_ updating])
9666 [tabbar_ cancelUpdate];
9668 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9669 [super applicationWillResignActive:application];
9672 - (void) applicationWillTerminate:(UIApplication *)application {
9674 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9675 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9676 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9681 - (void) setConfigurationData:(NSString *)data {
9682 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9684 if (!conffile_r(data)) {
9685 lprintf("E:invalid conffile\n");
9689 NSString *ofile = conffile_r[1];
9690 //NSString *nfile = conffile_r[2];
9692 UIAlertView *alert = [[[UIAlertView alloc]
9693 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9694 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9696 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9698 UCLocalize("ACCEPT_NEW_COPY"),
9699 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9703 [alert setContext:@"conffile"];
9704 [alert setNumberOfRows:2];
9708 - (void) addStashController {
9710 stash_ = [[StashController alloc] init];
9711 [window_ addSubview:[stash_ view]];
9714 - (void) removeStashController {
9715 [[stash_ view] removeFromSuperview];
9721 [self setIdleTimerDisabled:YES];
9723 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9724 UpdateExternalStatus(1);
9725 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9726 UpdateExternalStatus(0);
9728 [self removeStashController];
9730 if (ExecFork() == 0) {
9731 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9732 perror("launchctl stop");
9736 - (void) setupViewControllers {
9737 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9739 NSMutableArray *items([NSMutableArray arrayWithObjects:
9740 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9741 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9742 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9743 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9747 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9748 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9750 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9753 NSMutableArray *controllers([NSMutableArray array]);
9754 for (UITabBarItem *item in items) {
9755 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9756 [controller setTabBarItem:item];
9757 [controllers addObject:controller];
9759 [tabbar_ setViewControllers:controllers];
9761 [tabbar_ setUpdateDelegate:self];
9764 - (void) addBridgedHost:(NSString *)host {
9765 [BridgedHosts_ addObject:host];
9768 - (void) applicationDidFinishLaunching:(id)unused {
9770 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9771 [self setApplicationSupportsShakeToEdit:NO];
9773 [self addBridgedHost:[[NSURL URLWithString:CydiaURL(@"")] host]];
9775 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9776 initWithMemoryCapacity:524288
9777 diskCapacity:10485760
9778 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9781 [CYBrowserController _initialize];
9783 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9785 Font12_ = [[UIFont systemFontOfSize:12] retain];
9786 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9787 Font14_ = [[UIFont systemFontOfSize:14] retain];
9788 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9789 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9791 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9792 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9794 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9795 [window_ orderFront:self];
9796 [window_ makeKey:self];
9797 [window_ setHidden:NO];
9800 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9801 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9802 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9803 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9804 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9805 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9806 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9807 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9808 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9811 [self addStashController];
9812 // XXX: this would be much cleaner as a yieldToSelector:
9813 // that way the removeStashController could happen right here inline
9814 // we also could no longer require the useless stash_ field anymore
9815 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9819 database_ = [Database sharedInstance];
9820 [database_ setDelegate:self];
9822 [window_ setUserInteractionEnabled:NO];
9823 [self setupViewControllers];
9825 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9826 [window_ addSubview:[emulated_ view]];
9828 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9832 - (NSArray *) defaultStartPages {
9833 NSMutableArray *standard = [NSMutableArray array];
9834 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9835 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9836 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9838 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9840 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9841 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9843 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9850 [window_ setUserInteractionEnabled:YES];
9851 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9854 if ([emulated_ modalViewController] != nil)
9855 [emulated_ dismissModalViewControllerAnimated:YES];
9856 [window_ setUserInteractionEnabled:NO];
9864 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9865 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9866 int standardIndex = 0;
9867 NSArray *standard = [self defaultStartPages];
9874 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9875 if (valid && closed != nil) {
9876 NSTimeInterval interval([closed timeIntervalSinceNow]);
9877 // XXX: Is 15 minutes the optimal time here?
9878 if (interval > 0 && interval <= -(15*60))
9882 if (valid && [saved count] != [standard count])
9886 for (unsigned int i = 0; i < [standard count]; i++) {
9887 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9888 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9889 // but it's good enough for now.
9890 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9897 NSArray *items = nil;
9899 [tabbar_ setSelectedIndex:savedIndex];
9902 [tabbar_ setSelectedIndex:standardIndex];
9906 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9907 NSArray *stack = [items objectAtIndex:tab];
9908 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9909 NSMutableArray *current = [NSMutableArray array];
9911 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9912 NSString *addr = [stack objectAtIndex:nav];
9913 NSURL *url = [NSURL URLWithString:addr];
9914 CYViewController *page = [self pageForURL:url forExternal:NO];
9916 [current addObject:page];
9919 [navigation setViewControllers:current];
9922 // (Try to) show the startup URL.
9923 if (starturl_ != nil) {
9924 [self openCydiaURL:starturl_ forExternal:NO];
9925 [starturl_ release];
9930 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9931 if (item != nil && IsWildcat_) {
9932 [sheet showFromBarButtonItem:item animated:YES];
9934 [sheet showInView:window_];
9938 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9939 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9940 [progress setTitle:task];
9941 [progress addProgressEvent:event];
9944 - (void) addProgressEventForTask:(NSArray *)data {
9945 CydiaProgressEvent *event([data objectAtIndex:0]);
9946 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9947 [self addProgressEvent:event forTask:task];
9950 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9951 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9957 id Alloc_(id self, SEL selector) {
9958 id object = alloc_(self, selector);
9959 lprintf("[%s]A-%p\n", self->isa->name, object);
9964 id Dealloc_(id self, SEL selector) {
9965 id object = dealloc_(self, selector);
9966 lprintf("[%s]D-%p\n", self->isa->name, object);
9970 Class $WebDefaultUIKitDelegate;
9972 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9973 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9974 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9975 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9978 static NSNumber *shouldPlayKeyboardSounds;
9982 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9984 case 1104: // Keyboard Button Clicked
9985 case 1105: // Keyboard Delete Repeated
9986 if (shouldPlayKeyboardSounds == nil) {
9987 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9988 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9991 if (![shouldPlayKeyboardSounds boolValue])
9995 _UIHardware$_playSystemSound$(self, _cmd, sound);
9999 Class $UIApplication;
10001 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
10002 static BOOL initialized = NO;
10003 static BOOL started = NO;
10005 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
10006 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
10008 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
10009 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
10010 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
10011 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
10013 if (initialized && !enabled) {
10015 [bundle performSelector:@selector(_accessibilityStopServer)];
10016 } else if (enabled) {
10020 [bundle performSelector:@selector(_accessibilityStartServer)];
10026 Class $NSURLConnection;
10028 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10029 NSMutableURLRequest *copy([request mutableCopy]);
10031 NSURL *url([copy URL]);
10032 NSString *host([url host]);
10034 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10035 if ([BridgedHosts_ containsObject:host])
10036 [copy setHTTPShouldUsePipelining:YES];
10038 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10042 int main(int argc, char *argv[]) { _pooled
10045 UpdateExternalStatus(0);
10047 if (Class $UIDevice = objc_getClass("UIDevice")) {
10048 UIDevice *device([$UIDevice currentDevice]);
10049 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10051 IsWildcat_ = false;
10053 UIScreen *screen([UIScreen mainScreen]);
10054 if ([screen respondsToSelector:@selector(scale)])
10055 ScreenScale_ = [screen scale];
10059 UIDevice *device([UIDevice currentDevice]);
10060 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10061 Idiom_ = @"iphone";
10063 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10064 if (idiom == UIUserInterfaceIdiomPhone)
10065 Idiom_ = @"iphone";
10066 else if (idiom == UIUserInterfaceIdiomPad)
10069 NSLog(@"unknown UIUserInterfaceIdiom!");
10072 BridgedHosts_ = [NSMutableSet setWithCapacity:2];
10074 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
10076 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10078 /* Library Hacks {{{ */
10079 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10081 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10082 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10083 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10084 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10085 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10088 $NSURLConnection = objc_getClass("NSURLConnection");
10089 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10090 if (NSURLConnection$init$ != NULL) {
10091 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10092 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10095 $UIHardware = objc_getClass("UIHardware");
10096 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
10097 if (UIHardware$_playSystemSound$ != NULL) {
10098 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
10099 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
10102 $UIApplication = objc_getClass("UIApplication");
10103 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
10104 if (UIApplication$_updateApplicationAccessibility != NULL) {
10105 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
10106 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
10109 /* Set Locale {{{ */
10110 Locale_ = CFLocaleCopyCurrent();
10111 Languages_ = [NSLocale preferredLanguages];
10113 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10114 //NSLog(@"%@", [Languages_ description]);
10117 if (Locale_ != NULL)
10118 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10119 else if (Languages_ == nil || [Languages_ count] == 0)
10120 // XXX: consider just setting to C and then falling through?
10123 lang = [[Languages_ objectAtIndex:0] UTF8String];
10124 setenv("LANG", lang, true);
10125 std::setlocale(LC_ALL, lang);
10128 NSLog(@"Setting Language: %s", lang);
10131 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10133 /* Parse Arguments {{{ */
10134 bool substrate(false);
10140 for (int argi(1); argi != argc; ++argi)
10141 if (strcmp(argv[argi], "--") == 0) {
10143 argv[argi] = argv[0];
10149 for (int argi(1); argi != arge; ++argi)
10150 if (strcmp(args[argi], "--substrate") == 0)
10153 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10157 App_ = [[NSBundle mainBundle] bundlePath];
10163 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10164 alloc_ = alloc->method_imp;
10165 alloc->method_imp = (IMP) &Alloc_;*/
10167 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10168 dealloc_ = dealloc->method_imp;
10169 dealloc->method_imp = (IMP) &Dealloc_;*/
10171 /* System Information {{{ */
10175 size = sizeof(maxproc);
10176 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10177 perror("sysctlbyname(\"kern.maxproc\", ?)");
10178 else if (maxproc < 64) {
10180 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10181 perror("sysctlbyname(\"kern.maxproc\", #)");
10184 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10185 char *osversion = new char[size];
10186 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10187 perror("sysctlbyname(\"kern.osversion\", ?)");
10189 System_ = [NSString stringWithUTF8String:osversion];
10191 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10192 char *machine = new char[size];
10193 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10194 perror("sysctlbyname(\"hw.machine\", ?)");
10196 Machine_ = machine;
10198 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
10199 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
10200 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
10201 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
10205 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
10206 NSData *data((NSData *) ecid);
10207 size_t length([data length]);
10208 uint8_t bytes[length];
10209 [data getBytes:bytes];
10210 char string[length * 2 + 1];
10211 for (size_t i(0); i != length; ++i)
10212 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
10213 ChipID_ = [NSString stringWithUTF8String:string];
10217 IOObjectRelease(service);
10221 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
10223 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10224 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10225 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10227 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10228 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10229 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10231 if (mcc != NULL && mnc != NULL)
10232 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10239 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10240 Build_ = [system objectForKey:@"ProductBuildVersion"];
10241 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10242 Product_ = [info objectForKey:@"SafariProductVersion"];
10243 Safari_ = [info objectForKey:@"CFBundleVersion"];
10246 /* Load Database {{{ */
10248 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10250 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10252 if (Metadata_ == NULL)
10253 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10255 Settings_ = [Metadata_ objectForKey:@"Settings"];
10257 Packages_ = [Metadata_ objectForKey:@"Packages"];
10258 Sections_ = [Metadata_ objectForKey:@"Sections"];
10259 Sources_ = [Metadata_ objectForKey:@"Sources"];
10261 Token_ = [Metadata_ objectForKey:@"Token"];
10264 if (Settings_ != nil)
10265 Role_ = [Settings_ objectForKey:@"Role"];
10267 if (Sections_ == nil) {
10268 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10269 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10272 if (Sources_ == nil) {
10273 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10274 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10279 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10282 if (Packages_ != nil) {
10284 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10288 [Metadata_ removeObjectForKey:@"Packages"];
10294 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10296 #define MobileSubstrate_(name) \
10297 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10298 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10299 if (handle == NULL) \
10300 NSLog(@"%s", dlerror()); \
10303 MobileSubstrate_(Activator)
10304 MobileSubstrate_(libstatusbar)
10305 MobileSubstrate_(SimulatedKeyEvents)
10306 MobileSubstrate_(WinterBoard)
10308 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10309 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10311 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10313 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10314 unlink("/tmp/.cydia.fw");
10316 } else if (access("/User", F_OK) != 0 || version < 4) {
10319 system("/usr/libexec/cydia/firmware.sh");
10323 _assert([[NSFileManager defaultManager]
10324 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10325 withIntermediateDirectories:YES
10330 if (access("/tmp/cydia.chk", F_OK) == 0) {
10331 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10332 _assert(errno == ENOENT);
10333 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10334 _assert(errno == ENOENT);
10337 /* APT Initialization {{{ */
10338 _assert(pkgInitConfig(*_config));
10339 _assert(pkgInitSystem(*_config, _system));
10342 _config->Set("APT::Acquire::Translation", lang);
10344 // XXX: this timeout might be important :(
10345 //_config->Set("Acquire::http::Timeout", 15);
10347 _config->Set("Acquire::http::MaxParallel", 3);
10349 /* Color Choices {{{ */
10350 space_ = CGColorSpaceCreateDeviceRGB();
10352 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10353 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10354 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10355 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10356 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10357 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10358 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10359 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10360 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10362 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10363 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10365 /* UIKit Configuration {{{ */
10366 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10367 if ($GSFontSetUseLegacyFontMetrics != NULL)
10368 $GSFontSetUseLegacyFontMetrics(YES);
10370 // XXX: I have a feeling this was important
10371 //UIKeyboardDisableAutomaticAppearance();
10374 Colon_ = UCLocalize("COLON_DELIMITED");
10375 Elision_ = UCLocalize("ELISION");
10376 Error_ = UCLocalize("ERROR");
10377 Warning_ = UCLocalize("WARNING");
10380 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10382 CGColorSpaceRelease(space_);
10383 CFRelease(Locale_);