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_;
1090 static NSMutableSet *PipelinedHosts_;
1092 static NSString *kCydiaProgressEventTypeError = @"Error";
1093 static NSString *kCydiaProgressEventTypeInformation = @"Information";
1094 static NSString *kCydiaProgressEventTypeStatus = @"Status";
1095 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
1098 /* Display Helpers {{{ */
1099 inline float Interpolate(float begin, float end, float fraction) {
1100 return (end - begin) * fraction + begin;
1103 static _finline const char *StripVersion_(const char *version) {
1104 const char *colon(strchr(version, ':'));
1105 return colon == NULL ? version : colon + 1;
1108 NSString *LocalizeSection(NSString *section) {
1109 static Pcre title_r("^(.*?) \\((.*)\\)$");
1110 if (title_r(section)) {
1111 NSString *parent(title_r[1]);
1112 NSString *child(title_r[2]);
1114 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1115 LocalizeSection(parent),
1116 LocalizeSection(child)
1120 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1123 NSString *Simplify(NSString *title) {
1124 const char *data = [title UTF8String];
1125 size_t size = [title length];
1127 static Pcre square_r("^\\[(.*)\\]$");
1128 if (square_r(data, size))
1129 return Simplify(square_r[1]);
1131 static Pcre paren_r("^\\((.*)\\)$");
1132 if (paren_r(data, size))
1133 return Simplify(paren_r[1]);
1135 static Pcre title_r("^(.*?) \\((.*)\\)$");
1136 if (title_r(data, size))
1137 return Simplify(title_r[1]);
1143 NSString *GetLastUpdate() {
1144 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1147 return UCLocalize("NEVER_OR_UNKNOWN");
1149 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1150 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1152 CFRelease(formatter);
1154 return [(NSString *) formatted autorelease];
1157 bool isSectionVisible(NSString *section) {
1158 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1159 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1160 return hidden == nil || ![hidden boolValue];
1165 /* Delegate Prototypes {{{ */
1168 @class CydiaProgressEvent;
1170 @protocol DatabaseDelegate
1171 - (void) repairWithSelector:(SEL)selector;
1172 - (void) setConfigurationData:(NSString *)data;
1173 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
1176 @class CYPackageController;
1178 @protocol CydiaDelegate
1179 - (void) retainNetworkActivityIndicator;
1180 - (void) releaseNetworkActivityIndicator;
1181 - (void) clearPackage:(Package *)package;
1182 - (void) installPackage:(Package *)package;
1183 - (void) installPackages:(NSArray *)packages;
1184 - (void) removePackage:(Package *)package;
1185 - (void) beginUpdate;
1187 - (void) distUpgrade;
1189 - (void) updateData;
1191 - (void) addTrivialSource:(NSString *)href;
1192 - (void) showSettings;
1193 - (UIProgressHUD *) addProgressHUD;
1194 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1195 - (CYViewController *) pageForPackage:(NSString *)name;
1196 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1197 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
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(addPipelinedHost:))
4214 return @"addPipelinedHost";
4215 else if (selector == @selector(addTrivialSource:))
4216 return @"addTrivialSource";
4217 else if (selector == @selector(close))
4219 else if (selector == @selector(divert::))
4221 else if (selector == @selector(du:))
4223 else if (selector == @selector(stringWithFormat:arguments:))
4225 else if (selector == @selector(getAllSources))
4226 return @"getAllSourcs";
4227 else if (selector == @selector(getKernelNumber:))
4228 return @"getKernelNumber";
4229 else if (selector == @selector(getKernelString:))
4230 return @"getKernelString";
4231 else if (selector == @selector(getInstalledPackages))
4232 return @"getInstalledPackages";
4233 else if (selector == @selector(getPackageById:))
4234 return @"getPackageById";
4235 else if (selector == @selector(installPackages:))
4236 return @"installPackages";
4237 else if (selector == @selector(localizedStringForKey:value:table:))
4239 else if (selector == @selector(popViewController:))
4240 return @"popViewController";
4241 else if (selector == @selector(refreshSources))
4242 return @"refreshSources";
4243 else if (selector == @selector(removeButton))
4244 return @"removeButton";
4245 else if (selector == @selector(substitutePackageNames:))
4246 return @"substitutePackageNames";
4247 else if (selector == @selector(scrollToBottom:))
4248 return @"scrollToBottom";
4249 else if (selector == @selector(setAllowsNavigationAction:))
4250 return @"setAllowsNavigationAction";
4251 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4252 return @"setButtonImage";
4253 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4254 return @"setButtonTitle";
4255 else if (selector == @selector(setHidesBackButton:))
4256 return @"setHidesBackButton";
4257 else if (selector == @selector(setHidesNavigationBar:))
4258 return @"setHidesNavigationBar";
4259 else if (selector == @selector(setNavigationBarStyle:))
4260 return @"setNavigationBarStyle";
4261 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4262 return @"setNavigationBarTintColor";
4263 else if (selector == @selector(setPopupHook:))
4264 return @"setPopupHook";
4265 else if (selector == @selector(setToken:))
4267 else if (selector == @selector(setViewportWidth:))
4268 return @"setViewportWidth";
4269 else if (selector == @selector(statfs:))
4271 else if (selector == @selector(supports:))
4277 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4278 return [self webScriptNameForSelector:selector] == nil;
4281 - (BOOL) supports:(NSString *)feature {
4282 return [feature isEqualToString:@"window.open"];
4285 - (void) divert:(NSString *)from :(NSString *)to {
4286 [CYBrowserController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4289 - (NSNumber *) getKernelNumber:(NSString *)name {
4290 const char *string([name UTF8String]);
4293 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4294 return (id) [NSNull null];
4296 if (size != sizeof(int))
4297 return (id) [NSNull null];
4300 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4301 return (id) [NSNull null];
4303 return [NSNumber numberWithInt:value];
4306 - (NSString *) getKernelString:(NSString *)name {
4307 const char *string([name UTF8String]);
4310 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4311 return (id) [NSNull null];
4313 char value[size + 1];
4314 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4315 return (id) [NSNull null];
4317 // XXX: just in case you request something ludicrous
4320 return [NSString stringWithCString:value];
4323 - (void) addBridgedHost:(NSString *)host {
4324 [BridgedHosts_ performSelectorOnMainThread:@selector(addObject:) withObject:host waitUntilDone:NO];
4327 - (void) addPipelinedHost:(NSString *)host {
4328 [PipelinedHosts_ performSelectorOnMainThread:@selector(addObject:) withObject:host waitUntilDone:NO];
4331 - (void) popViewController:(NSNumber *)value {
4332 if (value == (id) [WebUndefined undefined])
4333 value = [NSNumber numberWithBool:YES];
4334 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4337 - (void) addTrivialSource:(NSString *)href {
4338 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4341 - (void) refreshSources {
4342 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4345 - (NSArray *) getAllSources {
4346 return [[Database sharedInstance] sources];
4349 - (NSArray *) getInstalledPackages {
4350 Database *database([Database sharedInstance]);
4351 @synchronized (database) {
4352 NSArray *packages([database packages]);
4353 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4354 for (Package *package in packages)
4355 if (![package uninstalled])
4356 [installed addObject:package];
4360 - (Package *) getPackageById:(NSString *)id {
4361 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4365 return (Package *) [NSNull null];
4368 - (NSArray *) statfs:(NSString *)path {
4371 if (path == nil || statfs([path UTF8String], &stat) == -1)
4374 return [NSArray arrayWithObjects:
4375 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4376 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4377 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4381 - (NSNumber *) du:(NSString *)path {
4382 NSNumber *value(nil);
4385 _assert(pipe(fds) != -1);
4387 pid_t pid(ExecFork());
4389 _assert(dup2(fds[1], 1) != -1);
4390 _assert(close(fds[0]) != -1);
4391 _assert(close(fds[1]) != -1);
4392 /* XXX: this should probably not use du */
4393 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4398 _assert(close(fds[1]) != -1);
4400 if (FILE *du = fdopen(fds[0], "r")) {
4402 while (fgets(line, sizeof(line), du) != NULL) {
4403 size_t length(strlen(line));
4404 while (length != 0 && line[length - 1] == '\n')
4405 line[--length] = '\0';
4406 if (char *tab = strchr(line, '\t')) {
4408 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4413 } else _assert(close(fds[0]));
4417 if (waitpid(pid, &status, 0) == -1)
4420 else _assert(false);
4426 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4429 - (void) installPackages:(NSArray *)packages {
4430 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4433 - (NSString *) substitutePackageNames:(NSString *)message {
4434 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4435 for (size_t i(0), e([words count]); i != e; ++i) {
4436 NSString *word([words objectAtIndex:i]);
4437 if (Package *package = [[Database sharedInstance] packageWithName:word])
4438 [words replaceObjectAtIndex:i withObject:[package name]];
4441 return [words componentsJoinedByString:@" "];
4444 - (void) removeButton {
4445 [indirect_ removeButton];
4448 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4449 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4452 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4453 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4456 - (void) setAllowsNavigationAction:(NSString *)value {
4457 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4460 - (void) setHidesBackButton:(NSString *)value {
4461 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4464 - (void) setHidesNavigationBar:(NSString *)value {
4465 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4468 - (void) setNavigationBarStyle:(NSString *)value {
4469 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4472 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4473 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4474 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4475 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4478 - (void) _setToken:(NSString *)token {
4482 [Metadata_ removeObjectForKey:@"Token"];
4484 [Metadata_ setObject:Token_ forKey:@"Token"];
4489 - (void) setToken:(NSString *)token {
4490 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4493 - (void) setPopupHook:(id)function {
4494 [indirect_ setPopupHook:function];
4497 - (void) scrollToBottom:(NSNumber *)animated {
4498 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4501 - (void) setViewportWidth:(float)width {
4502 [indirect_ setViewportWidthOnMainThread:width];
4505 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4506 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4507 unsigned count([arguments count]);
4509 for (unsigned i(0); i != count; ++i)
4510 values[i] = [arguments objectAtIndex:i];
4511 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4514 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4515 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4517 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4519 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4525 /* @ Loading... Indicator {{{ */
4526 @interface CYLoadingIndicator : UIView {
4527 _H<UIActivityIndicatorView> spinner_;
4529 _H<UIView> container_;
4532 @property (readonly, nonatomic) UILabel *label;
4533 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4537 @implementation CYLoadingIndicator
4539 - (id) initWithFrame:(CGRect)frame {
4540 if ((self = [super initWithFrame:frame]) != nil) {
4541 container_ = [[[UIView alloc] init] autorelease];
4542 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4544 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4545 [spinner_ startAnimating];
4546 [container_ addSubview:spinner_];
4548 label_ = [[[UILabel alloc] init] autorelease];
4549 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4550 [label_ setBackgroundColor:[UIColor clearColor]];
4551 [label_ setTextColor:[UIColor blackColor]];
4552 [label_ setShadowColor:[UIColor whiteColor]];
4553 [label_ setShadowOffset:CGSizeMake(0, 1)];
4554 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4555 [container_ addSubview:label_];
4557 CGSize viewsize = frame.size;
4558 CGSize spinnersize = [spinner_ bounds].size;
4559 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4560 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4562 CGRect containrect = {
4563 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4564 CGSizeMake(bothwidth, spinnersize.height)
4567 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4575 [container_ setFrame:containrect];
4576 [spinner_ setFrame:spinrect];
4577 [label_ setFrame:textrect];
4578 [self addSubview:container_];
4582 - (UILabel *) label {
4586 - (UIActivityIndicatorView *) activityIndicatorView {
4592 /* Emulated Loading Controller {{{ */
4593 @interface CYEmulatedLoadingController : CYViewController {
4594 _transient Database *database_;
4595 _H<CYLoadingIndicator> indicator_;
4596 _H<UITabBar> tabbar_;
4597 _H<UINavigationBar> navbar_;
4602 @implementation CYEmulatedLoadingController
4604 - (id) initWithDatabase:(Database *)database {
4605 if ((self = [super init]) != nil) {
4606 database_ = database;
4611 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4613 UITableView *table([[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]);
4614 [table setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4615 [[self view] addSubview:table];
4617 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4618 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4619 [[self view] addSubview:indicator_];
4621 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4622 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4623 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4624 [[self view] addSubview:tabbar_];
4626 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4627 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4628 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4629 [[self view] addSubview:navbar_];
4632 - (void) releaseSubviews {
4641 /* Cydia Browser Controller {{{ */
4642 @implementation CYBrowserController
4649 - (NSURL *) navigationURL {
4650 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4653 + (void) initialize {
4654 Diversions_ = [[NSMutableSet alloc] initWithCapacity:0];
4657 + (void) addDiversion:(Diversion *)diversion {
4658 [Diversions_ addObject:diversion];
4661 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4662 [super webView:view didClearWindowObject:window forFrame:frame];
4664 WebDataSource *source([frame dataSource]);
4665 NSURLResponse *response([source response]);
4666 NSURL *url([response URL]);
4668 if ([[[url scheme] lowercaseString] isEqualToString:@"https"])
4669 if ([BridgedHosts_ containsObject:[url host]])
4670 [window setValue:cydia_ forKey:@"cydia"];
4673 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4674 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4677 NSURL *url([copy URL]);
4678 NSString *href([url absoluteString]);
4680 for (Diversion *diversion in Diversions_)
4681 if (NSString *diverted = [diversion divert:href]) {
4682 [copy setURL:[NSURL URLWithString:diverted]];
4686 if (System_ != NULL)
4687 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4688 if (Machine_ != NULL)
4689 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4691 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4696 - (void) setDelegate:(id)delegate {
4697 [super setDelegate:delegate];
4698 [cydia_ setDelegate:delegate];
4702 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4703 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4705 WebView *webview([[webview_ _documentView] webView]);
4707 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4710 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4712 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4713 if (Product_ != nil)
4714 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4716 [webview setApplicationNameForUserAgent:application];
4724 @interface NSObject (CydiaScript)
4725 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4728 @implementation NSObject (CydiaScript)
4730 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4736 @implementation NSArray (CydiaScript)
4738 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4739 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4740 for (size_t i(0), e([self count]); i != e; ++i)
4741 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4747 @implementation NSDictionary (CydiaScript)
4749 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4750 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4752 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4759 /* Confirmation Controller {{{ */
4760 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4761 if (!iterator.end())
4762 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4763 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4765 pkgCache::PkgIterator package(dep.TargetPkg());
4768 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4775 @protocol ConfirmationControllerDelegate
4776 - (void) cancelAndClear:(bool)clear;
4777 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4781 @interface ConfirmationController : CYBrowserController {
4782 _transient Database *database_;
4784 UIAlertView *essential_;
4786 NSDictionary *changes_;
4787 NSMutableArray *issues_;
4788 NSDictionary *sizes_;
4793 - (id) initWithDatabase:(Database *)database;
4797 @implementation ConfirmationController
4804 if (essential_ != nil)
4805 [essential_ release];
4812 RestartSubstrate_ = true;
4813 [delegate_ confirmWithNavigationController:[self navigationController]];
4816 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4817 NSString *context([alert context]);
4819 if ([context isEqualToString:@"remove"]) {
4820 if (button == [alert cancelButtonIndex])
4821 [self dismissModalViewControllerAnimated:YES];
4822 else if (button == [alert firstOtherButtonIndex]) {
4826 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4827 } else if ([context isEqualToString:@"unable"]) {
4828 [self dismissModalViewControllerAnimated:YES];
4829 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4831 [super alertView:alert clickedButtonAtIndex:button];
4835 - (void) _doContinue {
4836 [self dismissModalViewControllerAnimated:YES];
4837 [delegate_ cancelAndClear:NO];
4840 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4841 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4845 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4846 [super webView:view didClearWindowObject:window forFrame:frame];
4848 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4849 changes_, @"changes",
4853 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4856 - (id) initWithDatabase:(Database *)database {
4857 if ((self = [super init]) != nil) {
4858 database_ = database;
4860 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4861 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4862 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4863 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4864 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4868 pkgCacheFile &cache([database_ cache]);
4869 NSArray *packages([database_ packages]);
4870 pkgDepCache::Policy *policy([database_ policy]);
4872 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4874 for (Package *package in packages) {
4875 pkgCache::PkgIterator iterator([package iterator]);
4876 NSString *name([package id]);
4878 if ([package broken]) {
4879 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4881 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4883 reasons, @"reasons",
4886 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4890 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4891 pkgCache::DepIterator start;
4892 pkgCache::DepIterator end;
4893 dep.GlobOr(start, end); // ++dep
4895 if (!cache->IsImportantDep(end))
4897 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4900 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4902 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4903 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4904 clauses, @"clauses",
4908 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4910 pkgCache::PkgIterator target(start.TargetPkg());
4911 if (target->ProvidesList != 0)
4912 reason = @"missing";
4914 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4916 reason = @"installed";
4917 installed = [NSString stringWithUTF8String:ver.VerStr()];
4918 } else if (!cache[target].CandidateVerIter(cache).end())
4919 reason = @"uninstalled";
4920 else if (target->ProvidesList == 0)
4921 reason = @"uninstallable";
4923 reason = @"virtual";
4926 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4927 [NSString stringWithUTF8String:start.CompType()], @"operator",
4928 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4931 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4932 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4933 version, @"version",
4935 installed, @"installed",
4938 // yes, seriously. (wtf?)
4946 pkgDepCache::StateCache &state(cache[iterator]);
4948 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4950 if (state.NewInstall())
4951 [installs addObject:name];
4952 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4953 [reinstalls addObject:name];
4954 else if (state.Upgrade())
4955 [upgrades addObject:name];
4956 else if (state.Downgrade())
4957 [downgrades addObject:name];
4958 else if (!state.Delete())
4960 else if (special_r(name))
4961 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4962 [NSNull null], @"package",
4963 [NSArray arrayWithObjects:
4964 [NSDictionary dictionaryWithObjectsAndKeys:
4965 @"Conflicts", @"relationship",
4966 [NSArray arrayWithObjects:
4967 [NSDictionary dictionaryWithObjectsAndKeys:
4969 [NSNull null], @"version",
4970 @"installed", @"reason",
4977 if ([package essential])
4979 [removes addObject:name];
4982 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4983 substrate_ |= DepSubstrate(iterator.CurrentVer());
4988 else if (Advanced_) {
4989 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4991 essential_ = [[UIAlertView alloc]
4992 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4993 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4995 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4997 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5001 [essential_ setContext:@"remove"];
5003 essential_ = [[UIAlertView alloc]
5004 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5005 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5007 cancelButtonTitle:UCLocalize("OKAY")
5008 otherButtonTitles:nil
5011 [essential_ setContext:@"unable"];
5014 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
5015 installs, @"installs",
5016 reinstalls, @"reinstalls",
5017 upgrades, @"upgrades",
5018 downgrades, @"downgrades",
5019 removes, @"removes",
5022 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
5023 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5024 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5027 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5029 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
5030 initWithTitle:UCLocalize("CANCEL")
5031 style:UIBarButtonItemStylePlain
5033 action:@selector(cancelButtonClicked)
5039 - (void) applyRightButton {
5040 if ([issues_ count] == 0 && ![self isLoading])
5041 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5042 initWithTitle:UCLocalize("CONFIRM")
5043 style:UIBarButtonItemStyleDone
5045 action:@selector(confirmButtonClicked)
5048 [[self navigationItem] setRightBarButtonItem:nil];
5052 - (void) cancelButtonClicked {
5053 [self dismissModalViewControllerAnimated:YES];
5054 [delegate_ cancelAndClear:YES];
5058 - (void) confirmButtonClicked {
5059 if (essential_ != nil)
5069 /* Progress Data {{{ */
5070 @interface CydiaProgressData : NSObject {
5071 _transient id delegate_;
5080 _H<NSMutableArray> events_;
5081 _H<NSString> title_;
5083 _H<NSString> status_;
5084 _H<NSString> finish_;
5089 @implementation CydiaProgressData
5091 + (NSArray *) _attributeKeys {
5092 return [NSArray arrayWithObjects:
5104 - (NSArray *) attributeKeys {
5105 return [[self class] _attributeKeys];
5108 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5109 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5113 if ((self = [super init]) != nil) {
5114 events_ = [NSMutableArray arrayWithCapacity:32];
5118 - (void) setDelegate:(id)delegate {
5119 delegate_ = delegate;
5122 - (void) setPercent:(float)value {
5126 - (NSNumber *) percent {
5127 return [NSNumber numberWithFloat:percent_];
5130 - (void) setCurrent:(float)value {
5134 - (NSNumber *) current {
5135 return [NSNumber numberWithFloat:current_];
5138 - (void) setTotal:(float)value {
5142 - (NSNumber *) total {
5143 return [NSNumber numberWithFloat:total_];
5146 - (void) setSpeed:(float)value {
5150 - (NSNumber *) speed {
5151 return [NSNumber numberWithFloat:speed_];
5154 - (NSArray *) events {
5158 - (void) removeAllEvents {
5159 [events_ removeAllObjects];
5162 - (void) addEvent:(CydiaProgressEvent *)event {
5163 [events_ addObject:event];
5166 - (void) setTitle:(NSString *)text {
5170 - (NSString *) title {
5174 - (void) setFinish:(NSString *)text {
5178 - (NSString *) finish {
5179 return (id) finish_ ?: [NSNull null];
5182 - (void) setRunning:(bool)running {
5186 - (NSNumber *) running {
5187 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5192 /* Progress Controller {{{ */
5193 @interface ProgressController : CYBrowserController <
5196 _transient Database *database_;
5197 _H<CydiaProgressData> progress_;
5201 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5203 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5205 - (void) setTitle:(NSString *)title;
5206 - (void) setCancellable:(bool)cancellable;
5210 @implementation ProgressController
5213 [database_ setProgressDelegate:nil];
5214 [progress_ setDelegate:nil];
5218 - (void) updateCancel {
5219 [[self navigationItem] setLeftBarButtonItem:(cancel_ == 1 ? [[[UIBarButtonItem alloc]
5220 initWithTitle:UCLocalize("CANCEL")
5221 style:UIBarButtonItemStylePlain
5223 action:@selector(cancel)
5224 ] autorelease] : nil)];
5227 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5228 if ((self = [super init]) != nil) {
5229 database_ = database;
5230 delegate_ = delegate;
5232 [database_ setProgressDelegate:self];
5234 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5235 [progress_ setDelegate:self];
5237 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5239 [scroller_ setBackgroundColor:[UIColor blackColor]];
5241 [[self navigationItem] setHidesBackButton:YES];
5243 [self updateCancel];
5247 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5248 [super webView:view didClearWindowObject:window forFrame:frame];
5249 [window setValue:progress_ forKey:@"cydiaProgress"];
5252 - (void) updateProgress {
5253 [self dispatchEvent:@"CydiaProgressUpdate"];
5256 - (void) viewWillAppear:(BOOL)animated {
5257 if (![self hasLoaded])
5258 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5260 [super viewWillAppear:animated];
5264 UpdateExternalStatus(0);
5271 [delegate_ terminateWithSuccess];
5272 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5273 [delegate_ suspendWithAnimation:YES];
5275 [delegate_ suspend];*/
5287 system("/usr/bin/sbreload");
5293 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5294 SBReboot(SBSSpringBoardServerPort());
5296 reboot2(RB_AUTOBOOT);
5303 - (void) setTitle:(NSString *)title {
5304 [progress_ setTitle:title];
5305 [self updateProgress];
5308 - (UIBarButtonItem *) rightButton {
5309 return [[progress_ running] boolValue] ? nil : [[[UIBarButtonItem alloc]
5310 initWithTitle:UCLocalize("CLOSE")
5311 style:UIBarButtonItemStylePlain
5313 action:@selector(close)
5317 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5318 UpdateExternalStatus(1);
5320 [progress_ setRunning:true];
5321 [self setTitle:title];
5322 // implicit updateProgress
5324 SHA1SumValue notifyconf; {
5326 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5329 MMap mmap(file, MMap::ReadOnly);
5331 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5332 notifyconf = sha1.Result();
5336 SHA1SumValue springlist; {
5338 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5341 MMap mmap(file, MMap::ReadOnly);
5343 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5344 springlist = sha1.Result();
5348 if (invocation != nil) {
5349 [invocation yieldToSelector:@selector(invoke)];
5350 [self setTitle:@"COMPLETE"];
5355 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5358 MMap mmap(file, MMap::ReadOnly);
5360 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5361 if (!(notifyconf == sha1.Result()))
5368 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5371 MMap mmap(file, MMap::ReadOnly);
5373 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5374 if (!(springlist == sha1.Result()))
5380 if (RestartSubstrate_)
5384 RestartSubstrate_ = false;
5387 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5388 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5389 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5390 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5391 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5395 system("su -c /usr/bin/uicache mobile");
5398 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5400 [progress_ setRunning:false];
5401 [self updateProgress];
5403 [self applyRightButton];
5406 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5407 [progress_ addEvent:event];
5408 [self updateProgress];
5411 - (bool) isProgressCancelled {
5412 return cancel_ == 2;
5417 [self updateCancel];
5420 - (void) setCancellable:(bool)cancellable {
5421 unsigned cancel(cancel_);
5425 else if (cancel_ == 0)
5428 if (cancel != cancel_)
5429 [self updateCancel];
5432 - (void) setProgressCancellable:(NSNumber *)cancellable {
5433 [self setCancellable:[cancellable boolValue]];
5436 - (void) setProgressPercent:(NSNumber *)percent {
5437 [progress_ setPercent:[percent floatValue]];
5438 [self updateProgress];
5441 - (void) setProgressStatus:(NSDictionary *)status {
5442 if (status == nil) {
5443 [progress_ setCurrent:0];
5444 [progress_ setTotal:0];
5445 [progress_ setSpeed:0];
5447 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5449 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5450 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5451 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5454 [self updateProgress];
5460 /* Cell Content View {{{ */
5461 @protocol ContentDelegate
5462 - (void) drawContentRect:(CGRect)rect;
5465 @interface ContentView : UIView {
5466 _transient id<ContentDelegate> delegate_;
5471 @implementation ContentView
5473 - (id) initWithFrame:(CGRect)frame {
5474 if ((self = [super initWithFrame:frame]) != nil) {
5475 [self setNeedsDisplayOnBoundsChange:YES];
5479 - (void) setDelegate:(id<ContentDelegate>)delegate {
5480 delegate_ = delegate;
5483 - (void) drawRect:(CGRect)rect {
5484 [super drawRect:rect];
5485 [delegate_ drawContentRect:rect];
5490 /* Cydia TableView Cell {{{ */
5491 @interface CYTableViewCell : UITableViewCell {
5492 ContentView *content_;
5498 @implementation CYTableViewCell
5505 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5506 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5508 if (view == content_) {
5509 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5510 highlighted_ = highlighted;
5513 [super _updateHighlightColorsForView:view highlighted:highlighted];
5516 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5517 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5518 highlighted_ = selected;
5520 [super setSelected:selected animated:animated];
5521 [content_ setNeedsDisplay];
5527 /* Package Cell {{{ */
5528 @interface PackageCell : CYTableViewCell <
5533 NSString *description_;
5541 - (PackageCell *) init;
5542 - (void) setPackage:(Package *)package;
5544 - (void) drawContentRect:(CGRect)rect;
5548 @implementation PackageCell
5550 - (void) clearPackage {
5561 if (description_ != nil) {
5562 [description_ release];
5566 if (source_ != nil) {
5571 if (badge_ != nil) {
5576 if (placard_ != nil) {
5586 [self clearPackage];
5590 - (PackageCell *) init {
5591 CGRect frame(CGRectMake(0, 0, 320, 74));
5592 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5593 UIView *content([self contentView]);
5594 CGRect bounds([content bounds]);
5596 content_ = [[ContentView alloc] initWithFrame:bounds];
5597 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5598 [content addSubview:content_];
5600 [content_ setDelegate:self];
5601 [content_ setOpaque:YES];
5605 - (NSString *) accessibilityLabel {
5606 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5609 - (void) setPackage:(Package *)package {
5610 [self clearPackage];
5613 Source *source = [package source];
5615 icon_ = [[package icon] retain];
5616 name_ = [[package name] retain];
5619 description_ = [package longDescription];
5620 if (description_ == nil)
5621 description_ = [package shortDescription];
5622 if (description_ != nil)
5623 description_ = [description_ retain];
5625 commercial_ = [package isCommercial];
5627 package_ = [package retain];
5629 NSString *label = nil;
5630 bool trusted = false;
5632 if (source != nil) {
5633 label = [source label];
5634 trusted = [source trusted];
5635 } else if ([[package id] isEqualToString:@"firmware"])
5636 label = UCLocalize("APPLE");
5638 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5640 NSString *from(label);
5642 NSString *section = [package simpleSection];
5643 if (section != nil && ![section isEqualToString:label]) {
5644 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5645 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5648 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5649 source_ = [from retain];
5651 if (NSString *purpose = [package primaryPurpose])
5652 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5653 badge_ = [badge_ retain];
5658 if (NSString *mode = [package_ mode]) {
5659 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5660 color = RemovingColor_;
5661 //placard = @"removing";
5663 color = InstallingColor_;
5664 //placard = @"installing";
5667 // XXX: the removing/installing placards are not @2x
5670 color = [UIColor whiteColor];
5672 if ([package installed] != nil)
5673 placard = @"installed";
5678 [content_ setBackgroundColor:color];
5681 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5682 placard_ = [placard_ retain];
5684 [self setNeedsDisplay];
5685 [content_ setNeedsDisplay];
5688 - (void) drawContentRect:(CGRect)rect {
5689 bool highlighted(highlighted_);
5690 float width([self bounds].size.width);
5693 CGContextRef context(UIGraphicsGetCurrentContext());
5694 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5695 CGContextFillRect(context, rect);
5700 rect.size = [icon_ size];
5702 rect.size.width /= 2;
5703 rect.size.height /= 2;
5705 rect.origin.x = 25 - rect.size.width / 2;
5706 rect.origin.y = 25 - rect.size.height / 2;
5708 [icon_ drawInRect:rect];
5711 if (badge_ != nil) {
5713 rect.size = [badge_ size];
5715 rect.size.width /= 2;
5716 rect.size.height /= 2;
5718 rect.origin.x = 36 - rect.size.width / 2;
5719 rect.origin.y = 36 - rect.size.height / 2;
5721 [badge_ drawInRect:rect];
5728 UISetColor(commercial_ ? Purple_ : Black_);
5729 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5730 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5733 UISetColor(commercial_ ? Purplish_ : Gray_);
5734 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5736 if (placard_ != nil)
5737 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5742 /* Section Cell {{{ */
5743 @interface SectionCell : CYTableViewCell <
5755 - (void) setSection:(Section *)section editing:(BOOL)editing;
5759 @implementation SectionCell
5761 - (void) clearSection {
5762 if (basic_ != nil) {
5767 if (section_ != nil) {
5777 if (count_ != nil) {
5784 [self clearSection];
5790 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5791 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5792 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5793 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5794 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5796 UIView *content([self contentView]);
5797 CGRect bounds([content bounds]);
5799 content_ = [[ContentView alloc] initWithFrame:bounds];
5800 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5801 [content addSubview:content_];
5802 [content_ setBackgroundColor:[UIColor whiteColor]];
5804 [content_ setDelegate:self];
5808 - (void) onSwitch:(id)sender {
5809 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5810 if (metadata == nil) {
5811 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5812 [Sections_ setObject:metadata forKey:basic_];
5815 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5819 - (void) setSection:(Section *)section editing:(BOOL)editing {
5820 if (editing != editing_) {
5822 [switch_ removeFromSuperview];
5824 [self addSubview:switch_];
5828 [self clearSection];
5830 if (section == nil) {
5831 name_ = [UCLocalize("ALL_PACKAGES") retain];
5834 basic_ = [section name];
5836 basic_ = [basic_ retain];
5838 section_ = [section localized];
5839 if (section_ != nil)
5840 section_ = [section_ retain];
5842 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5843 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5846 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5849 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5850 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5852 [content_ setNeedsDisplay];
5855 - (void) setFrame:(CGRect)frame {
5856 [super setFrame:frame];
5858 CGRect rect([switch_ frame]);
5859 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5862 - (NSString *) accessibilityLabel {
5866 - (void) drawContentRect:(CGRect)rect {
5867 bool highlighted(highlighted_ && !editing_);
5869 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5874 float width(rect.size.width);
5880 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5882 CGSize size = [count_ sizeWithFont:Font14_];
5886 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5892 /* File Table {{{ */
5893 @interface FileTable : CYViewController <
5894 UITableViewDataSource,
5897 _transient Database *database_;
5900 NSMutableArray *files_;
5904 - (id) initWithDatabase:(Database *)database;
5905 - (void) setPackage:(Package *)package;
5909 @implementation FileTable
5912 [self releaseSubviews];
5921 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5922 return files_ == nil ? 0 : [files_ count];
5925 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5929 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5930 static NSString *reuseIdentifier = @"Cell";
5932 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5934 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5935 [cell setFont:[UIFont systemFontOfSize:16]];
5937 [cell setText:[files_ objectAtIndex:indexPath.row]];
5938 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5943 - (NSURL *) navigationURL {
5944 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5948 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5950 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5951 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5952 [list_ setRowHeight:24.0f];
5953 [list_ setDataSource:self];
5954 [list_ setDelegate:self];
5955 [[self view] addSubview:list_];
5958 - (void) viewDidLoad {
5959 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5962 - (void) releaseSubviews {
5967 - (id) initWithDatabase:(Database *)database {
5968 if ((self = [super init]) != nil) {
5969 database_ = database;
5971 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5975 - (void) setPackage:(Package *)package {
5976 if (package_ != nil) {
5977 [package_ autorelease];
5986 [files_ removeAllObjects];
5988 if (package != nil) {
5989 package_ = [package retain];
5990 name_ = [[package id] retain];
5992 if (NSArray *files = [package files])
5993 [files_ addObjectsFromArray:files];
5995 if ([files_ count] != 0) {
5996 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5997 [files_ removeObjectAtIndex:0];
5998 [files_ sortUsingSelector:@selector(compareByPath:)];
6000 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6001 [stack addObject:@"/"];
6003 for (int i(0), e([files_ count]); i != e; ++i) {
6004 NSString *file = [files_ objectAtIndex:i];
6005 while (![file hasPrefix:[stack lastObject]])
6006 [stack removeLastObject];
6007 NSString *directory = [stack lastObject];
6008 [stack addObject:[file stringByAppendingString:@"/"]];
6009 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6010 ([stack count] - 2) * 3, "",
6011 [file substringFromIndex:[directory length]]
6020 - (void) reloadData {
6023 [self setPackage:[database_ packageWithName:name_]];
6028 /* Package Controller {{{ */
6029 @interface CYPackageController : CYBrowserController <
6030 UIActionSheetDelegate
6032 _transient Database *database_;
6033 _H<Package> package_;
6036 _H<NSMutableArray> buttons_;
6037 _H<UIBarButtonItem> button_;
6040 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
6044 @implementation CYPackageController
6046 - (NSURL *) navigationURL {
6047 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6050 /* XXX: this is not safe at all... localization of /fail/ */
6051 - (void) _clickButtonWithName:(NSString *)name {
6052 if ([name isEqualToString:UCLocalize("CLEAR")])
6053 [delegate_ clearPackage:package_];
6054 else if ([name isEqualToString:UCLocalize("INSTALL")])
6055 [delegate_ installPackage:package_];
6056 else if ([name isEqualToString:UCLocalize("REINSTALL")])
6057 [delegate_ installPackage:package_];
6058 else if ([name isEqualToString:UCLocalize("REMOVE")])
6059 [delegate_ removePackage:package_];
6060 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6061 [delegate_ installPackage:package_];
6062 else _assert(false);
6065 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6066 NSString *context([sheet context]);
6068 if ([context isEqualToString:@"modify"]) {
6069 if (button != [sheet cancelButtonIndex]) {
6070 NSString *buttonName = [buttons_ objectAtIndex:button];
6071 [self _clickButtonWithName:buttonName];
6074 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6078 - (bool) _allowJavaScriptPanel {
6083 - (void) _customButtonClicked {
6084 int count([buttons_ count]);
6089 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6091 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6092 [buttons addObjectsFromArray:buttons_];
6094 UIActionSheet *sheet = [[[UIActionSheet alloc]
6097 cancelButtonTitle:nil
6098 destructiveButtonTitle:nil
6099 otherButtonTitles:nil
6102 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6104 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6105 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6107 [sheet setContext:@"modify"];
6109 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6113 // We don't want to allow non-commercial packages to do custom things to the install button,
6114 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6115 - (void) customButtonClicked {
6117 [super customButtonClicked];
6119 [self _customButtonClicked];
6122 - (void) reloadButtonClicked {
6123 // Don't reload a commerical package by tapping the loading button,
6124 // but if it's not an Install button, we should forward it on.
6125 if (![package_ uninstalled])
6126 [self _customButtonClicked];
6129 - (void) applyLoadingTitle {
6130 // Don't show "Loading" as the title. Ever.
6133 - (UIBarButtonItem *) rightButton {
6138 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
6139 if ((self = [super init]) != nil) {
6140 database_ = database;
6141 buttons_ = [NSMutableArray arrayWithCapacity:4];
6142 name_ = [NSString stringWithString:name];
6143 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
6147 - (void) reloadData {
6148 package_ = [database_ packageWithName:name_];
6150 [buttons_ removeAllObjects];
6152 if (package_ != nil) {
6153 [(Package *) package_ parse];
6155 commercial_ = [package_ isCommercial];
6157 if ([package_ mode] != nil)
6158 [buttons_ addObject:UCLocalize("CLEAR")];
6159 if ([package_ source] == nil);
6160 else if ([package_ upgradableAndEssential:NO])
6161 [buttons_ addObject:UCLocalize("UPGRADE")];
6162 else if ([package_ uninstalled])
6163 [buttons_ addObject:UCLocalize("INSTALL")];
6165 [buttons_ addObject:UCLocalize("REINSTALL")];
6166 if (![package_ uninstalled])
6167 [buttons_ addObject:UCLocalize("REMOVE")];
6171 switch ([buttons_ count]) {
6172 case 0: title = nil; break;
6173 case 1: title = [buttons_ objectAtIndex:0]; break;
6174 default: title = UCLocalize("MODIFY"); break;
6177 button_ = [[[UIBarButtonItem alloc]
6179 style:UIBarButtonItemStylePlain
6181 action:@selector(customButtonClicked)
6187 - (bool) isLoading {
6188 return commercial_ ? [super isLoading] : false;
6194 /* Package List Controller {{{ */
6195 @interface PackageListController : CYViewController <
6196 UITableViewDataSource,
6199 _transient Database *database_;
6201 NSMutableArray *packages_;
6202 NSMutableArray *sections_;
6204 NSMutableArray *index_;
6205 NSMutableDictionary *indices_;
6209 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6210 - (void) setDelegate:(id)delegate;
6211 - (void) resetCursor;
6215 @implementation PackageListController
6218 [packages_ release];
6219 [sections_ release];
6228 - (void) deselectWithAnimation:(BOOL)animated {
6229 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6232 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6233 CGRect base = [[self view] bounds];
6234 base.size.height -= bounds.size.height;
6235 base.origin = [list_ frame].origin;
6237 [UIView beginAnimations:nil context:NULL];
6238 [UIView setAnimationBeginsFromCurrentState:YES];
6239 [UIView setAnimationCurve:curve];
6240 [UIView setAnimationDuration:duration];
6241 [list_ setFrame:base];
6242 [UIView commitAnimations];
6245 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6246 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6249 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6250 [self resizeForKeyboardBounds:bounds duration:0];
6253 - (void) keyboardWillShow:(NSNotification *)notification {
6256 NSTimeInterval duration;
6257 UIViewAnimationCurve curve;
6258 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6259 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6260 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6261 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6263 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);
6264 UIViewController *base = self;
6265 while ([base parentViewController] != nil)
6266 base = [base parentViewController];
6267 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6268 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6270 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6273 - (void) keyboardWillHide:(NSNotification *)notification {
6274 NSTimeInterval duration;
6275 UIViewAnimationCurve curve;
6276 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6277 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6279 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6282 - (void) viewWillAppear:(BOOL)animated {
6283 [super viewWillAppear:animated];
6285 [self resizeForKeyboardBounds:CGRectZero];
6286 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6287 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6290 - (void) viewWillDisappear:(BOOL)animated {
6291 [super viewWillDisappear:animated];
6293 [self resizeForKeyboardBounds:CGRectZero];
6294 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6295 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6298 - (void) viewDidAppear:(BOOL)animated {
6299 [super viewDidAppear:animated];
6300 [self deselectWithAnimation:animated];
6303 - (void) didSelectPackage:(Package *)package {
6304 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6305 [view setDelegate:delegate_];
6306 [[self navigationController] pushViewController:view animated:YES];
6309 #if TryIndexedCollation
6310 + (BOOL) hasIndexedCollation {
6311 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6315 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6316 NSInteger count([sections_ count]);
6317 return count == 0 ? 1 : count;
6320 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6321 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6323 return [[sections_ objectAtIndex:section] name];
6326 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6327 if ([sections_ count] == 0)
6329 return [[sections_ objectAtIndex:section] count];
6332 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6333 @synchronized (database_) {
6334 if ([database_ era] != era_)
6337 Section *section([sections_ objectAtIndex:[path section]]);
6338 NSInteger row([path row]);
6339 Package *package([packages_ objectAtIndex:([section row] + row)]);
6340 return [[package retain] autorelease];
6343 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6344 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6346 cell = [[[PackageCell alloc] init] autorelease];
6347 [cell setPackage:[self packageAtIndexPath:path]];
6351 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6352 Package *package([self packageAtIndexPath:path]);
6353 package = [database_ packageWithName:[package id]];
6354 [self didSelectPackage:package];
6357 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6358 // XXX: is 20 the most optimal number here?
6359 return [packages_ count] > 20 ? index_ : nil;
6362 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6363 #if TryIndexedCollation
6364 if ([[self class] hasIndexedCollation]) {
6365 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6372 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6373 if ((self = [super init]) != nil) {
6374 database_ = database;
6375 title_ = [title copy];
6376 [[self navigationItem] setTitle:title_];
6378 #if TryIndexedCollation
6379 if ([[self class] hasIndexedCollation])
6380 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6383 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6385 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6387 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6388 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6390 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6391 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6392 [list_ setRowHeight:73];
6393 [[self view] addSubview:list_];
6395 [list_ setDataSource:self];
6396 [list_ setDelegate:self];
6400 - (void) setDelegate:(id)delegate {
6401 delegate_ = delegate;
6404 - (bool) hasPackage:(Package *)package {
6408 - (void) reloadData {
6411 era_ = [database_ era];
6412 NSArray *packages = [database_ packages];
6414 [packages_ removeAllObjects];
6415 [sections_ removeAllObjects];
6417 _profile(PackageTable$reloadData$Filter)
6418 for (Package *package in packages)
6419 if ([self hasPackage:package])
6420 [packages_ addObject:package];
6423 [indices_ removeAllObjects];
6425 Section *section = nil;
6427 #if TryIndexedCollation
6428 if ([[self class] hasIndexedCollation]) {
6429 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6430 NSArray *titles = [collation sectionIndexTitles];
6433 _profile(PackageTable$reloadData$Section)
6434 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6438 _profile(PackageTable$reloadData$Section$Package)
6439 package = [packages_ objectAtIndex:offset];
6440 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6443 while (secidx < index) {
6446 _profile(PackageTable$reloadData$Section$Allocate)
6447 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6450 _profile(PackageTable$reloadData$Section$Add)
6451 [sections_ addObject:section];
6455 [section addToCount];
6461 [index_ removeAllObjects];
6463 _profile(PackageTable$reloadData$Section)
6464 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6468 _profile(PackageTable$reloadData$Section$Package)
6469 package = [packages_ objectAtIndex:offset];
6470 index = [package index];
6473 if (section == nil || [section index] != index) {
6474 _profile(PackageTable$reloadData$Section$Allocate)
6475 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6478 [index_ addObject:[section name]];
6479 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6481 _profile(PackageTable$reloadData$Section$Add)
6482 [sections_ addObject:section];
6486 [section addToCount];
6491 _profile(PackageTable$reloadData$List)
6496 - (void) resetCursor {
6497 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6502 /* Filtered Package List Controller {{{ */
6503 @interface FilteredPackageListController : PackageListController {
6509 - (void) setObject:(id)object;
6510 - (void) setObject:(id)object forFilter:(SEL)filter;
6512 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6516 @implementation FilteredPackageListController
6524 - (void) setFilter:(SEL)filter {
6527 /* XXX: this is an unsafe optimization of doomy hell */
6528 Method method(class_getInstanceMethod([Package class], filter));
6529 _assert(method != NULL);
6530 imp_ = method_getImplementation(method);
6531 _assert(imp_ != NULL);
6534 - (void) setObject:(id)object {
6540 object_ = [object retain];
6543 - (void) setObject:(id)object forFilter:(SEL)filter {
6544 [self setFilter:filter];
6545 [self setObject:object];
6548 - (bool) hasPackage:(Package *)package {
6549 _profile(FilteredPackageTable$hasPackage)
6550 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6554 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6555 if ((self = [super initWithDatabase:database title:title]) != nil) {
6556 [self setFilter:filter];
6557 [self setObject:object];
6564 /* Home Controller {{{ */
6565 @interface HomeController : CYBrowserController {
6570 @implementation HomeController
6573 if ((self = [super init]) != nil) {
6574 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6578 - (NSURL *) navigationURL {
6579 return [NSURL URLWithString:@"cydia://home"];
6582 - (void) aboutButtonClicked {
6583 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6585 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6586 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6587 [alert setCancelButtonIndex:0];
6590 @"Copyright (C) 2008-2011\n"
6591 "Jay Freeman (saurik)\n"
6592 "saurik@saurik.com\n"
6593 "http://www.saurik.com/"
6599 - (void) viewDidLoad {
6600 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6601 initWithTitle:UCLocalize("ABOUT")
6602 style:UIBarButtonItemStylePlain
6604 action:@selector(aboutButtonClicked)
6610 /* Manage Controller {{{ */
6611 @interface ManageController : CYBrowserController {
6614 - (void) queueStatusDidChange;
6618 @implementation ManageController
6621 if ((self = [super init]) != nil) {
6622 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6626 - (NSURL *) navigationURL {
6627 return [NSURL URLWithString:@"cydia://manage"];
6630 - (void) viewDidLoad {
6631 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6632 initWithTitle:UCLocalize("SETTINGS")
6633 style:UIBarButtonItemStylePlain
6635 action:@selector(settingsButtonClicked)
6638 [self queueStatusDidChange];
6641 - (void) settingsButtonClicked {
6642 [delegate_ showSettings];
6646 - (void) queueButtonClicked {
6650 - (void) applyLoadingTitle {
6651 // Disable "Loading" title.
6654 - (void) applyRightButton {
6655 // Disable right button.
6659 - (void) queueStatusDidChange {
6661 if (!IsWildcat_ && Queuing_) {
6662 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6663 initWithTitle:UCLocalize("QUEUE")
6664 style:UIBarButtonItemStyleDone
6666 action:@selector(queueButtonClicked)
6669 [[self navigationItem] setRightBarButtonItem:nil];
6674 - (bool) isLoading {
6675 // Never show as loading.
6682 /* Refresh Bar {{{ */
6683 @interface RefreshBar : UINavigationBar {
6684 UIProgressIndicator *indicator_;
6685 UITextLabel *prompt_;
6686 UIProgressBar *progress_;
6687 UINavigationButton *cancel_;
6692 @implementation RefreshBar
6695 [indicator_ release];
6697 [progress_ release];
6702 - (void) positionViews {
6703 CGRect frame = [cancel_ frame];
6704 frame.size = [cancel_ sizeThatFits:frame.size];
6705 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6706 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6707 [cancel_ setFrame:frame];
6709 CGSize prgsize = {75, 100};
6711 [self frame].size.width - prgsize.width - 10,
6712 ([self frame].size.height - prgsize.height) / 2
6714 [progress_ setFrame:prgrect];
6716 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6717 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6718 CGRect indrect = {{indoffset, indoffset}, indsize};
6719 [indicator_ setFrame:indrect];
6721 CGSize prmsize = {215, indsize.height + 4};
6723 indoffset * 2 + indsize.width,
6724 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6726 [prompt_ setFrame:prmrect];
6729 - (void) setFrame:(CGRect)frame {
6730 [super setFrame:frame];
6731 [self positionViews];
6734 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6735 if ((self = [super initWithFrame:frame]) != nil) {
6736 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6738 [self setBarStyle:UIBarStyleBlack];
6740 UIBarStyle barstyle([self _barStyle:NO]);
6741 bool ugly(barstyle == UIBarStyleDefault);
6743 UIProgressIndicatorStyle style = ugly ?
6744 UIProgressIndicatorStyleMediumBrown :
6745 UIProgressIndicatorStyleMediumWhite;
6747 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6748 [indicator_ setStyle:style];
6749 [indicator_ startAnimation];
6750 [self addSubview:indicator_];
6752 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6753 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6754 [prompt_ setBackgroundColor:[UIColor clearColor]];
6755 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6756 [self addSubview:prompt_];
6758 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6759 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6760 [progress_ setStyle:0];
6761 [self addSubview:progress_];
6763 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6764 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6765 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6766 [cancel_ setBarStyle:barstyle];
6768 [self positionViews];
6772 - (void) setCancellable:(bool)cancellable {
6774 [self addSubview:cancel_];
6776 [cancel_ removeFromSuperview];
6780 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6781 [progress_ setProgress:0];
6785 [self setCancellable:NO];
6788 - (void) setPrompt:(NSString *)prompt {
6789 [prompt_ setText:prompt];
6792 - (void) setProgress:(float)progress {
6793 [progress_ setProgress:progress];
6799 @class CYNavigationController;
6801 /* Cydia Tab Bar Controller {{{ */
6802 @interface CYTabBarController : UITabBarController <
6803 UITabBarControllerDelegate,
6806 _transient Database *database_;
6807 RefreshBar *refreshbar_;
6811 // XXX: ok, "updatedelegate_"?...
6812 _transient NSObject<CydiaDelegate> *updatedelegate_;
6815 UIViewController *remembered_;
6816 _transient UIViewController *transient_;
6819 - (NSArray *) navigationURLCollection;
6820 - (void) dropBar:(BOOL)animated;
6821 - (void) beginUpdate;
6822 - (void) raiseBar:(BOOL)animated;
6827 @implementation CYTabBarController
6829 - (void) setUnselectedViewController:(UIViewController *)transient {
6830 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6831 if (transient != nil) {
6832 if (transient_ == nil)
6833 remembered_ = [[controllers objectAtIndex:0] retain];
6834 transient_ = transient;
6835 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6836 [controllers replaceObjectAtIndex:0 withObject:transient_];
6837 [self setSelectedIndex:0];
6838 [self setViewControllers:controllers];
6839 [self concealTabBarSelection];
6840 } else if (remembered_ != nil) {
6841 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6842 transient_ = transient;
6843 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6844 [remembered_ release];
6846 [self setViewControllers:controllers];
6847 [self revealTabBarSelection];
6851 - (UIViewController *) unselectedViewController {
6855 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6856 if ([self unselectedViewController])
6857 [self setUnselectedViewController:nil];
6860 - (NSArray *) navigationURLCollection {
6861 NSMutableArray *items([NSMutableArray array]);
6863 // XXX: Should this deal with transient view controllers?
6864 for (id navigation in [self viewControllers]) {
6865 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6867 [items addObject:stack];
6873 - (void) reloadData {
6874 for (CYViewController *controller in [self viewControllers])
6875 [controller reloadData];
6877 [(CYNavigationController *)[self unselectedViewController] reloadData];
6881 [refreshbar_ release];
6882 [[NSNotificationCenter defaultCenter] removeObserver:self];
6887 - (id) initWithDatabase:(Database *)database {
6888 if ((self = [super init]) != nil) {
6889 database_ = database;
6890 [self setDelegate:self];
6892 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6893 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6895 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6899 - (void) setUpdate:(NSDate *)date {
6903 - (void) beginUpdate {
6904 [refreshbar_ start];
6907 [updatedelegate_ retainNetworkActivityIndicator];
6911 detachNewThreadSelector:@selector(performUpdate)
6917 - (void) performUpdate { _pooled
6919 status.setDelegate(self);
6920 [database_ updateWithStatus:status];
6923 performSelectorOnMainThread:@selector(completeUpdate)
6929 - (void) stopUpdateWithSelector:(SEL)selector {
6931 [updatedelegate_ releaseNetworkActivityIndicator];
6933 [self raiseBar:YES];
6936 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6939 - (void) completeUpdate {
6942 [self stopUpdateWithSelector:@selector(reloadData)];
6945 - (void) cancelUpdate {
6946 [self stopUpdateWithSelector:@selector(updateData)];
6949 - (void) cancelPressed {
6950 [self cancelUpdate];
6957 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6958 [refreshbar_ setPrompt:[event compoundMessage]];
6961 - (bool) isProgressCancelled {
6965 - (void) setProgressCancellable:(NSNumber *)cancellable {
6966 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6969 - (void) setProgressPercent:(NSNumber *)percent {
6970 [refreshbar_ setProgress:[percent floatValue]];
6973 - (void) setProgressStatus:(NSDictionary *)status {
6975 [self setProgressPercent:[status objectForKey:@"Percent"]];
6978 - (void) setUpdateDelegate:(id)delegate {
6979 updatedelegate_ = delegate;
6982 - (CGFloat) statusBarHeight {
6983 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6984 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6986 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6990 - (UIView *) transitionView {
6991 if ([self respondsToSelector:@selector(_transitionView)])
6992 return [self _transitionView];
6994 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6997 - (void) dropBar:(BOOL)animated {
7002 UIView *transition([self transitionView]);
7003 [[self view] addSubview:refreshbar_];
7005 CGRect barframe([refreshbar_ frame]);
7007 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
7008 barframe.origin.y = [self statusBarHeight];
7010 barframe.origin.y = 0;
7012 [refreshbar_ setFrame:barframe];
7015 [UIView beginAnimations:nil context:NULL];
7017 CGRect viewframe = [transition frame];
7018 viewframe.origin.y += barframe.size.height;
7019 viewframe.size.height -= barframe.size.height;
7020 [transition setFrame:viewframe];
7023 [UIView commitAnimations];
7025 // Ensure bar has the proper width for our view, it might have changed
7026 barframe.size.width = viewframe.size.width;
7027 [refreshbar_ setFrame:barframe];
7029 // XXX: fix Apple's layout bug
7030 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7033 - (void) raiseBar:(BOOL)animated {
7038 UIView *transition([self transitionView]);
7039 [refreshbar_ removeFromSuperview];
7041 CGRect barframe([refreshbar_ frame]);
7044 [UIView beginAnimations:nil context:NULL];
7046 CGRect viewframe = [transition frame];
7047 viewframe.origin.y -= barframe.size.height;
7048 viewframe.size.height += barframe.size.height;
7049 [transition setFrame:viewframe];
7052 [UIView commitAnimations];
7054 // XXX: fix Apple's layout bug
7055 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7059 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7060 // XXX: fix Apple's layout bug
7061 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7065 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7066 bool dropped(dropped_);
7071 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7076 // XXX: fix Apple's layout bug
7077 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7080 - (void) statusBarFrameChanged:(NSNotification *)notification {
7089 /* Cydia Navigation Controller {{{ */
7090 @interface CYNavigationController : UINavigationController {
7091 _transient Database *database_;
7092 _transient id<UINavigationControllerDelegate> delegate_;
7095 - (NSArray *) navigationURLCollection;
7096 - (id) initWithDatabase:(Database *)database;
7097 - (void) reloadData;
7102 @implementation CYNavigationController
7104 - (NSArray *) navigationURLCollection {
7105 NSMutableArray *stack([NSMutableArray array]);
7107 for (CYViewController *controller in [self viewControllers]) {
7108 NSString *url = [[controller navigationURL] absoluteString];
7110 [stack addObject:url];
7116 - (void) reloadData {
7117 for (CYViewController *page in [self viewControllers]) {
7118 // Only reload controllers that have already loaded.
7119 // This prevents a page from accidentally loading too
7120 // early if it hasn't been shown on the screen yet.
7121 if ([page hasLoaded])
7126 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
7127 delegate_ = delegate;
7130 - (id) initWithDatabase:(Database *)database {
7131 if ((self = [super init]) != nil) {
7132 database_ = database;
7139 /* Cydia:// Protocol {{{ */
7140 @interface CydiaURLProtocol : NSURLProtocol {
7145 @implementation CydiaURLProtocol
7147 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7148 NSURL *url([request URL]);
7152 NSString *scheme([[url scheme] lowercaseString]);
7153 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7155 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7161 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7165 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7166 id<NSURLProtocolClient> client([self client]);
7168 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7170 NSData *data(UIImagePNGRepresentation(icon));
7172 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7173 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7174 [client URLProtocol:self didLoadData:data];
7175 [client URLProtocolDidFinishLoading:self];
7179 - (void) startLoading {
7180 id<NSURLProtocolClient> client([self client]);
7181 NSURLRequest *request([self request]);
7183 NSURL *url([request URL]);
7184 NSString *href([url absoluteString]);
7185 NSString *scheme([[url scheme] lowercaseString]);
7189 if ([scheme isEqualToString:@"cydia"])
7190 path = [href substringFromIndex:8];
7191 else if ([scheme isEqualToString:@"about"])
7192 path = [href substringFromIndex:12];
7193 else _assert(false);
7195 NSRange slash([path rangeOfString:@"/"]);
7198 if (slash.location == NSNotFound) {
7202 command = [path substringToIndex:slash.location];
7203 path = [path substringFromIndex:(slash.location + 1)];
7206 Database *database([Database sharedInstance]);
7208 if ([command isEqualToString:@"package-icon"]) {
7211 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7212 Package *package([database packageWithName:path]);
7215 UIImage *icon([package icon]);
7216 [self _returnPNGWithImage:icon forRequest:request];
7217 } else if ([command isEqualToString:@"source-icon"]) {
7220 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7221 NSString *source(Simplify(path));
7222 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7224 icon = [UIImage applicationImageNamed:@"unknown.png"];
7225 [self _returnPNGWithImage:icon forRequest:request];
7226 } else if ([command isEqualToString:@"uikit-image"]) {
7229 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7230 UIImage *icon(_UIImageWithName(path));
7231 [self _returnPNGWithImage:icon forRequest:request];
7232 } else if ([command isEqualToString:@"section-icon"]) {
7235 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7236 NSString *section(Simplify(path));
7237 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7239 icon = [UIImage applicationImageNamed:@"unknown.png"];
7240 [self _returnPNGWithImage:icon forRequest:request];
7242 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7246 - (void) stopLoading {
7252 /* Section Controller {{{ */
7253 @interface SectionController : FilteredPackageListController {
7254 _H<NSString> section_;
7257 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7261 @implementation SectionController
7263 - (NSURL *) navigationURL {
7264 NSString *name = section_;
7268 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7271 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7274 title = UCLocalize("ALL_PACKAGES");
7275 else if (![name isEqual:@""])
7276 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7278 title = UCLocalize("NO_SECTION");
7280 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7287 /* Sections Controller {{{ */
7288 @interface SectionsController : CYViewController <
7289 UITableViewDataSource,
7292 _transient Database *database_;
7293 NSMutableArray *sections_;
7294 NSMutableArray *filtered_;
7298 - (id) initWithDatabase:(Database *)database;
7299 - (void) editButtonClicked;
7303 @implementation SectionsController
7306 [self releaseSubviews];
7307 [sections_ release];
7308 [filtered_ release];
7313 - (NSURL *) navigationURL {
7314 return [NSURL URLWithString:@"cydia://sections"];
7317 - (void) updateNavigationItem {
7318 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7319 if ([sections_ count] == 0) {
7320 [[self navigationItem] setRightBarButtonItem:nil];
7322 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7323 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7325 action:@selector(editButtonClicked)
7326 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7330 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7331 [super setEditing:editing animated:animated];
7336 [delegate_ updateData];
7338 [self updateNavigationItem];
7341 - (void) viewDidAppear:(BOOL)animated {
7342 [super viewDidAppear:animated];
7343 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7346 - (void) viewWillDisappear:(BOOL)animated {
7347 [super viewWillDisappear:animated];
7348 if ([self isEditing]) [self setEditing:NO];
7351 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7352 Section *section = nil;
7353 int index = [indexPath row];
7354 if (![self isEditing]) {
7357 section = [filtered_ objectAtIndex:index];
7359 section = [sections_ objectAtIndex:index];
7364 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7365 if ([self isEditing])
7366 return [sections_ count];
7368 return [filtered_ count] + 1;
7371 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7375 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7376 static NSString *reuseIdentifier = @"SectionCell";
7378 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7380 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7382 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7387 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7388 if ([self isEditing])
7391 Section *section = [self sectionAtIndexPath:indexPath];
7393 SectionController *controller = [[[SectionController alloc]
7394 initWithDatabase:database_
7395 section:[section name]
7397 [controller setDelegate:delegate_];
7399 [[self navigationController] pushViewController:controller animated:YES];
7403 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7405 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7406 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7407 [list_ setRowHeight:45.0f];
7408 [list_ setDataSource:self];
7409 [list_ setDelegate:self];
7410 [[self view] addSubview:list_];
7413 - (void) viewDidLoad {
7414 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7417 - (void) releaseSubviews {
7422 - (id) initWithDatabase:(Database *)database {
7423 if ((self = [super init]) != nil) {
7424 database_ = database;
7426 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7427 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7431 - (void) reloadData {
7434 NSArray *packages = [database_ packages];
7436 [sections_ removeAllObjects];
7437 [filtered_ removeAllObjects];
7439 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7442 for (Package *package in packages) {
7443 NSString *name([package section]);
7444 NSString *key(name == nil ? @"" : name);
7448 _profile(SectionsView$reloadData$Section)
7449 section = [sections objectForKey:key];
7450 if (section == nil) {
7451 _profile(SectionsView$reloadData$Section$Allocate)
7452 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7453 [sections setObject:section forKey:key];
7458 [section addToCount];
7460 _profile(SectionsView$reloadData$Filter)
7461 if (![package valid] || ![package visible])
7469 [sections_ addObjectsFromArray:[sections allValues]];
7471 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7473 for (Section *section in sections_) {
7474 size_t count([section row]);
7478 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7479 [section setCount:count];
7480 [filtered_ addObject:section];
7483 [self updateNavigationItem];
7488 - (void) editButtonClicked {
7489 [self setEditing:![self isEditing] animated:YES];
7495 /* Changes Controller {{{ */
7496 @interface ChangesController : CYViewController <
7497 UITableViewDataSource,
7500 _transient Database *database_;
7502 CFMutableArrayRef packages_;
7503 NSMutableArray *sections_;
7506 BOOL hasSentFirstLoad_;
7509 - (id) initWithDatabase:(Database *)database;
7513 @implementation ChangesController
7516 [self releaseSubviews];
7517 CFRelease(packages_);
7518 [sections_ release];
7523 - (NSURL *) navigationURL {
7524 return [NSURL URLWithString:@"cydia://changes"];
7527 - (void) viewWillAppear:(BOOL)animated {
7528 // Loads after it appears, so don't load beforehand.
7530 [super viewWillAppear:animated];
7533 - (void) viewDidAppear:(BOOL)animated {
7534 [super viewDidAppear:animated];
7536 if (!hasSentFirstLoad_) {
7537 hasSentFirstLoad_ = YES;
7538 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7540 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7544 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7545 NSInteger count([sections_ count]);
7546 return count == 0 ? 1 : count;
7549 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7550 if ([sections_ count] == 0)
7552 return [[sections_ objectAtIndex:section] name];
7555 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7556 if ([sections_ count] == 0)
7558 return [[sections_ objectAtIndex:section] count];
7561 - (Package *) packageAtIndex:(NSUInteger)index {
7562 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7565 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7566 @synchronized (database_) {
7567 if ([database_ era] != era_)
7570 NSUInteger sectionIndex([path section]);
7571 if (sectionIndex >= [sections_ count])
7573 Section *section([sections_ objectAtIndex:sectionIndex]);
7574 NSInteger row([path row]);
7575 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7578 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7579 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7581 cell = [[[PackageCell alloc] init] autorelease];
7582 [cell setPackage:[self packageAtIndexPath:path]];
7586 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7587 Package *package([self packageAtIndexPath:path]);
7588 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7589 [view setDelegate:delegate_];
7590 [[self navigationController] pushViewController:view animated:YES];
7594 - (void) refreshButtonClicked {
7595 [delegate_ beginUpdate];
7596 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7599 - (void) upgradeButtonClicked {
7600 [delegate_ distUpgrade];
7604 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7606 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7607 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7608 [list_ setRowHeight:73];
7609 [list_ setDataSource:self];
7610 [list_ setDelegate:self];
7611 [[self view] addSubview:list_];
7614 - (void) viewDidLoad {
7615 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7618 - (void) releaseSubviews {
7623 - (id) initWithDatabase:(Database *)database {
7624 if ((self = [super init]) != nil) {
7625 database_ = database;
7627 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7628 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7632 // this mostly works because reloadData (below) is @synchronized (database_)
7633 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7634 - (void) _reloadPackages:(NSArray *)packages {
7635 CFRelease(packages_);
7636 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7639 _profile(ChangesController$_reloadPackages$Filter)
7640 for (Package *package in packages)
7641 if ([package upgradableAndEssential:YES] || [package visible])
7642 CFArrayAppendValue(packages_, package);
7645 _profile(ChangesController$_reloadPackages$radixSort)
7646 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7651 - (void) reloadData {
7652 @synchronized (database_) {
7653 era_ = [database_ era];
7654 NSArray *packages = [database_ packages];
7656 [sections_ removeAllObjects];
7659 UIProgressHUD *hud([delegate_ addProgressHUD]);
7660 [hud setText:UCLocalize("LOADING")];
7661 //NSLog(@"HUD:%@::%@", delegate_, hud);
7662 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7663 [delegate_ removeProgressHUD:hud];
7665 [self _reloadPackages:packages];
7668 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7669 Section *ignored = nil;
7670 Section *section = nil;
7674 bool unseens = false;
7676 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7678 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7679 Package *package = [self packageAtIndex:offset];
7681 BOOL uae = [package upgradableAndEssential:YES];
7685 time_t seen([package seen]);
7687 if (section == nil || last != seen) {
7691 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7694 _profile(ChangesController$reloadData$Allocate)
7695 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7696 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7697 [sections_ addObject:section];
7701 [section addToCount];
7702 } else if ([package ignored]) {
7703 if (ignored == nil) {
7704 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7706 [ignored addToCount];
7709 [upgradable addToCount];
7714 CFRelease(formatter);
7717 Section *last = [sections_ lastObject];
7718 size_t count = [last count];
7719 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7720 [sections_ removeLastObject];
7723 if ([ignored count] != 0)
7724 [sections_ insertObject:ignored atIndex:0];
7726 [sections_ insertObject:upgradable atIndex:0];
7731 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7732 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7733 style:UIBarButtonItemStylePlain
7735 action:@selector(upgradeButtonClicked)
7738 if (![delegate_ updating])
7739 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7740 initWithTitle:UCLocalize("REFRESH")
7741 style:UIBarButtonItemStylePlain
7743 action:@selector(refreshButtonClicked)
7751 /* Search Controller {{{ */
7752 @interface SearchController : FilteredPackageListController <
7755 _H<UISearchBar> search_;
7759 - (id) initWithDatabase:(Database *)database;
7760 - (void) setSearchTerm:(NSString *)term;
7761 - (void) reloadData;
7765 @implementation SearchController
7768 [search_ setDelegate:nil];
7772 - (NSURL *) navigationURL {
7773 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7774 return [NSURL URLWithString:@"cydia://search"];
7776 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7779 - (void) setSearchTerm:(NSString *)searchTerm {
7780 [search_ setText:searchTerm];
7784 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7785 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7786 [search_ resignFirstResponder];
7790 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7791 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7795 - (id) initWithDatabase:(Database *)database {
7796 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7797 search_ = [[[UISearchBar alloc] init] autorelease];
7798 [search_ setDelegate:self];
7802 - (void) viewDidAppear:(BOOL)animated {
7803 [super viewDidAppear:animated];
7805 if (!searchloaded_) {
7806 searchloaded_ = YES;
7807 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7808 [search_ layoutSubviews];
7809 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7811 UITextField *textField;
7812 if ([search_ respondsToSelector:@selector(searchField)])
7813 textField = [search_ searchField];
7815 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7817 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7818 [textField setEnablesReturnKeyAutomatically:NO];
7819 [[self navigationItem] setTitleView:textField];
7823 - (void) reloadData {
7824 [self setObject:[search_ text]];
7829 - (void) didSelectPackage:(Package *)package {
7830 [search_ resignFirstResponder];
7831 [super didSelectPackage:package];
7836 /* Package Settings Controller {{{ */
7837 @interface PackageSettingsController : CYViewController <
7838 UITableViewDataSource,
7841 _transient Database *database_;
7844 UITableView *table_;
7845 UISwitch *subscribedSwitch_;
7846 UISwitch *ignoredSwitch_;
7847 UITableViewCell *subscribedCell_;
7848 UITableViewCell *ignoredCell_;
7851 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7855 @implementation PackageSettingsController
7858 [self releaseSubviews];
7865 - (NSURL *) navigationURL {
7866 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7869 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7870 if (package_ == nil)
7873 if ([package_ installed] == nil)
7879 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7880 if (package_ == nil)
7883 // both sections contain just one item right now.
7887 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7891 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7893 return UCLocalize("SHOW_ALL_CHANGES_EX");
7895 return UCLocalize("IGNORE_UPGRADES_EX");
7898 - (void) onSubscribed:(id)control {
7899 bool value([control isOn]);
7900 if (package_ == nil)
7902 if ([package_ setSubscribed:value])
7903 [delegate_ updateData];
7906 - (void) _updateIgnored {
7907 const char *package([name_ UTF8String]);
7908 bool on([ignoredSwitch_ isOn]);
7910 pid_t pid(ExecFork());
7912 FILE *dpkg(popen("dpkg --set-selections", "w"));
7913 fwrite(package, strlen(package), 1, dpkg);
7916 fwrite(" hold\n", 6, 1, dpkg);
7918 fwrite(" install\n", 9, 1, dpkg);
7928 int result(waitpid(pid, &status, 0));
7931 _assert(result == pid);
7937 - (void) onIgnored:(id)control {
7938 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7939 [invocation setTarget:self];
7940 [invocation setSelector:@selector(_updateIgnored)];
7942 [delegate_ reloadDataWithInvocation:invocation];
7945 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7946 if (package_ == nil)
7949 switch ([indexPath section]) {
7950 case 0: return subscribedCell_;
7951 case 1: return ignoredCell_;
7960 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7962 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7963 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7964 [table_ setDataSource:self];
7965 [table_ setDelegate:self];
7966 [[self view] addSubview:table_];
7968 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7969 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7970 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7972 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7973 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7974 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7976 subscribedCell_ = [[UITableViewCell alloc] init];
7977 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7978 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7979 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7981 ignoredCell_ = [[UITableViewCell alloc] init];
7982 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7983 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7984 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7987 - (void) viewDidLoad {
7988 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7991 - (void) releaseSubviews {
7992 [ignoredCell_ release];
7995 [subscribedCell_ release];
7996 subscribedCell_ = nil;
8001 [ignoredSwitch_ release];
8002 ignoredSwitch_ = nil;
8004 [subscribedSwitch_ release];
8005 subscribedSwitch_ = nil;
8008 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8009 if ((self = [super init]) != nil) {
8010 database_ = database;
8011 name_ = [package retain];
8015 - (void) reloadData {
8018 if (package_ != nil)
8019 [package_ autorelease];
8020 package_ = [database_ packageWithName:name_];
8022 if (package_ != nil) {
8023 package_ = [package_ retain];
8024 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8025 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8026 } // XXX: what now, G?
8028 [table_ reloadData];
8034 /* Installed Controller {{{ */
8035 @interface InstalledController : FilteredPackageListController {
8039 - (id) initWithDatabase:(Database *)database;
8041 - (void) updateRoleButton;
8042 - (void) queueStatusDidChange;
8046 @implementation InstalledController
8052 - (NSURL *) navigationURL {
8053 return [NSURL URLWithString:@"cydia://installed"];
8056 - (id) initWithDatabase:(Database *)database {
8057 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8058 [self updateRoleButton];
8059 [self queueStatusDidChange];
8064 - (void) queueButtonClicked {
8069 - (void) queueStatusDidChange {
8073 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8074 initWithTitle:UCLocalize("QUEUE")
8075 style:UIBarButtonItemStyleDone
8077 action:@selector(queueButtonClicked)
8080 [[self navigationItem] setLeftBarButtonItem:nil];
8086 - (void) updateRoleButton {
8087 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8088 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8089 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8090 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8092 action:@selector(roleButtonClicked)
8096 - (void) roleButtonClicked {
8097 [self setObject:[NSNumber numberWithBool:expert_]];
8101 [self updateRoleButton];
8107 /* Source Cell {{{ */
8108 @interface SourceCell : CYTableViewCell <
8116 - (void) setSource:(Source *)source;
8120 @implementation SourceCell
8122 - (void) clearSource {
8132 - (void) setSource:(Source *)source {
8136 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
8138 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8139 icon_ = [icon_ retain];
8141 origin_ = [[source name] retain];
8142 label_ = [[source uri] retain];
8144 [content_ setNeedsDisplay];
8152 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8153 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8154 UIView *content([self contentView]);
8155 CGRect bounds([content bounds]);
8157 content_ = [[ContentView alloc] initWithFrame:bounds];
8158 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8159 [content_ setBackgroundColor:[UIColor whiteColor]];
8160 [content addSubview:content_];
8162 [content_ setDelegate:self];
8163 [content_ setOpaque:YES];
8167 - (NSString *) accessibilityLabel {
8171 - (void) drawContentRect:(CGRect)rect {
8172 bool highlighted(highlighted_);
8173 float width(rect.size.width);
8176 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8183 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8187 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8192 /* Source Controller {{{ */
8193 @interface SourceController : FilteredPackageListController {
8194 _transient Source *source_;
8198 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8202 @implementation SourceController
8204 - (NSURL *) navigationURL {
8205 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8208 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8209 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8211 key_ = [[source key] retain];
8215 - (void) reloadData {
8216 source_ = [database_ sourceWithKey:key_];
8218 key_ = [[source_ key] retain];
8219 [self setObject:source_];
8220 [[self navigationItem] setTitle:[source_ label]];
8227 /* Sources Controller {{{ */
8228 @interface SourcesController : CYViewController <
8229 UITableViewDataSource,
8232 _transient Database *database_;
8234 NSMutableArray *sources_;
8238 UIProgressHUD *hud_;
8241 //NSURLConnection *installer_;
8242 NSURLConnection *trivial_;
8243 NSURLConnection *trivial_bz2_;
8244 NSURLConnection *trivial_gz_;
8245 //NSURLConnection *automatic_;
8250 - (id) initWithDatabase:(Database *)database;
8251 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8255 @implementation SourcesController
8257 - (void) _releaseConnection:(NSURLConnection *)connection {
8258 if (connection != nil) {
8259 [connection cancel];
8260 //[connection setDelegate:nil];
8261 [connection release];
8266 [self releaseSubviews];
8272 //[self _releaseConnection:installer_];
8273 [self _releaseConnection:trivial_];
8274 [self _releaseConnection:trivial_gz_];
8275 [self _releaseConnection:trivial_bz2_];
8276 //[self _releaseConnection:automatic_];
8282 - (NSURL *) navigationURL {
8283 return [NSURL URLWithString:@"cydia://sources"];
8286 - (void) viewDidAppear:(BOOL)animated {
8287 [super viewDidAppear:animated];
8288 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8291 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8292 return offset_ == 0 ? 1 : 2;
8295 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8296 switch (section + (offset_ == 0 ? 1 : 0)) {
8297 case 0: return UCLocalize("ENTERED_BY_USER");
8298 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8304 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8305 int count = [sources_ count];
8307 case 0: return (offset_ == 0 ? count : offset_);
8308 case 1: return count - offset_;
8314 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8316 switch (indexPath.section) {
8317 case 0: idx = indexPath.row; break;
8318 case 1: idx = indexPath.row + offset_; break;
8322 return [sources_ objectAtIndex:idx];
8325 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8326 static NSString *cellIdentifier = @"SourceCell";
8328 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8329 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8330 [cell setSource:[self sourceAtIndexPath:indexPath]];
8331 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8336 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8337 Source *source = [self sourceAtIndexPath:indexPath];
8339 SourceController *controller = [[[SourceController alloc]
8340 initWithDatabase:database_
8344 [controller setDelegate:delegate_];
8346 [[self navigationController] pushViewController:controller animated:YES];
8349 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8350 Source *source = [self sourceAtIndexPath:indexPath];
8351 return [source record] != nil;
8354 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8355 Source *source = [self sourceAtIndexPath:indexPath];
8356 [Sources_ removeObjectForKey:[source key]];
8357 [delegate_ syncData];
8361 [delegate_ addTrivialSource:href_];
8362 [delegate_ syncData];
8365 - (NSString *) getWarning {
8366 NSString *href(href_);
8367 NSRange colon([href rangeOfString:@"://"]);
8368 if (colon.location != NSNotFound)
8369 href = [href substringFromIndex:(colon.location + 3)];
8370 href = [href stringByAddingPercentEscapes];
8371 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8372 href = [href stringByCachingURLWithCurrentCDN];
8374 NSURL *url([NSURL URLWithString:href]);
8376 NSStringEncoding encoding;
8377 NSError *error(nil);
8379 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8380 return [warning length] == 0 ? nil : warning;
8384 - (void) _endConnection:(NSURLConnection *)connection {
8385 // XXX: the memory management in this method is horribly awkward
8387 NSURLConnection **field = NULL;
8388 if (connection == trivial_)
8390 else if (connection == trivial_bz2_)
8391 field = &trivial_bz2_;
8392 else if (connection == trivial_gz_)
8393 field = &trivial_gz_;
8394 _assert(field != NULL);
8395 [connection release];
8400 trivial_bz2_ == nil &&
8406 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8409 UIAlertView *alert = [[[UIAlertView alloc]
8410 initWithTitle:UCLocalize("SOURCE_WARNING")
8413 cancelButtonTitle:UCLocalize("CANCEL")
8415 UCLocalize("ADD_ANYWAY"),
8419 [alert setContext:@"warning"];
8420 [alert setNumberOfRows:1];
8424 } else if (error_ != nil) {
8425 UIAlertView *alert = [[[UIAlertView alloc]
8426 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8427 message:[error_ localizedDescription]
8429 cancelButtonTitle:UCLocalize("OK")
8430 otherButtonTitles:nil
8433 [alert setContext:@"urlerror"];
8436 UIAlertView *alert = [[[UIAlertView alloc]
8437 initWithTitle:UCLocalize("NOT_REPOSITORY")
8438 message:UCLocalize("NOT_REPOSITORY_EX")
8440 cancelButtonTitle:UCLocalize("OK")
8441 otherButtonTitles:nil
8444 [alert setContext:@"trivial"];
8448 [delegate_ releaseNetworkActivityIndicator];
8450 [delegate_ removeProgressHUD:hud_];
8459 if (error_ != nil) {
8466 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8467 switch ([response statusCode]) {
8473 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8474 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8476 error_ = [error retain];
8477 [self _endConnection:connection];
8480 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8481 [self _endConnection:connection];
8484 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8485 NSMutableURLRequest *request = [NSMutableURLRequest
8486 requestWithURL:[NSURL URLWithString:href]
8487 cachePolicy:NSURLRequestUseProtocolCachePolicy
8488 timeoutInterval:120.0
8491 [request setHTTPMethod:method];
8493 if (Machine_ != NULL)
8494 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8495 if (UniqueID_ != nil)
8496 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8498 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8501 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8502 NSString *context([alert context]);
8504 if ([context isEqualToString:@"source"]) {
8507 NSString *href = [[alert textField] text];
8509 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8511 if (![href hasSuffix:@"/"])
8512 href_ = [href stringByAppendingString:@"/"];
8515 href_ = [href_ retain];
8517 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8518 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8519 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8520 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8524 // XXX: this is stupid
8525 hud_ = [[delegate_ addProgressHUD] retain];
8526 [hud_ setText:UCLocalize("VERIFYING_URL")];
8527 [delegate_ retainNetworkActivityIndicator];
8536 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8537 } else if ([context isEqualToString:@"trivial"])
8538 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8539 else if ([context isEqualToString:@"urlerror"])
8540 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8541 else if ([context isEqualToString:@"warning"]) {
8556 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8561 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8563 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8564 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8565 [list_ setRowHeight:56];
8566 [list_ setDataSource:self];
8567 [list_ setDelegate:self];
8568 [[self view] addSubview:list_];
8571 - (void) viewDidLoad {
8572 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8573 [self updateButtonsForEditingStatus:NO animated:NO];
8576 - (void) releaseSubviews {
8581 - (id) initWithDatabase:(Database *)database {
8582 if ((self = [super init]) != nil) {
8583 database_ = database;
8584 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8588 - (void) reloadData {
8592 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8595 [sources_ removeAllObjects];
8596 [sources_ addObjectsFromArray:[database_ sources]];
8598 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8601 int count([sources_ count]);
8603 for (int i = 0; i != count; i++) {
8604 if ([[sources_ objectAtIndex:i] record] == nil)
8609 [list_ setEditing:NO];
8610 [self updateButtonsForEditingStatus:NO animated:NO];
8614 - (void) showAddSourcePrompt {
8615 UIAlertView *alert = [[[UIAlertView alloc]
8616 initWithTitle:UCLocalize("ENTER_APT_URL")
8619 cancelButtonTitle:UCLocalize("CANCEL")
8621 UCLocalize("ADD_SOURCE"),
8625 [alert setContext:@"source"];
8626 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8628 [alert setNumberOfRows:1];
8629 [alert addTextFieldWithValue:@"http://" label:@""];
8631 UITextInputTraits *traits = [[alert textField] textInputTraits];
8632 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8633 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8634 [traits setKeyboardType:UIKeyboardTypeURL];
8635 // XXX: UIReturnKeyDone
8636 [traits setReturnKeyType:UIReturnKeyNext];
8641 - (void) addButtonClicked {
8642 [self showAddSourcePrompt];
8645 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8646 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8647 initWithTitle:UCLocalize("ADD")
8648 style:UIBarButtonItemStylePlain
8650 action:@selector(addButtonClicked)
8651 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8653 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8654 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8655 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8657 action:@selector(editButtonClicked)
8658 ] autorelease] animated:animated];
8660 if (IsWildcat_ && !editing)
8661 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8662 initWithTitle:UCLocalize("SETTINGS")
8663 style:UIBarButtonItemStylePlain
8665 action:@selector(settingsButtonClicked)
8669 - (void) settingsButtonClicked {
8670 [delegate_ showSettings];
8673 - (void) editButtonClicked {
8674 [list_ setEditing:![list_ isEditing] animated:YES];
8676 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8682 /* Settings Controller {{{ */
8683 @interface SettingsController : CYViewController <
8684 UITableViewDataSource,
8687 _transient Database *database_;
8688 // XXX: ok, "roledelegate_"?...
8689 _transient id roledelegate_;
8690 UITableView *table_;
8691 UISegmentedControl *segment_;
8695 - (void) showDoneButton;
8696 - (void) resizeSegmentedControl;
8700 @implementation SettingsController
8703 [self releaseSubviews];
8709 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8711 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8712 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8713 [table_ setDelegate:self];
8714 [table_ setDataSource:self];
8715 [[self view] addSubview:table_];
8717 NSArray *items = [NSArray arrayWithObjects:
8719 UCLocalize("HACKER"),
8720 UCLocalize("DEVELOPER"),
8722 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8723 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8724 [container_ addSubview:segment_];
8727 - (void) viewDidLoad {
8728 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8731 if ([Role_ isEqualToString:@"User"]) index = 0;
8732 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8733 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8735 [segment_ setSelectedSegmentIndex:index];
8736 [self showDoneButton];
8739 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8740 [self resizeSegmentedControl];
8743 - (void) releaseSubviews {
8750 [container_ release];
8754 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8755 if ((self = [super init]) != nil) {
8756 database_ = database;
8757 roledelegate_ = delegate;
8761 - (void) resizeSegmentedControl {
8762 CGFloat width = [[self view] frame].size.width;
8763 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8766 - (void) viewWillAppear:(BOOL)animated {
8767 [super viewWillAppear:animated];
8769 [self resizeSegmentedControl];
8772 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8773 [self resizeSegmentedControl];
8776 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8777 [self resizeSegmentedControl];
8781 NSString *role(nil);
8783 switch ([segment_ selectedSegmentIndex]) {
8784 case 0: role = @"User"; break;
8785 case 1: role = @"Hacker"; break;
8786 case 2: role = @"Developer"; break;
8791 if (![role isEqualToString:Role_]) {
8792 bool rolling(Role_ == nil);
8795 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8799 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8803 [roledelegate_ loadData];
8805 [roledelegate_ updateData];
8809 - (void) segmentChanged:(UISegmentedControl *)control {
8810 [self showDoneButton];
8813 - (void) saveAndClose {
8816 [[self navigationItem] setRightBarButtonItem:nil];
8817 [[self navigationController] dismissModalViewControllerAnimated:YES];
8820 - (void) doneButtonClicked {
8821 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8822 [spinner startAnimating];
8823 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8824 [[self navigationItem] setRightBarButtonItem:spinItem];
8826 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8829 - (void) showDoneButton {
8830 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8831 initWithTitle:UCLocalize("DONE")
8832 style:UIBarButtonItemStyleDone
8834 action:@selector(doneButtonClicked)
8835 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8838 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8839 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8843 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8847 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8848 return nil; // This method is required by the protocol.
8851 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8853 return UCLocalize("ROLE_EX");
8855 return [NSString stringWithFormat:
8856 @"%@: %@\n%@: %@\n%@: %@",
8857 UCLocalize("USER"), UCLocalize("USER_EX"),
8858 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8859 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8864 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8865 return section == 3 ? 44.0f : 0;
8868 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8869 return section == 3 ? container_ : nil;
8872 - (void) reloadData {
8874 [table_ reloadData];
8879 /* Stash Controller {{{ */
8880 @interface StashController : CYViewController {
8881 UIActivityIndicatorView *spinner_;
8888 @implementation StashController
8891 [self releaseSubviews];
8897 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8898 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8900 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8901 CGRect spinrect = [spinner_ frame];
8902 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8903 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8904 [spinner_ setFrame:spinrect];
8905 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8906 [[self view] addSubview:spinner_];
8907 [spinner_ startAnimating];
8910 captrect.size.width = [[self view] frame].size.width;
8911 captrect.size.height = 40.0f;
8912 captrect.origin.x = 0;
8913 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8914 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8915 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8916 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8917 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8918 [caption_ setTextColor:[UIColor whiteColor]];
8919 [caption_ setBackgroundColor:[UIColor clearColor]];
8920 [caption_ setShadowColor:[UIColor blackColor]];
8921 [caption_ setTextAlignment:UITextAlignmentCenter];
8922 [[self view] addSubview:caption_];
8925 statusrect.size.width = [[self view] frame].size.width;
8926 statusrect.size.height = 30.0f;
8927 statusrect.origin.x = 0;
8928 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8929 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8930 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8931 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8932 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8933 [status_ setTextColor:[UIColor whiteColor]];
8934 [status_ setBackgroundColor:[UIColor clearColor]];
8935 [status_ setShadowColor:[UIColor blackColor]];
8936 [status_ setTextAlignment:UITextAlignmentCenter];
8937 [[self view] addSubview:status_];
8940 - (void) releaseSubviews {
8954 @interface Cydia : UIApplication <
8955 ConfirmationControllerDelegate,
8958 UINavigationControllerDelegate,
8959 UITabBarControllerDelegate
8961 // XXX: evaluate all fields for _transient
8964 CYTabBarController *tabbar_;
8965 CYEmulatedLoadingController *emulated_;
8967 NSMutableArray *essential_;
8968 NSMutableArray *broken_;
8970 Database *database_;
8977 StashController *stash_;
8986 @implementation Cydia
8988 - (void) beginUpdate {
8989 [tabbar_ beginUpdate];
8993 return [tabbar_ updating];
8997 if ([broken_ count] != 0) {
8998 int count = [broken_ count];
9000 UIAlertView *alert = [[[UIAlertView alloc]
9001 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9002 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9004 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
9006 UCLocalize("TEMPORARY_IGNORE"),
9010 [alert setContext:@"fixhalf"];
9011 [alert setNumberOfRows:2];
9013 } else if (!Ignored_ && [essential_ count] != 0) {
9014 int count = [essential_ count];
9016 UIAlertView *alert = [[[UIAlertView alloc]
9017 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9018 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9020 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9022 UCLocalize("UPGRADE_ESSENTIAL"),
9023 UCLocalize("COMPLETE_UPGRADE"),
9027 [alert setContext:@"upgrade"];
9032 - (void) _saveConfig {
9038 NSString *error(nil);
9040 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9042 NSError *error(nil);
9043 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9044 NSLog(@"failure to save metadata data: %@", error);
9049 NSLog(@"failure to serialize metadata: %@", error);
9054 // Navigation controller for the queuing badge.
9055 - (CYNavigationController *) queueNavigationController {
9056 NSArray *controllers = [tabbar_ viewControllers];
9057 return [controllers objectAtIndex:3];
9060 - (void) _updateData {
9063 [tabbar_ reloadData];
9065 CYNavigationController *navigation = [self queueNavigationController];
9067 id queuedelegate = nil;
9068 if ([[navigation viewControllers] count] > 0)
9069 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9071 [queuedelegate queueStatusDidChange];
9072 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9075 - (void) _refreshIfPossible:(NSDate *)update {
9076 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9078 bool recently = false;
9079 if (update != nil) {
9080 NSTimeInterval interval([update timeIntervalSinceNow]);
9081 if (interval <= 0 && interval > -(15*60))
9085 // Don't automatic refresh if:
9086 // - We already refreshed recently.
9087 // - We already auto-refreshed this launch.
9088 // - Auto-refresh is disabled.
9089 if (recently || loaded_ || ManualRefresh) {
9090 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9092 // If we are cancelling, we need to make sure it knows it's already loaded.
9096 // We are going to load, so remember that.
9100 SCNetworkReachabilityFlags flags; {
9101 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9102 SCNetworkReachabilityGetFlags(reachability, &flags);
9103 CFRelease(reachability);
9106 // XXX: this elaborate mess is what Apple is using to determine this? :(
9107 // XXX: do we care if the user has to intervene? maybe that's ok?
9109 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9110 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9111 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9112 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9113 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9114 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9118 // If we can reach the server, auto-refresh!
9120 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9125 - (void) refreshIfPossible {
9126 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9129 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
9130 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9131 [hud setText:UCLocalize("RELOADING_DATA")];
9133 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9136 [self removeProgressHUD:hud];
9140 [essential_ removeAllObjects];
9141 [broken_ removeAllObjects];
9143 NSArray *packages([database_ packages]);
9144 for (Package *package in packages) {
9146 [broken_ addObject:package];
9147 if ([package upgradableAndEssential:NO]) {
9148 if ([package essential])
9149 [essential_ addObject:package];
9154 NSLog(@"changes:#%u", changes);
9156 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9159 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9160 [changesItem setBadgeValue:badge];
9161 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9162 [self setApplicationIconBadgeNumber:changes];
9165 [changesItem setBadgeValue:nil];
9166 [changesItem setAnimatedBadge:NO];
9167 [self setApplicationIconBadgeNumber:0];
9172 [self refreshIfPossible];
9175 - (void) updateData {
9184 @synchronized (self) {
9185 [self _reloadDataWithInvocation:nil];
9189 - (void) disemulate {
9190 if (emulated_ == nil)
9193 [window_ addSubview:[tabbar_ view]];
9194 [[emulated_ view] removeFromSuperview];
9195 [emulated_ release];
9197 [window_ setUserInteractionEnabled:YES];
9200 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9201 UINavigationController *navigation([[[CYNavigationController alloc] initWithRootViewController:controller] autorelease]);
9203 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9205 UIViewController *parent;
9206 if (emulated_ == nil)
9215 [parent presentModalViewController:navigation animated:YES];
9218 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9219 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9221 if (navigation != nil)
9222 [navigation pushViewController:progress animated:YES];
9224 [self presentModalViewController:progress force:YES];
9226 [progress invoke:invocation withTitle:title];
9230 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9231 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9234 - (void) repairWithInvocation:(NSInvocation *)invocation {
9236 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9240 - (void) repairWithSelector:(SEL)selector {
9241 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9247 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
9248 _assert(file != NULL);
9250 for (NSString *key in [Sources_ allKeys]) {
9251 NSDictionary *source([Sources_ objectForKey:key]);
9253 fprintf(file, "%s %s %s\n",
9254 [[source objectForKey:@"Type"] UTF8String],
9255 [[source objectForKey:@"URI"] UTF8String],
9256 [[source objectForKey:@"Distribution"] UTF8String]
9262 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9267 - (void) addTrivialSource:(NSString *)href {
9268 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
9271 @"./", @"Distribution",
9272 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
9277 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9278 @synchronized (self) {
9279 [self _reloadDataWithInvocation:invocation];
9283 - (void) reloadData {
9284 [self reloadDataWithInvocation:nil];
9288 pkgProblemResolver *resolver = [database_ resolver];
9290 resolver->InstallProtect();
9291 if (!resolver->Resolve(true))
9296 // XXX: this is a really crappy way of doing this.
9297 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9298 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9299 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9300 if ([tabbar_ updating])
9301 [tabbar_ cancelUpdate];
9303 if (![database_ prepare])
9306 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9307 [page setDelegate:self];
9308 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
9309 [confirm_ setDelegate:self];
9312 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9313 [tabbar_ presentModalViewController:confirm_ animated:YES];
9319 @synchronized (self) {
9324 - (void) clearPackage:(Package *)package {
9325 @synchronized (self) {
9332 - (void) installPackages:(NSArray *)packages {
9333 @synchronized (self) {
9334 for (Package *package in packages)
9341 - (void) installPackage:(Package *)package {
9342 @synchronized (self) {
9349 - (void) removePackage:(Package *)package {
9350 @synchronized (self) {
9357 - (void) distUpgrade {
9358 @synchronized (self) {
9359 if (![database_ upgrade])
9365 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9368 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
9373 - (void) showSettings {
9374 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9375 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9377 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9378 [tabbar_ presentModalViewController:nav animated:YES];
9381 - (void) retainNetworkActivityIndicator {
9382 if (activity_++ == 0)
9383 [self setNetworkActivityIndicatorVisible:YES];
9386 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9390 - (void) releaseNetworkActivityIndicator {
9391 if (--activity_ == 0)
9392 [self setNetworkActivityIndicatorVisible:NO];
9395 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9400 - (void) cancelAndClear:(bool)clear {
9401 @synchronized (self) {
9413 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9414 NSString *context([alert context]);
9416 if ([context isEqualToString:@"conffile"]) {
9417 FILE *input = [database_ input];
9418 if (button == [alert cancelButtonIndex])
9419 fprintf(input, "N\n");
9420 else if (button == [alert firstOtherButtonIndex])
9421 fprintf(input, "Y\n");
9424 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9425 } else if ([context isEqualToString:@"fixhalf"]) {
9426 if (button == [alert cancelButtonIndex]) {
9427 @synchronized (self) {
9428 for (Package *broken in broken_) {
9431 NSString *id = [broken id];
9432 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9433 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9434 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9435 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9441 } else if (button == [alert firstOtherButtonIndex]) {
9442 [broken_ removeAllObjects];
9446 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9447 } else if ([context isEqualToString:@"upgrade"]) {
9448 if (button == [alert firstOtherButtonIndex]) {
9449 @synchronized (self) {
9450 for (Package *essential in essential_)
9451 [essential install];
9456 } else if (button == [alert firstOtherButtonIndex] + 1) {
9458 } else if (button == [alert cancelButtonIndex]) {
9462 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9466 - (void) system:(NSString *)command { _pooled
9468 system([command UTF8String]);
9472 - (void) applicationWillSuspend {
9474 [super applicationWillSuspend];
9477 - (BOOL) isSafeToSuspend {
9480 NSLog(@"isSafeToSuspend: locked_ != 0");
9485 // Use external process status API internally.
9486 // This is probably a really bad idea.
9487 // XXX: what is the point of this? does this solve anything at all?
9488 uint64_t status = 0;
9490 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9491 notify_get_state(notify_token, &status);
9492 notify_cancel(notify_token);
9497 NSLog(@"isSafeToSuspend: status != 0");
9503 NSLog(@"isSafeToSuspend: -> true");
9508 - (void) applicationSuspend:(__GSEvent *)event {
9509 if ([self isSafeToSuspend])
9510 [super applicationSuspend:event];
9513 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9514 if ([self isSafeToSuspend])
9515 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9518 - (void) _setSuspended:(BOOL)value {
9519 if ([self isSafeToSuspend])
9520 [super _setSuspended:value];
9523 - (UIProgressHUD *) addProgressHUD {
9524 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9525 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9527 [window_ setUserInteractionEnabled:NO];
9530 UIViewController *target = tabbar_;
9531 while ([target modalViewController] != nil) target = [target modalViewController];
9532 [[target view] addSubview:hud];
9538 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9540 [hud removeFromSuperview];
9541 [window_ setUserInteractionEnabled:YES];
9545 - (CYViewController *) pageForPackage:(NSString *)name {
9546 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9549 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9550 NSString *scheme([[url scheme] lowercaseString]);
9551 if ([[url absoluteString] length] <= [scheme length] + 3)
9553 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9554 NSArray *components([path pathComponents]);
9556 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9557 return [self pageForPackage:[components objectAtIndex:1]];
9559 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9562 NSString *base([components objectAtIndex:0]);
9564 CYViewController *controller = nil;
9566 if ([base isEqualToString:@"url"]) {
9567 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9568 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9569 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9570 } else if (!external && [components count] == 1) {
9571 if ([base isEqualToString:@"manage"]) {
9572 controller = [[[ManageController alloc] init] autorelease];
9575 if ([base isEqualToString:@"sources"]) {
9576 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9579 if ([base isEqualToString:@"home"]) {
9580 controller = [[[HomeController alloc] init] autorelease];
9583 if ([base isEqualToString:@"sections"]) {
9584 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9587 if ([base isEqualToString:@"search"]) {
9588 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9591 if ([base isEqualToString:@"changes"]) {
9592 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9595 if ([base isEqualToString:@"installed"]) {
9596 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9598 } else if ([components count] == 2) {
9599 NSString *argument = [components objectAtIndex:1];
9601 if ([base isEqualToString:@"package"]) {
9602 controller = [self pageForPackage:argument];
9605 if (!external && [base isEqualToString:@"search"]) {
9606 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9607 [(SearchController *)controller setSearchTerm:argument];
9610 if (!external && [base isEqualToString:@"sections"]) {
9611 if ([argument isEqualToString:@"all"])
9613 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9616 if (!external && [base isEqualToString:@"sources"]) {
9617 if ([argument isEqualToString:@"add"]) {
9618 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9619 [(SourcesController *)controller showAddSourcePrompt];
9621 Source *source = [database_ sourceWithKey:argument];
9622 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9626 if (!external && [base isEqualToString:@"launch"]) {
9627 [self launchApplicationWithIdentifier:argument suspended:NO];
9630 } else if (!external && [components count] == 3) {
9631 NSString *arg1 = [components objectAtIndex:1];
9632 NSString *arg2 = [components objectAtIndex:2];
9634 if ([base isEqualToString:@"package"]) {
9635 if ([arg2 isEqualToString:@"settings"]) {
9636 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9637 } else if ([arg2 isEqualToString:@"files"]) {
9638 if (Package *package = [database_ packageWithName:arg1]) {
9639 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9640 [(FileTable *)controller setPackage:package];
9646 [controller setDelegate:self];
9650 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9651 CYViewController *page([self pageForURL:url forExternal:external]);
9654 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9655 [nav setViewControllers:[NSArray arrayWithObject:page]];
9656 [tabbar_ setUnselectedViewController:nav];
9662 - (void) applicationOpenURL:(NSURL *)url {
9663 [super applicationOpenURL:url];
9665 if (!loaded_) starturl_ = [url retain];
9666 else [self openCydiaURL:url forExternal:YES];
9669 - (void) applicationWillResignActive:(UIApplication *)application {
9670 // Stop refreshing if you get a phone call or lock the device.
9671 if ([tabbar_ updating])
9672 [tabbar_ cancelUpdate];
9674 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9675 [super applicationWillResignActive:application];
9678 - (void) applicationWillTerminate:(UIApplication *)application {
9680 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9681 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9682 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9687 - (void) setConfigurationData:(NSString *)data {
9688 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9690 if (!conffile_r(data)) {
9691 lprintf("E:invalid conffile\n");
9695 NSString *ofile = conffile_r[1];
9696 //NSString *nfile = conffile_r[2];
9698 UIAlertView *alert = [[[UIAlertView alloc]
9699 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9700 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9702 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9704 UCLocalize("ACCEPT_NEW_COPY"),
9705 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9709 [alert setContext:@"conffile"];
9710 [alert setNumberOfRows:2];
9714 - (void) addStashController {
9716 stash_ = [[StashController alloc] init];
9717 [window_ addSubview:[stash_ view]];
9720 - (void) removeStashController {
9721 [[stash_ view] removeFromSuperview];
9727 [self setIdleTimerDisabled:YES];
9729 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9730 UpdateExternalStatus(1);
9731 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9732 UpdateExternalStatus(0);
9734 [self removeStashController];
9736 if (ExecFork() == 0) {
9737 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9738 perror("launchctl stop");
9742 - (void) setupViewControllers {
9743 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9745 NSMutableArray *items([NSMutableArray arrayWithObjects:
9746 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9747 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9748 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9749 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9753 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9754 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9756 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9759 NSMutableArray *controllers([NSMutableArray array]);
9760 for (UITabBarItem *item in items) {
9761 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9762 [controller setTabBarItem:item];
9763 [controllers addObject:controller];
9765 [tabbar_ setViewControllers:controllers];
9767 [tabbar_ setUpdateDelegate:self];
9770 - (void) applicationDidFinishLaunching:(id)unused {
9772 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9773 [self setApplicationSupportsShakeToEdit:NO];
9775 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9777 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9778 initWithMemoryCapacity:524288
9779 diskCapacity:10485760
9780 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9783 [CYBrowserController _initialize];
9785 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9787 Font12_ = [[UIFont systemFontOfSize:12] retain];
9788 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9789 Font14_ = [[UIFont systemFontOfSize:14] retain];
9790 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9791 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9793 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9794 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9796 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9797 [window_ orderFront:self];
9798 [window_ makeKey:self];
9799 [window_ setHidden:NO];
9802 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9803 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9804 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9805 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9806 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9807 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9808 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9809 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9810 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9813 [self addStashController];
9814 // XXX: this would be much cleaner as a yieldToSelector:
9815 // that way the removeStashController could happen right here inline
9816 // we also could no longer require the useless stash_ field anymore
9817 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9821 database_ = [Database sharedInstance];
9822 [database_ setDelegate:self];
9824 [window_ setUserInteractionEnabled:NO];
9825 [self setupViewControllers];
9827 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9828 [window_ addSubview:[emulated_ view]];
9830 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9834 - (NSArray *) defaultStartPages {
9835 NSMutableArray *standard = [NSMutableArray array];
9836 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9837 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9838 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9840 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9842 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9843 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9845 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9852 [window_ setUserInteractionEnabled:YES];
9853 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9856 if ([emulated_ modalViewController] != nil)
9857 [emulated_ dismissModalViewControllerAnimated:YES];
9858 [window_ setUserInteractionEnabled:NO];
9866 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9867 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9868 int standardIndex = 0;
9869 NSArray *standard = [self defaultStartPages];
9876 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9877 if (valid && closed != nil) {
9878 NSTimeInterval interval([closed timeIntervalSinceNow]);
9879 // XXX: Is 15 minutes the optimal time here?
9880 if (interval > 0 && interval <= -(15*60))
9884 if (valid && [saved count] != [standard count])
9888 for (unsigned int i = 0; i < [standard count]; i++) {
9889 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9890 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9891 // but it's good enough for now.
9892 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9899 NSArray *items = nil;
9901 [tabbar_ setSelectedIndex:savedIndex];
9904 [tabbar_ setSelectedIndex:standardIndex];
9908 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9909 NSArray *stack = [items objectAtIndex:tab];
9910 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9911 NSMutableArray *current = [NSMutableArray array];
9913 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9914 NSString *addr = [stack objectAtIndex:nav];
9915 NSURL *url = [NSURL URLWithString:addr];
9916 CYViewController *page = [self pageForURL:url forExternal:NO];
9918 [current addObject:page];
9921 [navigation setViewControllers:current];
9924 // (Try to) show the startup URL.
9925 if (starturl_ != nil) {
9926 [self openCydiaURL:starturl_ forExternal:NO];
9927 [starturl_ release];
9932 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9933 if (item != nil && IsWildcat_) {
9934 [sheet showFromBarButtonItem:item animated:YES];
9936 [sheet showInView:window_];
9940 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9941 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9942 [progress setTitle:task];
9943 [progress addProgressEvent:event];
9946 - (void) addProgressEventForTask:(NSArray *)data {
9947 CydiaProgressEvent *event([data objectAtIndex:0]);
9948 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9949 [self addProgressEvent:event forTask:task];
9952 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9953 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9959 id Alloc_(id self, SEL selector) {
9960 id object = alloc_(self, selector);
9961 lprintf("[%s]A-%p\n", self->isa->name, object);
9966 id Dealloc_(id self, SEL selector) {
9967 id object = dealloc_(self, selector);
9968 lprintf("[%s]D-%p\n", self->isa->name, object);
9972 Class $WebDefaultUIKitDelegate;
9974 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9975 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9976 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9977 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9980 static NSNumber *shouldPlayKeyboardSounds;
9984 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9986 case 1104: // Keyboard Button Clicked
9987 case 1105: // Keyboard Delete Repeated
9988 if (shouldPlayKeyboardSounds == nil) {
9989 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9990 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9993 if (![shouldPlayKeyboardSounds boolValue])
9997 _UIHardware$_playSystemSound$(self, _cmd, sound);
10001 Class $UIApplication;
10003 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
10004 static BOOL initialized = NO;
10005 static BOOL started = NO;
10007 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
10008 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
10010 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
10011 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
10012 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
10013 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
10015 if (initialized && !enabled) {
10017 [bundle performSelector:@selector(_accessibilityStopServer)];
10018 } else if (enabled) {
10022 [bundle performSelector:@selector(_accessibilityStartServer)];
10028 Class $NSURLConnection;
10030 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10031 NSMutableURLRequest *copy([request mutableCopy]);
10033 NSURL *url([copy URL]);
10034 NSString *host([url host]);
10036 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10037 if ([PipelinedHosts_ containsObject:host])
10038 [copy setHTTPShouldUsePipelining:YES];
10040 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10044 int main(int argc, char *argv[]) { _pooled
10047 UpdateExternalStatus(0);
10049 if (Class $UIDevice = objc_getClass("UIDevice")) {
10050 UIDevice *device([$UIDevice currentDevice]);
10051 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10053 IsWildcat_ = false;
10055 UIScreen *screen([UIScreen mainScreen]);
10056 if ([screen respondsToSelector:@selector(scale)])
10057 ScreenScale_ = [screen scale];
10061 UIDevice *device([UIDevice currentDevice]);
10062 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10063 Idiom_ = @"iphone";
10065 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10066 if (idiom == UIUserInterfaceIdiomPhone)
10067 Idiom_ = @"iphone";
10068 else if (idiom == UIUserInterfaceIdiomPad)
10071 NSLog(@"unknown UIUserInterfaceIdiom!");
10074 BridgedHosts_ = [NSMutableSet setWithCapacity:2];
10075 PipelinedHosts_ = [NSMutableSet setWithCapacity:2];
10077 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
10079 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10081 /* Library Hacks {{{ */
10082 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10084 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10085 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10086 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10087 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10088 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10091 $NSURLConnection = objc_getClass("NSURLConnection");
10092 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10093 if (NSURLConnection$init$ != NULL) {
10094 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10095 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10098 $UIHardware = objc_getClass("UIHardware");
10099 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
10100 if (UIHardware$_playSystemSound$ != NULL) {
10101 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
10102 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
10105 $UIApplication = objc_getClass("UIApplication");
10106 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
10107 if (UIApplication$_updateApplicationAccessibility != NULL) {
10108 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
10109 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
10112 /* Set Locale {{{ */
10113 Locale_ = CFLocaleCopyCurrent();
10114 Languages_ = [NSLocale preferredLanguages];
10116 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10117 //NSLog(@"%@", [Languages_ description]);
10120 if (Locale_ != NULL)
10121 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10122 else if (Languages_ == nil || [Languages_ count] == 0)
10123 // XXX: consider just setting to C and then falling through?
10126 lang = [[Languages_ objectAtIndex:0] UTF8String];
10127 setenv("LANG", lang, true);
10128 std::setlocale(LC_ALL, lang);
10131 NSLog(@"Setting Language: %s", lang);
10134 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10136 /* Parse Arguments {{{ */
10137 bool substrate(false);
10143 for (int argi(1); argi != argc; ++argi)
10144 if (strcmp(argv[argi], "--") == 0) {
10146 argv[argi] = argv[0];
10152 for (int argi(1); argi != arge; ++argi)
10153 if (strcmp(args[argi], "--substrate") == 0)
10156 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10160 App_ = [[NSBundle mainBundle] bundlePath];
10166 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10167 alloc_ = alloc->method_imp;
10168 alloc->method_imp = (IMP) &Alloc_;*/
10170 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10171 dealloc_ = dealloc->method_imp;
10172 dealloc->method_imp = (IMP) &Dealloc_;*/
10174 /* System Information {{{ */
10178 size = sizeof(maxproc);
10179 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10180 perror("sysctlbyname(\"kern.maxproc\", ?)");
10181 else if (maxproc < 64) {
10183 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10184 perror("sysctlbyname(\"kern.maxproc\", #)");
10187 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10188 char *osversion = new char[size];
10189 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10190 perror("sysctlbyname(\"kern.osversion\", ?)");
10192 System_ = [NSString stringWithUTF8String:osversion];
10194 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10195 char *machine = new char[size];
10196 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10197 perror("sysctlbyname(\"hw.machine\", ?)");
10199 Machine_ = machine;
10201 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
10202 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
10203 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
10204 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
10208 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
10209 NSData *data((NSData *) ecid);
10210 size_t length([data length]);
10211 uint8_t bytes[length];
10212 [data getBytes:bytes];
10213 char string[length * 2 + 1];
10214 for (size_t i(0); i != length; ++i)
10215 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
10216 ChipID_ = [NSString stringWithUTF8String:string];
10220 IOObjectRelease(service);
10224 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
10226 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10227 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10228 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10230 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10231 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10232 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10234 if (mcc != NULL && mnc != NULL)
10235 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10242 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10243 Build_ = [system objectForKey:@"ProductBuildVersion"];
10244 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10245 Product_ = [info objectForKey:@"SafariProductVersion"];
10246 Safari_ = [info objectForKey:@"CFBundleVersion"];
10249 /* Load Database {{{ */
10251 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10253 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10255 if (Metadata_ == NULL)
10256 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10258 Settings_ = [Metadata_ objectForKey:@"Settings"];
10260 Packages_ = [Metadata_ objectForKey:@"Packages"];
10261 Sections_ = [Metadata_ objectForKey:@"Sections"];
10262 Sources_ = [Metadata_ objectForKey:@"Sources"];
10264 Token_ = [Metadata_ objectForKey:@"Token"];
10267 if (Settings_ != nil)
10268 Role_ = [Settings_ objectForKey:@"Role"];
10270 if (Sections_ == nil) {
10271 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10272 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10275 if (Sources_ == nil) {
10276 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10277 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10282 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10285 if (Packages_ != nil) {
10287 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10291 [Metadata_ removeObjectForKey:@"Packages"];
10297 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10299 #define MobileSubstrate_(name) \
10300 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10301 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10302 if (handle == NULL) \
10303 NSLog(@"%s", dlerror()); \
10306 MobileSubstrate_(Activator)
10307 MobileSubstrate_(libstatusbar)
10308 MobileSubstrate_(SimulatedKeyEvents)
10309 MobileSubstrate_(WinterBoard)
10311 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10312 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10314 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10316 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10317 unlink("/tmp/.cydia.fw");
10319 } else if (access("/User", F_OK) != 0 || version < 4) {
10322 system("/usr/libexec/cydia/firmware.sh");
10326 _assert([[NSFileManager defaultManager]
10327 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10328 withIntermediateDirectories:YES
10333 if (access("/tmp/cydia.chk", F_OK) == 0) {
10334 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10335 _assert(errno == ENOENT);
10336 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10337 _assert(errno == ENOENT);
10340 /* APT Initialization {{{ */
10341 _assert(pkgInitConfig(*_config));
10342 _assert(pkgInitSystem(*_config, _system));
10345 _config->Set("APT::Acquire::Translation", lang);
10347 // XXX: this timeout might be important :(
10348 //_config->Set("Acquire::http::Timeout", 15);
10350 _config->Set("Acquire::http::MaxParallel", 3);
10352 /* Color Choices {{{ */
10353 space_ = CGColorSpaceCreateDeviceRGB();
10355 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10356 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10357 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10358 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10359 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10360 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10361 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10362 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10363 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10365 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10366 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10368 /* UIKit Configuration {{{ */
10369 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10370 if ($GSFontSetUseLegacyFontMetrics != NULL)
10371 $GSFontSetUseLegacyFontMetrics(YES);
10373 // XXX: I have a feeling this was important
10374 //UIKeyboardDisableAutomaticAppearance();
10377 Colon_ = UCLocalize("COLON_DELIMITED");
10378 Elision_ = UCLocalize("ELISION");
10379 Error_ = UCLocalize("ERROR");
10380 Warning_ = UCLocalize("WARNING");
10383 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10385 CGColorSpaceRelease(space_);
10386 CFRelease(Locale_);