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 {{{ */
847 Pcre(const char *regex) :
852 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
855 lprintf("%d:%s\n", offset, error);
859 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
860 matches_ = new int[(capture_ + 1) * 3];
868 NSString *operator [](size_t match) {
869 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
872 bool operator ()(NSString *data) {
873 // XXX: length is for characters, not for bytes
874 return operator ()([data UTF8String], [data length]);
877 bool operator ()(const char *data, size_t size) {
879 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
883 /* Mime Addresses {{{ */
884 @interface Address : NSObject {
890 - (NSString *) address;
892 - (void) setAddress:(NSString *)address;
894 + (Address *) addressWithString:(NSString *)string;
895 - (Address *) initWithString:(NSString *)string;
899 @implementation Address
908 - (NSString *) name {
912 - (NSString *) address {
916 - (void) setAddress:(NSString *)address {
918 [address_ autorelease];
922 address_ = [address retain];
925 + (Address *) addressWithString:(NSString *)string {
926 return [[[Address alloc] initWithString:string] autorelease];
929 + (NSArray *) _attributeKeys {
930 return [NSArray arrayWithObjects:
936 - (NSArray *) attributeKeys {
937 return [[self class] _attributeKeys];
940 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
941 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
944 - (Address *) initWithString:(NSString *)string {
945 if ((self = [super init]) != nil) {
946 const char *data = [string UTF8String];
947 size_t size = [string length];
949 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
951 if (address_r(data, size)) {
952 name_ = [address_r[1] retain];
953 address_ = [address_r[2] retain];
955 name_ = [string retain];
963 /* CoreGraphics Primitives {{{ */
968 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
969 CGFloat color[] = {red, green, blue, alpha};
970 return CGColorCreate(space, color);
979 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
980 color_(Create_(space, red, green, blue, alpha))
982 Set(space, red, green, blue, alpha);
987 CGColorRelease(color_);
994 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
996 color_ = Create_(space, red, green, blue, alpha);
999 operator CGColorRef() {
1005 /* Random Global Variables {{{ */
1006 static const int PulseInterval_ = 50000;
1008 static const NSString *UI_;
1011 static bool RestartSubstrate_;
1012 static NSArray *Finishes_;
1014 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1015 #define NotifyConfig_ "/etc/notify.conf"
1017 static bool Queuing_;
1019 static CYColor Blue_;
1020 static CYColor Blueish_;
1021 static CYColor Black_;
1022 static CYColor Off_;
1023 static CYColor White_;
1024 static CYColor Gray_;
1025 static CYColor Green_;
1026 static CYColor Purple_;
1027 static CYColor Purplish_;
1029 static UIColor *InstallingColor_;
1030 static UIColor *RemovingColor_;
1032 static NSString *App_;
1034 static BOOL Advanced_;
1035 static BOOL Ignored_;
1037 static UIFont *Font12_;
1038 static UIFont *Font12Bold_;
1039 static UIFont *Font14_;
1040 static UIFont *Font18Bold_;
1041 static UIFont *Font22Bold_;
1043 static const char *Machine_ = NULL;
1044 static NSString *System_ = nil;
1045 static NSString *SerialNumber_ = nil;
1046 static NSString *ChipID_ = nil;
1047 static _H<NSString> Token_;
1048 static NSString *UniqueID_ = nil;
1049 static NSString *PLMN_ = nil;
1050 static NSString *Build_ = nil;
1051 static NSString *Product_ = nil;
1052 static NSString *Safari_ = nil;
1054 static CFLocaleRef Locale_;
1055 static NSArray *Languages_;
1056 static CGColorSpaceRef space_;
1058 static NSDictionary *SectionMap_;
1059 static NSMutableDictionary *Metadata_;
1060 static _transient NSMutableDictionary *Settings_;
1061 static _transient NSString *Role_;
1062 static _transient NSMutableDictionary *Packages_;
1063 static _transient NSMutableDictionary *Sections_;
1064 static _transient NSMutableDictionary *Sources_;
1065 static bool Changed_;
1069 static CGFloat ScreenScale_;
1070 static NSString *Idiom_;
1072 static NSMutableSet *CydiaHosts_;
1074 static NSString *kCydiaProgressEventTypeError = @"Error";
1075 static NSString *kCydiaProgressEventTypeInformation = @"Information";
1076 static NSString *kCydiaProgressEventTypeStatus = @"Status";
1077 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
1080 /* Display Helpers {{{ */
1081 inline float Interpolate(float begin, float end, float fraction) {
1082 return (end - begin) * fraction + begin;
1085 static _finline const char *StripVersion_(const char *version) {
1086 const char *colon(strchr(version, ':'));
1087 return colon == NULL ? version : colon + 1;
1090 NSString *LocalizeSection(NSString *section) {
1091 static Pcre title_r("^(.*?) \\((.*)\\)$");
1092 if (title_r(section)) {
1093 NSString *parent(title_r[1]);
1094 NSString *child(title_r[2]);
1096 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1097 LocalizeSection(parent),
1098 LocalizeSection(child)
1102 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1105 NSString *Simplify(NSString *title) {
1106 const char *data = [title UTF8String];
1107 size_t size = [title length];
1109 static Pcre square_r("^\\[(.*)\\]$");
1110 if (square_r(data, size))
1111 return Simplify(square_r[1]);
1113 static Pcre paren_r("^\\((.*)\\)$");
1114 if (paren_r(data, size))
1115 return Simplify(paren_r[1]);
1117 static Pcre title_r("^(.*?) \\((.*)\\)$");
1118 if (title_r(data, size))
1119 return Simplify(title_r[1]);
1125 NSString *GetLastUpdate() {
1126 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1129 return UCLocalize("NEVER_OR_UNKNOWN");
1131 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1132 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1134 CFRelease(formatter);
1136 return [(NSString *) formatted autorelease];
1139 bool isSectionVisible(NSString *section) {
1140 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1141 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1142 return hidden == nil || ![hidden boolValue];
1147 /* Delegate Prototypes {{{ */
1150 @class CydiaProgressEvent;
1152 @protocol DatabaseDelegate
1153 - (void) repairWithSelector:(SEL)selector;
1154 - (void) setConfigurationData:(NSString *)data;
1155 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
1158 @class CYPackageController;
1160 @protocol CydiaDelegate
1161 - (void) retainNetworkActivityIndicator;
1162 - (void) releaseNetworkActivityIndicator;
1163 - (void) clearPackage:(Package *)package;
1164 - (void) installPackage:(Package *)package;
1165 - (void) installPackages:(NSArray *)packages;
1166 - (void) removePackage:(Package *)package;
1167 - (void) beginUpdate;
1169 - (void) distUpgrade;
1171 - (void) updateData;
1173 - (void) addTrivialSource:(NSString *)href;
1174 - (void) showSettings;
1175 - (UIProgressHUD *) addProgressHUD;
1176 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1177 - (CYViewController *) pageForPackage:(NSString *)name;
1178 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1179 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1180 - (void) addCydiaHost:(NSString *)host;
1184 /* ProgressEvent Interface/Delegate {{{ */
1185 @interface CydiaProgressEvent : NSObject {
1186 _H<NSString> message_;
1190 _H<NSString> package_;
1192 _H<NSString> version_;
1195 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type;
1196 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package;
1197 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item;
1199 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type;
1201 - (NSString *) message;
1202 - (NSString *) type;
1205 - (NSString *) package;
1207 - (NSString *) version;
1209 - (void) setItem:(NSArray *)item;
1210 - (void) setPackage:(NSString *)package;
1211 - (void) setURL:(NSString *)url;
1212 - (void) setVersion:(NSString *)version;
1214 - (NSString *) compound:(NSString *)value;
1215 - (NSString *) compoundMessage;
1216 - (NSString *) compoundTitle;
1220 @protocol ProgressDelegate
1221 - (void) addProgressEvent:(CydiaProgressEvent *)event;
1222 - (void) setProgressPercent:(NSNumber *)percent;
1223 - (void) setProgressStatus:(NSDictionary *)status;
1224 - (void) setProgressCancellable:(NSNumber *)cancellable;
1225 - (bool) isProgressCancelled;
1226 - (void) setTitle:(NSString *)title;
1229 /* Status Delegation {{{ */
1231 public pkgAcquireStatus
1234 _transient NSObject<ProgressDelegate> *delegate_;
1244 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1245 delegate_ = delegate;
1248 NSObject<ProgressDelegate> *getDelegate() const {
1252 virtual bool MediaChange(std::string media, std::string drive) {
1256 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1259 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1260 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1261 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
1262 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1265 virtual void Done(pkgAcquire::ItemDesc &item) {
1268 virtual void Fail(pkgAcquire::ItemDesc &item) {
1270 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1271 item.Owner->Status == pkgAcquire::Item::StatDone
1275 std::string &error(item.Owner->ErrorText);
1279 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
1280 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1283 virtual bool Pulse(pkgAcquire *Owner) {
1284 bool value = pkgAcquireStatus::Pulse(Owner);
1287 double(CurrentBytes + CurrentItems) /
1288 double(TotalBytes + TotalItems)
1291 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1292 [NSNumber numberWithDouble:percent], @"Percent",
1294 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1295 [NSNumber numberWithDouble:TotalBytes], @"Total",
1296 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1297 nil] waitUntilDone:YES];
1299 if (value && ![delegate_ isProgressCancelled])
1307 _finline bool WasCancelled() const {
1311 virtual void Start() {
1312 pkgAcquireStatus::Start();
1313 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1316 virtual void Stop() {
1317 pkgAcquireStatus::Stop();
1318 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1319 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1323 /* Database Interface {{{ */
1324 typedef std::map< unsigned long, _H<Source> > SourceMap;
1326 @interface Database : NSObject {
1332 pkgCacheFile cache_;
1333 pkgDepCache::Policy *policy_;
1334 pkgRecords *records_;
1335 pkgProblemResolver *resolver_;
1336 pkgAcquire *fetcher_;
1338 SPtr<pkgPackageManager> manager_;
1339 pkgSourceList *list_;
1341 SourceMap sourceMap_;
1342 NSMutableArray *sourceList_;
1344 CFMutableArrayRef packages_;
1346 _transient NSObject<DatabaseDelegate> *delegate_;
1347 _transient NSObject<ProgressDelegate> *progress_;
1355 std::map<const char *, _H<NSString> > sections_;
1358 + (Database *) sharedInstance;
1361 - (void) _readCydia:(NSNumber *)fd;
1362 - (void) _readStatus:(NSNumber *)fd;
1363 - (void) _readOutput:(NSNumber *)fd;
1367 - (Package *) packageWithName:(NSString *)name;
1369 - (pkgCacheFile &) cache;
1370 - (pkgDepCache::Policy *) policy;
1371 - (pkgRecords *) records;
1372 - (pkgProblemResolver *) resolver;
1373 - (pkgAcquire &) fetcher;
1374 - (pkgSourceList &) list;
1375 - (NSArray *) packages;
1376 - (NSArray *) sources;
1377 - (Source *) sourceWithKey:(NSString *)key;
1378 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1386 - (void) updateWithStatus:(Status &)status;
1388 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1390 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1391 - (NSObject<ProgressDelegate> *) progressDelegate;
1393 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1395 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1399 /* ProgressEvent Implementation {{{ */
1400 @implementation CydiaProgressEvent
1402 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1403 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1406 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1407 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1408 [event setPackage:package];
1412 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1413 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1415 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1416 NSArray *fields([description componentsSeparatedByString:@" "]);
1417 [event setItem:fields];
1419 if ([fields count] > 3) {
1420 [event setPackage:[fields objectAtIndex:2]];
1421 [event setVersion:[fields objectAtIndex:3]];
1424 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1429 + (NSArray *) _attributeKeys {
1430 return [NSArray arrayWithObjects:
1440 - (NSArray *) attributeKeys {
1441 return [[self class] _attributeKeys];
1444 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1445 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1448 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1449 if ((self = [super init]) != nil) {
1455 - (NSString *) message {
1459 - (NSString *) type {
1463 - (NSArray *) item {
1464 return (id) item_ ?: [NSNull null];
1467 - (void) setItem:(NSArray *)item {
1471 - (NSString *) package {
1472 return (id) package_ ?: [NSNull null];
1475 - (void) setPackage:(NSString *)package {
1479 - (NSString *) url {
1480 return (id) url_ ?: [NSNull null];
1483 - (void) setURL:(NSString *)url {
1487 - (void) setVersion:(NSString *)version {
1491 - (NSString *) version {
1492 return (id) version_ ?: [NSNull null];
1495 - (NSString *) compound:(NSString *)value {
1497 NSString *mode(nil); {
1498 NSString *type([self type]);
1499 if ([type isEqualToString:kCydiaProgressEventTypeError])
1500 mode = UCLocalize("ERROR");
1501 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1502 mode = UCLocalize("WARNING");
1506 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1512 - (NSString *) compoundMessage {
1513 return [self compound:[self message]];
1516 - (NSString *) compoundTitle {
1519 if (package_ == nil)
1521 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1522 title = [package name];
1526 return [self compound:title];
1532 // Cytore Definitions {{{
1533 struct PackageValue :
1536 Cytore::Offset<PackageValue> next_;
1538 uint32_t index_ : 23;
1539 uint32_t subscribed_ : 1;
1556 Cytore::Offset<PackageValue> packages_[1 << 16];
1559 static Cytore::File<MetaValue> MetaFile_;
1561 // Cytore Helper Functions {{{
1562 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1563 SplitHash nhash = { hashlittle(name, length) };
1565 PackageValue *metadata;
1567 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1568 offset: if (offset->IsNull()) {
1569 *offset = MetaFile_.New<PackageValue>(length + 1);
1570 metadata = &MetaFile_.Get(*offset);
1572 if (metadata == NULL) {
1576 metadata = new PackageValue();
1577 memset(metadata, 0, sizeof(*metadata));
1580 memcpy(metadata->name_, name, length + 1);
1581 metadata->nhash_ = nhash.u16[1];
1583 metadata = &MetaFile_.Get(*offset);
1585 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1586 offset = &metadata->next_;
1594 static void PackageImport(const void *key, const void *value, void *context) {
1595 bool &fail(*reinterpret_cast<bool *>(context));
1598 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1599 NSLog(@"failed to import package %@", key);
1603 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1604 NSDictionary *package((NSDictionary *) value);
1606 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1607 if ([subscribed boolValue] && !metadata->subscribed_)
1608 metadata->subscribed_ = true;
1610 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1611 time_t time([date timeIntervalSince1970]);
1612 if (metadata->first_ > time || metadata->first_ == 0)
1613 metadata->first_ = time;
1616 NSDate *date([package objectForKey:@"LastSeen"]);
1617 NSString *version([package objectForKey:@"LastVersion"]);
1619 if (date != nil && version != nil) {
1620 time_t time([date timeIntervalSince1970]);
1621 if (metadata->last_ < time || metadata->last_ == 0)
1622 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1623 size_t length(strlen(buffer));
1624 uint16_t vhash(hashlittle(buffer, length));
1626 size_t capped(std::min<size_t>(8, length));
1627 char *latest(buffer + length - capped);
1629 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1630 metadata->vhash_ = vhash;
1632 metadata->last_ = time;
1638 /* Source Class {{{ */
1639 @interface Source : NSObject {
1640 CYString depiction_;
1641 CYString description_;
1647 CYString distribution_;
1652 _H<NSString> authority_;
1654 CYString defaultIcon_;
1656 _H<NSDictionary> record_;
1660 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1662 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1664 - (NSString *) depictionForPackage:(NSString *)package;
1665 - (NSString *) supportForPackage:(NSString *)package;
1667 - (NSDictionary *) record;
1671 - (NSString *) distribution;
1672 - (NSString *) type;
1674 - (NSString *) host;
1676 - (NSString *) name;
1677 - (NSString *) description;
1678 - (NSString *) label;
1679 - (NSString *) origin;
1680 - (NSString *) version;
1682 - (NSString *) defaultIcon;
1686 @implementation Source
1690 distribution_.clear();
1693 description_.clear();
1699 defaultIcon_.clear();
1707 // XXX: this is a very inefficient way to call these deconstructors
1712 + (NSArray *) _attributeKeys {
1713 return [NSArray arrayWithObjects:
1728 - (NSArray *) attributeKeys {
1729 return [[self class] _attributeKeys];
1732 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1733 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1736 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1739 trusted_ = index->IsTrusted();
1741 uri_.set(pool, index->GetURI());
1742 distribution_.set(pool, index->GetDist());
1743 type_.set(pool, index->GetType());
1745 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1746 if (dindex != NULL) {
1748 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1751 pkgTagFile tags(&fd);
1753 pkgTagSection section;
1760 {"default-icon", &defaultIcon_},
1761 {"depiction", &depiction_},
1762 {"description", &description_},
1764 {"origin", &origin_},
1765 {"support", &support_},
1766 {"version", &version_},
1769 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1770 const char *start, *end;
1772 if (section.Find(names[i].name_, start, end)) {
1773 CYString &value(*names[i].value_);
1774 value.set(pool, start, end - start);
1780 record_ = [Sources_ objectForKey:[self key]];
1782 NSURL *url([NSURL URLWithString:uri_]);
1786 host_ = [host_ lowercaseString];
1789 // XXX: this is due to a bug in _H<>
1790 authority_ = (id) host_;
1792 authority_ = [url path];
1795 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1796 if ((self = [super init]) != nil) {
1797 [self setMetaIndex:index inPool:pool];
1801 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1802 NSDictionary *lhr = [self record];
1803 NSDictionary *rhr = [source record];
1806 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1808 NSString *lhs = [self name];
1809 NSString *rhs = [source name];
1811 if ([lhs length] != 0 && [rhs length] != 0) {
1812 unichar lhc = [lhs characterAtIndex:0];
1813 unichar rhc = [rhs characterAtIndex:0];
1815 if (isalpha(lhc) && !isalpha(rhc))
1816 return NSOrderedAscending;
1817 else if (!isalpha(lhc) && isalpha(rhc))
1818 return NSOrderedDescending;
1821 return [lhs compare:rhs options:LaxCompareOptions_];
1824 - (NSString *) depictionForPackage:(NSString *)package {
1825 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1828 - (NSString *) supportForPackage:(NSString *)package {
1829 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1832 - (NSDictionary *) record {
1840 - (NSString *) uri {
1844 - (NSString *) distribution {
1845 return distribution_;
1848 - (NSString *) type {
1852 - (NSString *) key {
1853 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1856 - (NSString *) host {
1860 - (NSString *) name {
1861 return origin_.empty() ? (id) authority_ : origin_;
1864 - (NSString *) description {
1865 return description_;
1868 - (NSString *) label {
1869 return label_.empty() ? (id) authority_ : label_;
1872 - (NSString *) origin {
1876 - (NSString *) version {
1880 - (NSString *) defaultIcon {
1881 return defaultIcon_;
1886 /* CydiaOperation Class {{{ */
1887 @interface CydiaOperation : NSObject {
1888 NSString *operator_;
1892 - (NSString *) operator;
1893 - (NSString *) value;
1897 @implementation CydiaOperation
1900 [operator_ release];
1905 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1906 if ((self = [super init]) != nil) {
1907 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1908 value_ = [[NSString alloc] initWithUTF8String:value];
1912 + (NSArray *) _attributeKeys {
1913 return [NSArray arrayWithObjects:
1919 - (NSArray *) attributeKeys {
1920 return [[self class] _attributeKeys];
1923 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1924 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1927 - (NSString *) operator {
1931 - (NSString *) value {
1937 /* CydiaClause Class {{{ */
1938 @interface CydiaClause : NSObject {
1940 CydiaOperation *version_;
1943 - (NSString *) package;
1944 - (CydiaOperation *) version;
1948 @implementation CydiaClause
1956 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1957 if ((self = [super init]) != nil) {
1958 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1960 if (const char *version = dep.TargetVer())
1961 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1963 version_ = [[NSNull null] retain];
1967 + (NSArray *) _attributeKeys {
1968 return [NSArray arrayWithObjects:
1974 - (NSArray *) attributeKeys {
1975 return [[self class] _attributeKeys];
1978 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1979 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1982 - (NSString *) package {
1986 - (CydiaOperation *) version {
1992 /* CydiaRelation Class {{{ */
1993 @interface CydiaRelation : NSObject {
1994 NSString *relationship_;
1995 NSMutableArray *clauses_;
1998 - (NSString *) relationship;
1999 - (NSArray *) clauses;
2003 @implementation CydiaRelation
2006 [relationship_ release];
2011 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2012 if ((self = [super init]) != nil) {
2013 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
2014 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
2016 pkgCache::DepIterator start;
2017 pkgCache::DepIterator end;
2018 dep.GlobOr(start, end); // ++dep
2021 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2023 // yes, seriously. (wtf?)
2031 + (NSArray *) _attributeKeys {
2032 return [NSArray arrayWithObjects:
2038 - (NSArray *) attributeKeys {
2039 return [[self class] _attributeKeys];
2042 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2043 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2046 - (NSString *) relationship {
2047 return relationship_;
2050 - (NSArray *) clauses {
2054 - (void) addClause:(CydiaClause *)clause {
2055 [clauses_ addObject:clause];
2060 /* Package Class {{{ */
2061 struct ParsedPackage {
2066 CYString depiction_;
2076 @interface Package : NSObject {
2079 uint32_t essential_ : 1;
2080 uint32_t obsolete_ : 1;
2081 uint32_t ignored_ : 1;
2085 _transient Database *database_;
2087 pkgCache::VerIterator version_;
2088 pkgCache::PkgIterator iterator_;
2089 pkgCache::VerFileIterator file_;
2095 CYString installed_;
2097 const char *section_;
2098 _transient NSString *section$_;
2102 PackageValue *metadata_;
2103 ParsedPackage *parsed_;
2105 NSMutableArray *tags_;
2108 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2109 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2111 - (pkgCache::PkgIterator) iterator;
2114 - (NSString *) section;
2115 - (NSString *) simpleSection;
2117 - (NSString *) longSection;
2118 - (NSString *) shortSection;
2122 - (Address *) maintainer;
2124 - (NSString *) longDescription;
2125 - (NSString *) shortDescription;
2128 - (PackageValue *) metadata;
2131 - (bool) subscribed;
2132 - (bool) setSubscribed:(bool)subscribed;
2136 - (NSString *) latest;
2137 - (NSString *) installed;
2138 - (BOOL) uninstalled;
2141 - (BOOL) upgradableAndEssential:(BOOL)essential;
2144 - (BOOL) unfiltered;
2148 - (BOOL) halfConfigured;
2149 - (BOOL) halfInstalled;
2151 - (NSString *) mode;
2154 - (NSString *) name;
2156 - (NSString *) homepage;
2157 - (NSString *) depiction;
2158 - (Address *) author;
2160 - (NSString *) support;
2162 - (NSArray *) files;
2163 - (NSArray *) warnings;
2164 - (NSArray *) applications;
2166 - (Source *) source;
2168 - (BOOL) matches:(NSString *)text;
2170 - (bool) hasSupportingRole;
2171 - (BOOL) hasTag:(NSString *)tag;
2172 - (NSString *) primaryPurpose;
2173 - (NSArray *) purposes;
2174 - (bool) isCommercial;
2176 - (void) setIndex:(size_t)index;
2178 - (CYString &) cyname;
2180 - (uint32_t) compareBySection:(NSArray *)sections;
2185 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2186 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2187 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2188 - (bool) isVisibleInSection:(NSString *)section;
2189 - (bool) isVisibleInSource:(Source *)source;
2193 uint32_t PackageChangesRadix(Package *self, void *) {
2198 uint32_t timestamp : 30;
2199 uint32_t ignored : 1;
2200 uint32_t upgradable : 1;
2204 bool upgradable([self upgradableAndEssential:YES]);
2205 value.bits.upgradable = upgradable ? 1 : 0;
2208 value.bits.timestamp = 0;
2209 value.bits.ignored = [self ignored] ? 0 : 1;
2210 value.bits.upgradable = 1;
2212 value.bits.timestamp = [self seen] >> 2;
2213 value.bits.ignored = 0;
2214 value.bits.upgradable = 0;
2217 return _not(uint32_t) - value.key;
2220 uint32_t PackagePrefixRadix(Package *self, void *context) {
2221 size_t offset(reinterpret_cast<size_t>(context));
2222 CYString &name([self cyname]);
2224 size_t size(name.size());
2227 char *text(name.data());
2230 if (!isdigit(text[0]))
2234 while (size != digits && isdigit(text[digits]))
2242 if (offset == 0 && zeros != 0) {
2243 memset(data, '0', zeros);
2244 memcpy(data + zeros, text, 4 - zeros);
2246 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2247 if (size <= offset - zeros)
2250 text += offset - zeros;
2251 size -= offset - zeros;
2254 memcpy(data, text, 4);
2256 memcpy(data, text, size);
2257 memset(data + size, 0, 4 - size);
2260 for (size_t i(0); i != 4; ++i)
2261 if (isalpha(data[i]))
2269 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2271 /* XXX: ntohl may be more honest */
2272 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2275 CYString &(*PackageName)(Package *self, SEL sel);
2277 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2278 _profile(PackageNameCompare)
2279 CYString &lhi(PackageName(lhs, @selector(cyname)));
2280 CYString &rhi(PackageName(rhs, @selector(cyname)));
2281 CFStringRef lhn(lhi), rhn(rhi);
2284 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2285 else if (rhn == NULL)
2286 return NSOrderedDescending;
2288 _profile(PackageNameCompare$NumbersLast)
2289 if (!lhi.empty() && !rhi.empty()) {
2290 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2291 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2292 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2293 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2294 return lha ? NSOrderedAscending : NSOrderedDescending;
2298 CFIndex length = CFStringGetLength(lhn);
2300 _profile(PackageNameCompare$Compare)
2301 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2306 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2307 return PackageNameCompare(*lhs, *rhs, context);
2310 struct PackageNameOrdering :
2311 std::binary_function<Package *, Package *, bool>
2313 _finline bool operator ()(Package *lhs, Package *rhs) const {
2314 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2318 @implementation Package
2320 - (NSString *) description {
2321 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2325 if (parsed_ != NULL)
2334 + (NSString *) webScriptNameForSelector:(SEL)selector {
2336 else if (selector == @selector(clear))
2338 else if (selector == @selector(getField:))
2340 else if (selector == @selector(hasTag:))
2342 else if (selector == @selector(install))
2344 else if (selector == @selector(remove))
2350 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2351 return [self webScriptNameForSelector:selector] == nil;
2354 + (NSArray *) _attributeKeys {
2355 return [NSArray arrayWithObjects:
2374 @"shortDescription",
2387 - (NSArray *) attributeKeys {
2388 return [[self class] _attributeKeys];
2391 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2392 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2395 - (NSArray *) relations {
2396 @synchronized (database_) {
2397 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2398 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2399 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2403 - (NSString *) getField:(NSString *)name {
2404 @synchronized (database_) {
2405 if ([database_ era] != era_ || file_.end())
2408 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2410 const char *start, *end;
2411 if (!parser.Find([name UTF8String], start, end))
2412 return (NSString *) [NSNull null];
2414 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2418 if (parsed_ != NULL)
2420 @synchronized (database_) {
2421 if ([database_ era] != era_ || file_.end())
2424 ParsedPackage *parsed(new ParsedPackage);
2427 _profile(Package$parse)
2428 pkgRecords::Parser *parser;
2430 _profile(Package$parse$Lookup)
2431 parser = &[database_ records]->Lookup(file_);
2436 _profile(Package$parse$Find)
2441 {"icon", &parsed->icon_},
2442 {"depiction", &parsed->depiction_},
2443 {"homepage", &parsed->homepage_},
2444 {"website", &website},
2445 {"bugs", &parsed->bugs_},
2446 {"support", &parsed->support_},
2447 {"sponsor", &parsed->sponsor_},
2448 {"author", &parsed->author_},
2451 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2452 const char *start, *end;
2454 if (parser->Find(names[i].name_, start, end)) {
2455 CYString &value(*names[i].value_);
2456 _profile(Package$parse$Value)
2457 value.set(pool_, start, end - start);
2463 _profile(Package$parse$Tagline)
2464 const char *start, *end;
2465 if (parser->ShortDesc(start, end)) {
2466 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2469 while (stop != start && stop[-1] == '\r')
2471 parsed->tagline_.set(pool_, start, stop - start);
2475 _profile(Package$parse$Retain)
2476 if (parsed->homepage_.empty())
2477 parsed->homepage_ = website;
2478 if (parsed->homepage_ == parsed->depiction_)
2479 parsed->homepage_.clear();
2484 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2485 if ((self = [super init]) != nil) {
2486 _profile(Package$initWithVersion)
2489 database_ = database;
2490 era_ = [database era];
2494 pkgCache::PkgIterator iterator(version.ParentPkg());
2495 iterator_ = iterator;
2497 _profile(Package$initWithVersion$Version)
2498 if (!version_.end())
2499 file_ = version_.FileList();
2501 pkgCache &cache([database_ cache]);
2502 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2506 _profile(Package$initWithVersion$Cache)
2507 name_.set(NULL, iterator.Display());
2509 latest_.set(NULL, StripVersion_(version_.VerStr()));
2511 pkgCache::VerIterator current(iterator.CurrentVer());
2513 installed_.set(NULL, StripVersion_(current.VerStr()));
2516 _profile(Package$initWithVersion$Tags)
2517 pkgCache::TagIterator tag(iterator.TagList());
2519 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2521 const char *name(tag.Name());
2522 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2524 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2525 if (strcmp(name + 6, "enduser") == 0)
2527 else if (strcmp(name + 6, "hacker") == 0)
2529 else if (strcmp(name + 6, "developer") == 0)
2531 else if (strcmp(name + 6, "cydia") == 0)
2537 if (strncmp(name, "cydia::", 7) == 0) {
2538 if (strcmp(name + 7, "essential") == 0)
2540 else if (strcmp(name + 7, "obsolete") == 0)
2545 } while (!tag.end());
2549 _profile(Package$initWithVersion$Metadata)
2550 const char *mixed(iterator.Name());
2551 size_t size(strlen(mixed));
2552 char lower[size + 1];
2554 for (size_t i(0); i != size; ++i)
2555 lower[i] = mixed[i] | 0x20;
2558 PackageValue *metadata(PackageFind(lower, size));
2559 metadata_ = metadata;
2561 id_.set(NULL, metadata->name_, size);
2563 const char *latest(version_.VerStr());
2564 size_t length(strlen(latest));
2566 uint16_t vhash(hashlittle(latest, length));
2568 size_t capped(std::min<size_t>(8, length));
2569 latest = latest + length - capped;
2571 if (metadata->first_ == 0)
2572 metadata->first_ = now_;
2574 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2575 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2576 metadata->vhash_ = vhash;
2577 metadata->last_ = now_;
2578 } else if (metadata->last_ == 0)
2579 metadata->last_ = metadata->first_;
2582 _profile(Package$initWithVersion$Section)
2583 section_ = iterator.Section();
2586 _profile(Package$initWithVersion$Flags)
2587 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2588 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2593 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2594 pkgCache::VerIterator version;
2596 _profile(Package$packageWithIterator$GetCandidateVer)
2597 version = [database policy]->GetCandidateVer(iterator);
2605 _profile(Package$packageWithIterator$Allocate)
2606 package = [Package allocWithZone:zone];
2609 _profile(Package$packageWithIterator$Initialize)
2611 initWithVersion:version
2618 _profile(Package$packageWithIterator$Autorelease)
2619 package = [package autorelease];
2625 - (pkgCache::PkgIterator) iterator {
2629 - (NSString *) section {
2630 if (section$_ == nil) {
2631 if (section_ == NULL)
2634 _profile(Package$section$mappedSectionForPointer)
2635 section$_ = [database_ mappedSectionForPointer:section_];
2640 - (NSString *) simpleSection {
2641 if (NSString *section = [self section])
2642 return Simplify(section);
2647 - (NSString *) longSection {
2648 return LocalizeSection([self section]);
2651 - (NSString *) shortSection {
2652 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2655 - (NSString *) uri {
2658 pkgIndexFile *index;
2659 pkgCache::PkgFileIterator file(file_.File());
2660 if (![database_ list].FindIndex(file, index))
2662 return [NSString stringWithUTF8String:iterator_->Path];
2663 //return [NSString stringWithUTF8String:file.Site()];
2664 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2668 - (Address *) maintainer {
2669 @synchronized (database_) {
2670 if ([database_ era] != era_ || file_.end())
2673 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2674 const std::string &maintainer(parser->Maintainer());
2675 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2679 @synchronized (database_) {
2680 if ([database_ era] != era_ || version_.end())
2683 return version_->InstalledSize;
2686 - (NSString *) longDescription {
2687 @synchronized (database_) {
2688 if ([database_ era] != era_ || file_.end())
2691 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2692 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2694 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2695 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2696 if ([lines count] < 2)
2699 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2700 for (size_t i(1), e([lines count]); i != e; ++i) {
2701 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2702 [trimmed addObject:trim];
2705 return [trimmed componentsJoinedByString:@"\n"];
2708 - (NSString *) shortDescription {
2709 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2713 _profile(Package$index)
2714 CFStringRef name((CFStringRef) [self name]);
2715 if (CFStringGetLength(name) == 0)
2717 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2718 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2720 return toupper(character);
2724 - (PackageValue *) metadata {
2729 PackageValue *metadata([self metadata]);
2730 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2733 - (bool) subscribed {
2734 return [self metadata]->subscribed_;
2737 - (bool) setSubscribed:(bool)subscribed {
2738 PackageValue *metadata([self metadata]);
2739 if (metadata->subscribed_ == subscribed)
2741 metadata->subscribed_ = subscribed;
2749 - (NSString *) latest {
2753 - (NSString *) installed {
2757 - (BOOL) uninstalled {
2758 return installed_.empty();
2762 return !version_.end();
2765 - (BOOL) upgradableAndEssential:(BOOL)essential {
2766 _profile(Package$upgradableAndEssential)
2767 pkgCache::VerIterator current(iterator_.CurrentVer());
2769 return essential && essential_;
2771 return !version_.end() && version_ != current;
2775 - (BOOL) essential {
2780 return [database_ cache][iterator_].InstBroken();
2783 - (BOOL) unfiltered {
2784 _profile(Package$unfiltered$obsolete)
2785 if (_unlikely(obsolete_))
2789 _profile(Package$unfiltered$hasSupportingRole)
2790 if (_unlikely(![self hasSupportingRole]))
2798 if (![self unfiltered])
2803 _profile(Package$visible$section)
2804 section = [self section];
2807 _profile(Package$visible$isSectionVisible)
2808 if (!isSectionVisible(section))
2816 unsigned char current(iterator_->CurrentState);
2817 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2820 - (BOOL) halfConfigured {
2821 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2824 - (BOOL) halfInstalled {
2825 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2829 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2830 return state.Mode != pkgDepCache::ModeKeep;
2833 - (NSString *) mode {
2834 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2836 switch (state.Mode) {
2837 case pkgDepCache::ModeDelete:
2838 if ((state.iFlags & pkgDepCache::Purge) != 0)
2842 case pkgDepCache::ModeKeep:
2843 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2844 return @"REINSTALL";
2845 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2849 case pkgDepCache::ModeInstall:
2850 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2851 return @"REINSTALL";
2852 else*/ switch (state.Status) {
2854 return @"DOWNGRADE";
2860 return @"NEW_INSTALL";
2871 - (NSString *) name {
2872 return name_.empty() ? id_ : name_;
2875 - (UIImage *) icon {
2876 NSString *section = [self simpleSection];
2879 if (parsed_ != NULL)
2880 if (NSString *href = parsed_->icon_)
2881 if ([href hasPrefix:@"file:///"])
2882 // XXX: correct escaping
2883 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2884 if (icon == nil) if (section != nil)
2885 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2886 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2887 if ([dicon hasPrefix:@"file:///"])
2888 // XXX: correct escaping
2889 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2891 icon = [UIImage applicationImageNamed:@"unknown.png"];
2895 - (NSString *) homepage {
2896 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2899 - (NSString *) depiction {
2900 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2903 - (Address *) sponsor {
2904 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2907 - (Address *) author {
2908 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2911 - (NSString *) support {
2912 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2915 - (NSArray *) files {
2916 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2917 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2920 fin.open([path UTF8String]);
2925 while (std::getline(fin, line))
2926 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2931 - (NSString *) state {
2932 @synchronized (database_) {
2933 if ([database_ era] != era_ || file_.end())
2936 switch (iterator_->CurrentState) {
2937 case pkgCache::State::NotInstalled:
2938 return @"NotInstalled";
2939 case pkgCache::State::UnPacked:
2941 case pkgCache::State::HalfConfigured:
2942 return @"HalfConfigured";
2943 case pkgCache::State::HalfInstalled:
2944 return @"HalfInstalled";
2945 case pkgCache::State::ConfigFiles:
2946 return @"ConfigFiles";
2947 case pkgCache::State::Installed:
2948 return @"Installed";
2949 case pkgCache::State::TriggersAwaited:
2950 return @"TriggersAwaited";
2951 case pkgCache::State::TriggersPending:
2952 return @"TriggersPending";
2955 return (NSString *) [NSNull null];
2958 - (NSString *) selection {
2959 @synchronized (database_) {
2960 if ([database_ era] != era_ || file_.end())
2963 switch (iterator_->SelectedState) {
2964 case pkgCache::State::Unknown:
2966 case pkgCache::State::Install:
2968 case pkgCache::State::Hold:
2970 case pkgCache::State::DeInstall:
2971 return @"DeInstall";
2972 case pkgCache::State::Purge:
2976 return (NSString *) [NSNull null];
2979 - (NSArray *) warnings {
2980 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2981 const char *name(iterator_.Name());
2983 size_t length(strlen(name));
2984 if (length < 2) invalid:
2985 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2986 else for (size_t i(0); i != length; ++i)
2988 /* XXX: technically this is not allowed */
2989 (name[i] < 'A' || name[i] > 'Z') &&
2990 (name[i] < 'a' || name[i] > 'z') &&
2991 (name[i] < '0' || name[i] > '9') &&
2992 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2995 if (strcmp(name, "cydia") != 0) {
2998 bool _private = false;
3001 bool repository = [[self section] isEqualToString:@"Repositories"];
3003 if (NSArray *files = [self files])
3004 for (NSString *file in files)
3005 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3007 else if (!user && [file isEqualToString:@"/User"])
3009 else if (!_private && [file isEqualToString:@"/private"])
3011 else if (!stash && [file isEqualToString:@"/var/stash"])
3014 /* XXX: this is not sensitive enough. only some folders are valid. */
3015 if (cydia && !repository)
3016 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3018 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3020 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3022 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3025 return [warnings count] == 0 ? nil : warnings;
3028 - (NSArray *) applications {
3029 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3031 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3033 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
3034 if (NSArray *files = [self files])
3035 for (NSString *file in files)
3036 if (application_r(file)) {
3037 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3038 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3039 if ([id isEqualToString:me])
3042 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3044 display = application_r[1];
3046 NSString *bundle([file stringByDeletingLastPathComponent]);
3047 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3048 if (icon == nil || [icon length] == 0)
3050 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3052 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3053 [applications addObject:application];
3055 [application addObject:id];
3056 [application addObject:display];
3057 [application addObject:url];
3060 return [applications count] == 0 ? nil : applications;
3063 - (Source *) source {
3064 if (source_ == nil) {
3065 @synchronized (database_) {
3066 if ([database_ era] != era_ || file_.end())
3067 source_ = (Source *) [NSNull null];
3069 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
3073 return source_ == (Source *) [NSNull null] ? nil : source_;
3076 - (BOOL) matches:(NSString *)text {
3082 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
3083 if (range.location != NSNotFound)
3086 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
3087 if (range.location != NSNotFound)
3092 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
3093 if (range.location != NSNotFound)
3099 - (bool) hasSupportingRole {
3104 if ([Role_ isEqualToString:@"User"])
3108 if ([Role_ isEqualToString:@"Hacker"])
3112 if ([Role_ isEqualToString:@"Developer"])
3117 - (NSArray *) tags {
3121 - (BOOL) hasTag:(NSString *)tag {
3122 return tags_ == nil ? NO : [tags_ containsObject:tag];
3125 - (NSString *) primaryPurpose {
3126 for (NSString *tag in tags_)
3127 if ([tag hasPrefix:@"purpose::"])
3128 return [tag substringFromIndex:9];
3132 - (NSArray *) purposes {
3133 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3134 for (NSString *tag in tags_)
3135 if ([tag hasPrefix:@"purpose::"])
3136 [purposes addObject:[tag substringFromIndex:9]];
3137 return [purposes count] == 0 ? nil : purposes;
3140 - (bool) isCommercial {
3141 return [self hasTag:@"cydia::commercial"];
3144 - (void) setIndex:(size_t)index {
3145 if (metadata_->index_ != index)
3146 metadata_->index_ = index;
3149 - (CYString &) cyname {
3150 return name_.empty() ? id_ : name_;
3153 - (uint32_t) compareBySection:(NSArray *)sections {
3154 NSString *section([self section]);
3155 for (size_t i(0), e([sections count]); i != e; ++i) {
3156 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3160 return _not(uint32_t);
3164 @synchronized (database_) {
3165 pkgProblemResolver *resolver = [database_ resolver];
3166 resolver->Clear(iterator_);
3168 pkgCacheFile &cache([database_ cache]);
3169 cache->SetReInstall(iterator_, false);
3170 cache->MarkKeep(iterator_, false);
3174 @synchronized (database_) {
3175 pkgProblemResolver *resolver = [database_ resolver];
3176 resolver->Clear(iterator_);
3177 resolver->Protect(iterator_);
3179 pkgCacheFile &cache([database_ cache]);
3180 cache->SetReInstall(iterator_, false);
3181 cache->MarkInstall(iterator_, false);
3183 pkgDepCache::StateCache &state((*cache)[iterator_]);
3184 if (!state.Install())
3185 cache->SetReInstall(iterator_, true);
3189 @synchronized (database_) {
3190 pkgProblemResolver *resolver = [database_ resolver];
3191 resolver->Clear(iterator_);
3192 resolver->Remove(iterator_);
3193 resolver->Protect(iterator_);
3195 pkgCacheFile &cache([database_ cache]);
3196 cache->SetReInstall(iterator_, false);
3197 cache->MarkDelete(iterator_, true);
3200 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3201 _profile(Package$isUnfilteredAndSearchedForBy)
3204 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3205 value &= [self unfiltered];
3208 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3209 value &= [self matches:search];
3216 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3217 if ([search length] == 0)
3220 _profile(Package$isUnfilteredAndSelectedForBy)
3223 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3224 value &= [self unfiltered];
3227 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3228 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3235 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3236 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3239 - (bool) isVisibleInSection:(NSString *)name {
3240 NSString *section([self section]);
3244 section == nil && [name length] == 0 ||
3245 [name isEqualToString:section]
3246 ) && [self visible];
3249 - (bool) isVisibleInSource:(Source *)source {
3250 return [self source] == source && [self visible];
3255 /* Section Class {{{ */
3256 @interface Section : NSObject {
3261 NSString *localized_;
3264 - (NSComparisonResult) compareByLocalized:(Section *)section;
3265 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3266 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3267 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3268 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3269 - (NSString *) name;
3276 - (void) addToCount;
3278 - (void) setCount:(size_t)count;
3279 - (NSString *) localized;
3283 @implementation Section
3287 if (localized_ != nil)
3288 [localized_ release];
3292 - (NSComparisonResult) compareByLocalized:(Section *)section {
3293 NSString *lhs(localized_);
3294 NSString *rhs([section localized]);
3296 /*if ([lhs length] != 0 && [rhs length] != 0) {
3297 unichar lhc = [lhs characterAtIndex:0];
3298 unichar rhc = [rhs characterAtIndex:0];
3300 if (isalpha(lhc) && !isalpha(rhc))
3301 return NSOrderedAscending;
3302 else if (!isalpha(lhc) && isalpha(rhc))
3303 return NSOrderedDescending;
3306 return [lhs compare:rhs options:LaxCompareOptions_];
3309 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3310 if ((self = [self initWithName:name localize:NO]) != nil) {
3311 if (localized != nil)
3312 localized_ = [localized retain];
3316 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3317 return [self initWithName:name row:0 localize:localize];
3320 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3321 if ((self = [super init]) != nil) {
3322 name_ = [name retain];
3326 localized_ = [LocalizeSection(name_) retain];
3330 /* XXX: localize the index thingees */
3331 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3332 if ((self = [super init]) != nil) {
3333 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3339 - (NSString *) name {
3359 - (void) addToCount {
3363 - (void) setCount:(size_t)count {
3367 - (NSString *) localized {
3374 static NSString *Colon_;
3375 static NSString *Elision_;
3376 static NSString *Error_;
3377 static NSString *Warning_;
3379 /* Database Implementation {{{ */
3380 @implementation Database
3382 + (Database *) sharedInstance {
3383 static Database *instance;
3384 if (instance == nil)
3385 instance = [[Database alloc] init];
3393 - (void) releasePackages {
3394 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3395 CFArrayRemoveAllValues(packages_);
3399 // XXX: actually implement this thing
3401 [sourceList_ release];
3402 [self releasePackages];
3403 apr_pool_destroy(pool_);
3404 NSRecycleZone(zone_);
3408 - (void) _readCydia:(NSNumber *)fd { _pooled
3409 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3410 std::istream is(&ib);
3413 static Pcre finish_r("^finish:([^:]*)$");
3415 while (std::getline(is, line)) {
3416 const char *data(line.c_str());
3417 size_t size = line.size();
3418 lprintf("C:%s\n", data);
3420 if (finish_r(data, size)) {
3421 NSString *finish = finish_r[1];
3422 int index = [Finishes_ indexOfObject:finish];
3423 if (index != INT_MAX && index > Finish_)
3431 - (void) _readStatus:(NSNumber *)fd { _pooled
3432 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3433 std::istream is(&ib);
3436 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3437 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3439 while (std::getline(is, line)) {
3440 const char *data(line.c_str());
3441 size_t size(line.size());
3442 lprintf("S:%s\n", data);
3444 if (conffile_r(data, size)) {
3445 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3446 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3447 } else if (strncmp(data, "status: ", 8) == 0) {
3448 // status: <package>: {unpacked,half-configured,installed}
3449 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3450 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3451 } else if (strncmp(data, "processing: ", 12) == 0) {
3452 // processing: configure: config-test
3453 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3454 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3455 } else if (pmstatus_r(data, size)) {
3456 std::string type([pmstatus_r[1] UTF8String]);
3458 NSString *package = pmstatus_r[2];
3459 if ([package isEqualToString:@"dpkg-exec"])
3462 float percent([pmstatus_r[3] floatValue]);
3463 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3465 NSString *string = pmstatus_r[4];
3467 if (type == "pmerror") {
3468 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3469 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3470 } else if (type == "pmstatus") {
3471 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3472 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3473 } else if (type == "pmconffile")
3474 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3476 lprintf("E:unknown pmstatus\n");
3478 lprintf("E:unknown status\n");
3484 - (void) _readOutput:(NSNumber *)fd { _pooled
3485 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3486 std::istream is(&ib);
3489 while (std::getline(is, line)) {
3490 lprintf("O:%s\n", line.c_str());
3492 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3493 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3503 - (Package *) packageWithName:(NSString *)name {
3504 @synchronized (self) {
3505 if (static_cast<pkgDepCache *>(cache_) == NULL)
3507 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3508 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3512 if ((self = [super init]) != nil) {
3519 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3520 apr_pool_create(&pool_, NULL);
3522 size_t capacity(MetaFile_->active_);
3528 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3529 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3533 _assert(pipe(fds) != -1);
3536 _config->Set("APT::Keep-Fds::", cydiafd_);
3537 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3540 detachNewThreadSelector:@selector(_readCydia:)
3542 withObject:[NSNumber numberWithInt:fds[0]]
3545 _assert(pipe(fds) != -1);
3549 detachNewThreadSelector:@selector(_readStatus:)
3551 withObject:[NSNumber numberWithInt:fds[0]]
3554 _assert(pipe(fds) != -1);
3555 _assert(dup2(fds[0], 0) != -1);
3556 _assert(close(fds[0]) != -1);
3558 input_ = fdopen(fds[1], "a");
3560 _assert(pipe(fds) != -1);
3561 _assert(dup2(fds[1], 1) != -1);
3562 _assert(close(fds[1]) != -1);
3565 detachNewThreadSelector:@selector(_readOutput:)
3567 withObject:[NSNumber numberWithInt:fds[0]]
3572 - (pkgCacheFile &) cache {
3576 - (pkgDepCache::Policy *) policy {
3580 - (pkgRecords *) records {
3584 - (pkgProblemResolver *) resolver {
3588 - (pkgAcquire &) fetcher {
3592 - (pkgSourceList &) list {
3596 - (NSArray *) packages {
3597 return (NSArray *) packages_;
3600 - (NSArray *) sources {
3604 - (Source *) sourceWithKey:(NSString *)key {
3605 for (Source *source in [self sources]) {
3606 if ([[source key] isEqualToString:key])
3611 - (bool) popErrorWithTitle:(NSString *)title {
3614 while (!_error->empty()) {
3616 bool warning(!_error->PopMessage(error));
3621 size_t size(error.size());
3622 if (size == 0 || error[size - 1] != '\n')
3624 error.resize(size - 1);
3627 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3629 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3635 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3636 return [self popErrorWithTitle:title] || !success;
3639 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3640 @synchronized (self) {
3643 [self releasePackages];
3646 [sourceList_ removeAllObjects];
3666 apr_pool_clear(pool_);
3668 NSRecycleZone(zone_);
3669 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3671 int chk(creat("/tmp/cydia.chk", 0644));
3675 if (invocation != nil)
3676 [invocation invoke];
3678 NSString *title(UCLocalize("DATABASE"));
3681 OpProgress progress;
3682 while (!cache_.Open(progress, true)) { pop:
3684 bool warning(!_error->PopMessage(error));
3685 lprintf("cache_.Open():[%s]\n", error.c_str());
3687 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3688 [delegate_ repairWithSelector:@selector(configure)];
3689 else if (error == "The package lists or status file could not be parsed or opened.")
3690 [delegate_ repairWithSelector:@selector(update)];
3691 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3692 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3693 // else if (error == "Malformed Status line")
3694 // else if (error == "The list of sources could not be read.")
3696 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3706 unlink("/tmp/cydia.chk");
3708 now_ = [[NSDate date] timeIntervalSince1970];
3710 policy_ = new pkgDepCache::Policy();
3711 records_ = new pkgRecords(cache_);
3712 resolver_ = new pkgProblemResolver(cache_);
3713 fetcher_ = new pkgAcquire(&status_);
3716 list_ = new pkgSourceList();
3717 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3720 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3721 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3725 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3728 if (cache_->BrokenCount() != 0) {
3729 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3732 if (cache_->BrokenCount() != 0) {
3733 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3737 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3741 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3742 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3743 [sourceList_ addObject:object];
3745 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3746 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3747 // XXX: this could be more intelligent
3748 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3749 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3751 sourceMap_[cached->ID] = object;
3756 /*std::vector<Package *> packages;
3757 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3758 [packages_ release];
3763 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3764 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3765 //packages.push_back(package);
3766 CFArrayAppendValue(packages_, [package retain]);
3770 /*if (packages.empty())
3771 packages_ = [[NSArray alloc] init];
3773 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3776 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3777 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3778 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3786 /*if (!packages.empty())
3787 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3788 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3790 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3792 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3794 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3798 size_t count(CFArrayGetCount(packages_));
3799 MetaFile_->active_ = count;
3801 for (size_t index(0); index != count; ++index)
3802 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3806 } } CYPoolEnd() _trace(); }
3809 @synchronized (self) {
3811 resolver_ = new pkgProblemResolver(cache_);
3813 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3814 if (!cache_[iterator].Keep())
3815 cache_->MarkKeep(iterator, false);
3816 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3817 cache_->SetReInstall(iterator, false);
3820 - (void) configure {
3821 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3823 system([dpkg UTF8String]);
3828 // XXX: I don't remember this condition
3833 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3835 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3837 if ([self popErrorWithTitle:title])
3841 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3844 public pkgArchiveCleaner
3847 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3852 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3859 fetcher_->Shutdown();
3861 pkgRecords records(cache_);
3863 lock_ = new FileFd();
3864 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3866 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3868 if ([self popErrorWithTitle:title])
3872 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3875 manager_ = (_system->CreatePM(cache_));
3876 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3883 bool substrate(RestartSubstrate_);
3884 RestartSubstrate_ = false;
3886 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3888 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3890 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3892 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3893 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3896 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3898 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3900 [self popErrorWithTitle:title];
3904 bool failed = false;
3905 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3906 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3908 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3914 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3922 RestartSubstrate_ = true;
3925 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3927 if (_error->PendingError()) {
3932 if (result == pkgPackageManager::Failed) {
3937 if (result != pkgPackageManager::Completed) {
3942 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3944 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3946 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3947 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3950 if (![before isEqualToArray:after])
3955 NSString *title(UCLocalize("UPGRADE"));
3956 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3962 [self updateWithStatus:status_];
3965 - (void) updateWithStatus:(Status &)status {
3966 NSString *title(UCLocalize("REFRESHING_DATA"));
3969 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3973 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3974 if ([self popErrorWithTitle:title])
3977 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3979 bool success(ListUpdate(status, list, PulseInterval_));
3980 if (status.WasCancelled())
3983 [self popErrorWithTitle:title forOperation:success];
3985 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3987 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3991 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3992 delegate_ = delegate;
3995 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3996 progress_ = delegate;
3997 status_.setDelegate(delegate);
4000 - (NSObject<ProgressDelegate> *) progressDelegate {
4004 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4005 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4006 return i == sourceMap_.end() ? nil : i->second;
4009 - (NSString *) mappedSectionForPointer:(const char *)section {
4010 _H<NSString> *mapped;
4012 _profile(Database$mappedSectionForPointer$Cache)
4013 mapped = §ions_[section];
4016 if (*mapped == NULL) {
4017 size_t length(strlen(section));
4018 char spaced[length + 1];
4020 _profile(Database$mappedSectionForPointer$Replace)
4021 for (size_t index(0); index != length; ++index)
4022 spaced[index] = section[index] == '_' ? ' ' : section[index];
4023 spaced[length] = '\0';
4028 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4029 string = [NSString stringWithUTF8String:spaced];
4032 _profile(Database$mappedSectionForPointer$Map)
4033 string = [SectionMap_ objectForKey:string] ?: string;
4043 /* Web Scripting {{{ */
4044 @interface CydiaObject : NSObject {
4046 _transient id delegate_;
4049 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4053 @implementation CydiaObject
4056 [indirect_ release];
4060 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4061 if ((self = [super init]) != nil) {
4062 indirect_ = [indirect retain];
4066 - (void) setDelegate:(id)delegate {
4067 delegate_ = delegate;
4070 + (NSArray *) _attributeKeys {
4071 return [NSArray arrayWithObjects:
4086 - (NSArray *) attributeKeys {
4087 return [[self class] _attributeKeys];
4090 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4091 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4094 - (NSString *) version {
4098 - (NSString *) device {
4099 return [[UIDevice currentDevice] uniqueIdentifier];
4102 - (NSString *) firmware {
4103 return [[UIDevice currentDevice] systemVersion];
4106 - (NSString *) hostname {
4107 return [[UIDevice currentDevice] name];
4110 - (NSString *) idiom {
4111 return (id) Idiom_ ?: [NSNull null];
4114 - (NSString *) plmn {
4115 return (id) PLMN_ ?: [NSNull null];
4118 - (NSString *) ecid {
4119 return (id) ChipID_ ?: [NSNull null];
4122 - (NSString *) serial {
4123 return SerialNumber_;
4126 - (NSString *) role {
4127 return (id) Role_ ?: [NSNull null];
4130 - (NSString *) model {
4131 return [NSString stringWithUTF8String:Machine_];
4134 - (NSString *) token {
4135 return (id) Token_ ?: [NSNull null];
4138 + (NSString *) webScriptNameForSelector:(SEL)selector {
4140 else if (selector == @selector(addCydiaHost:))
4141 return @"addCydiaHost";
4142 else if (selector == @selector(addTrivialSource:))
4143 return @"addTrivialSource";
4144 else if (selector == @selector(close))
4146 else if (selector == @selector(du:))
4148 else if (selector == @selector(stringWithFormat:arguments:))
4150 else if (selector == @selector(getAllSources))
4151 return @"getAllSourcs";
4152 else if (selector == @selector(getKernelNumber:))
4153 return @"getKernelNumber";
4154 else if (selector == @selector(getKernelString:))
4155 return @"getKernelString";
4156 else if (selector == @selector(getInstalledPackages))
4157 return @"getInstalledPackages";
4158 else if (selector == @selector(getPackageById:))
4159 return @"getPackageById";
4160 else if (selector == @selector(installPackages:))
4161 return @"installPackages";
4162 else if (selector == @selector(localizedStringForKey:value:table:))
4164 else if (selector == @selector(refreshSources))
4165 return @"refreshSources";
4166 else if (selector == @selector(removeButton))
4167 return @"removeButton";
4168 else if (selector == @selector(substitutePackageNames:))
4169 return @"substitutePackageNames";
4170 else if (selector == @selector(scrollToBottom:))
4171 return @"scrollToBottom";
4172 else if (selector == @selector(setAllowsNavigationAction:))
4173 return @"setAllowsNavigationAction";
4174 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4175 return @"setButtonImage";
4176 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4177 return @"setButtonTitle";
4178 else if (selector == @selector(setHidesBackButton:))
4179 return @"setHidesBackButton";
4180 else if (selector == @selector(setHidesNavigationBar:))
4181 return @"setHidesNavigationBar";
4182 else if (selector == @selector(setNavigationBarStyle:))
4183 return @"setNavigationBarStyle";
4184 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4185 return @"setNavigationBarTintColor";
4186 else if (selector == @selector(setPopupHook:))
4187 return @"setPopupHook";
4188 else if (selector == @selector(setToken:))
4190 else if (selector == @selector(setViewportWidth:))
4191 return @"setViewportWidth";
4192 else if (selector == @selector(statfs:))
4194 else if (selector == @selector(supports:))
4200 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4201 return [self webScriptNameForSelector:selector] == nil;
4204 - (BOOL) supports:(NSString *)feature {
4205 return [feature isEqualToString:@"window.open"];
4208 - (NSNumber *) getKernelNumber:(NSString *)name {
4209 const char *string([name UTF8String]);
4212 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4213 return (id) [NSNull null];
4215 if (size != sizeof(int))
4216 return (id) [NSNull null];
4219 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4220 return (id) [NSNull null];
4222 return [NSNumber numberWithInt:value];
4225 - (NSString *) getKernelString:(NSString *)name {
4226 const char *string([name UTF8String]);
4229 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4230 return (id) [NSNull null];
4232 char value[size + 1];
4233 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4234 return (id) [NSNull null];
4236 // XXX: just in case you request something ludicrous
4239 return [NSString stringWithCString:value];
4242 - (void) addCydiaHost:(NSString *)host {
4243 [delegate_ performSelectorOnMainThread:@selector(addCydiaHost:) withObject:host waitUntilDone:NO];
4246 - (void) addTrivialSource:(NSString *)href {
4247 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4250 - (void) refreshSources {
4251 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4254 - (NSArray *) getAllSources {
4255 return [[Database sharedInstance] sources];
4258 - (NSArray *) getInstalledPackages {
4259 Database *database([Database sharedInstance]);
4260 @synchronized (database) {
4261 NSArray *packages([database packages]);
4262 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4263 for (Package *package in packages)
4264 if (![package uninstalled])
4265 [installed addObject:package];
4269 - (Package *) getPackageById:(NSString *)id {
4270 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4274 return (Package *) [NSNull null];
4277 - (NSArray *) statfs:(NSString *)path {
4280 if (path == nil || statfs([path UTF8String], &stat) == -1)
4283 return [NSArray arrayWithObjects:
4284 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4285 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4286 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4290 - (NSNumber *) du:(NSString *)path {
4291 NSNumber *value(nil);
4294 _assert(pipe(fds) != -1);
4296 pid_t pid(ExecFork());
4298 _assert(dup2(fds[1], 1) != -1);
4299 _assert(close(fds[0]) != -1);
4300 _assert(close(fds[1]) != -1);
4301 /* XXX: this should probably not use du */
4302 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4307 _assert(close(fds[1]) != -1);
4309 if (FILE *du = fdopen(fds[0], "r")) {
4311 while (fgets(line, sizeof(line), du) != NULL) {
4312 size_t length(strlen(line));
4313 while (length != 0 && line[length - 1] == '\n')
4314 line[--length] = '\0';
4315 if (char *tab = strchr(line, '\t')) {
4317 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4322 } else _assert(close(fds[0]));
4326 if (waitpid(pid, &status, 0) == -1)
4329 else _assert(false);
4335 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4338 - (void) installPackages:(NSArray *)packages {
4339 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4342 - (NSString *) substitutePackageNames:(NSString *)message {
4343 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4344 for (size_t i(0), e([words count]); i != e; ++i) {
4345 NSString *word([words objectAtIndex:i]);
4346 if (Package *package = [[Database sharedInstance] packageWithName:word])
4347 [words replaceObjectAtIndex:i withObject:[package name]];
4350 return [words componentsJoinedByString:@" "];
4353 - (void) removeButton {
4354 [indirect_ removeButton];
4357 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4358 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4361 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4362 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4365 - (void) setAllowsNavigationAction:(NSString *)value {
4366 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4369 - (void) setHidesBackButton:(NSString *)value {
4370 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4373 - (void) setHidesNavigationBar:(NSString *)value {
4374 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4377 - (void) setNavigationBarStyle:(NSString *)value {
4378 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4381 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4382 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4383 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4384 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4387 - (void) _setToken:(NSString *)token {
4391 [Metadata_ removeObjectForKey:@"Token"];
4393 [Metadata_ setObject:Token_ forKey:@"Token"];
4398 - (void) setToken:(NSString *)token {
4399 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4402 - (void) setPopupHook:(id)function {
4403 [indirect_ setPopupHook:function];
4406 - (void) scrollToBottom:(NSNumber *)animated {
4407 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4410 - (void) setViewportWidth:(float)width {
4411 [indirect_ setViewportWidthOnMainThread:width];
4414 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4415 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4416 unsigned count([arguments count]);
4418 for (unsigned i(0); i != count; ++i)
4419 values[i] = [arguments objectAtIndex:i];
4420 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4423 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4424 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4426 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4428 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4434 /* @ Loading... Indicator {{{ */
4435 @interface CYLoadingIndicator : UIView {
4436 _H<UIActivityIndicatorView> spinner_;
4438 _H<UIView> container_;
4441 @property (readonly, nonatomic) UILabel *label;
4442 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4446 @implementation CYLoadingIndicator
4448 - (id) initWithFrame:(CGRect)frame {
4449 if ((self = [super initWithFrame:frame]) != nil) {
4450 container_ = [[[UIView alloc] init] autorelease];
4451 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4453 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4454 [spinner_ startAnimating];
4455 [container_ addSubview:spinner_];
4457 label_ = [[[UILabel alloc] init] autorelease];
4458 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4459 [label_ setBackgroundColor:[UIColor clearColor]];
4460 [label_ setTextColor:[UIColor blackColor]];
4461 [label_ setShadowColor:[UIColor whiteColor]];
4462 [label_ setShadowOffset:CGSizeMake(0, 1)];
4463 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4464 [container_ addSubview:label_];
4466 CGSize viewsize = frame.size;
4467 CGSize spinnersize = [spinner_ bounds].size;
4468 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4469 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4471 CGRect containrect = {
4472 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4473 CGSizeMake(bothwidth, spinnersize.height)
4476 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4484 [container_ setFrame:containrect];
4485 [spinner_ setFrame:spinrect];
4486 [label_ setFrame:textrect];
4487 [self addSubview:container_];
4491 - (UILabel *) label {
4495 - (UIActivityIndicatorView *) activityIndicatorView {
4501 /* Emulated Loading Controller {{{ */
4502 @interface CYEmulatedLoadingController : CYViewController {
4503 _transient Database *database_;
4504 _H<CYLoadingIndicator> indicator_;
4505 _H<UITabBar> tabbar_;
4506 _H<UINavigationBar> navbar_;
4511 @implementation CYEmulatedLoadingController
4513 - (id) initWithDatabase:(Database *)database {
4514 if ((self = [super init]) != nil) {
4515 database_ = database;
4520 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4522 UITableView *table([[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]);
4523 [table setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4524 [[self view] addSubview:table];
4526 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4527 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4528 [[self view] addSubview:indicator_];
4530 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4531 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4532 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4533 [[self view] addSubview:tabbar_];
4535 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4536 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4537 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4538 [[self view] addSubview:navbar_];
4541 - (void) releaseSubviews {
4550 /* Cydia Browser Controller {{{ */
4551 @interface CYBrowserController : BrowserController {
4552 CydiaObject *cydia_;
4557 @implementation CYBrowserController
4564 - (NSURL *) navigationURL {
4565 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4568 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4569 [super webView:view didClearWindowObject:window forFrame:frame];
4571 WebDataSource *source([frame dataSource]);
4572 NSURLResponse *response([source response]);
4573 NSURL *url([response URL]);
4575 if ([[[url scheme] lowercaseString] isEqualToString:@"https"])
4576 if ([CydiaHosts_ containsObject:[url host]])
4577 [window setValue:cydia_ forKey:@"cydia"];
4580 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4581 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4583 if (System_ != NULL)
4584 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4585 if (Machine_ != NULL)
4586 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4588 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4593 - (void) setDelegate:(id)delegate {
4594 [super setDelegate:delegate];
4595 [cydia_ setDelegate:delegate];
4599 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4600 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4602 WebView *webview([[webview_ _documentView] webView]);
4604 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4607 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4609 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4610 if (Product_ != nil)
4611 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4613 [webview setApplicationNameForUserAgent:application];
4621 @interface NSObject (CydiaScript)
4622 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4625 @implementation NSObject (CydiaScript)
4627 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4633 @implementation NSArray (CydiaScript)
4635 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4636 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4637 for (size_t i(0), e([self count]); i != e; ++i)
4638 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4644 @implementation NSDictionary (CydiaScript)
4646 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4647 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4649 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4656 /* Confirmation Controller {{{ */
4657 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4658 if (!iterator.end())
4659 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4660 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4662 pkgCache::PkgIterator package(dep.TargetPkg());
4665 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4672 @protocol ConfirmationControllerDelegate
4673 - (void) cancelAndClear:(bool)clear;
4674 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4678 @interface ConfirmationController : CYBrowserController {
4679 _transient Database *database_;
4681 UIAlertView *essential_;
4683 NSDictionary *changes_;
4684 NSMutableArray *issues_;
4685 NSDictionary *sizes_;
4690 - (id) initWithDatabase:(Database *)database;
4694 @implementation ConfirmationController
4701 if (essential_ != nil)
4702 [essential_ release];
4709 RestartSubstrate_ = true;
4710 [delegate_ confirmWithNavigationController:[self navigationController]];
4713 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4714 NSString *context([alert context]);
4716 if ([context isEqualToString:@"remove"]) {
4717 if (button == [alert cancelButtonIndex])
4718 [self dismissModalViewControllerAnimated:YES];
4719 else if (button == [alert firstOtherButtonIndex]) {
4723 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4724 } else if ([context isEqualToString:@"unable"]) {
4725 [self dismissModalViewControllerAnimated:YES];
4726 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4728 [super alertView:alert clickedButtonAtIndex:button];
4732 - (void) _doContinue {
4733 [self dismissModalViewControllerAnimated:YES];
4734 [delegate_ cancelAndClear:NO];
4737 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4738 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4742 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4743 [super webView:view didClearWindowObject:window forFrame:frame];
4745 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4746 changes_, @"changes",
4750 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4753 - (id) initWithDatabase:(Database *)database {
4754 if ((self = [super init]) != nil) {
4755 database_ = database;
4757 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4758 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4759 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4760 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4761 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4765 pkgCacheFile &cache([database_ cache]);
4766 NSArray *packages([database_ packages]);
4767 pkgDepCache::Policy *policy([database_ policy]);
4769 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4771 for (Package *package in packages) {
4772 pkgCache::PkgIterator iterator([package iterator]);
4773 NSString *name([package id]);
4775 if ([package broken]) {
4776 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4778 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4780 reasons, @"reasons",
4783 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4787 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4788 pkgCache::DepIterator start;
4789 pkgCache::DepIterator end;
4790 dep.GlobOr(start, end); // ++dep
4792 if (!cache->IsImportantDep(end))
4794 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4797 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4799 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4800 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4801 clauses, @"clauses",
4805 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4807 pkgCache::PkgIterator target(start.TargetPkg());
4808 if (target->ProvidesList != 0)
4809 reason = @"missing";
4811 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4813 reason = @"installed";
4814 installed = [NSString stringWithUTF8String:ver.VerStr()];
4815 } else if (!cache[target].CandidateVerIter(cache).end())
4816 reason = @"uninstalled";
4817 else if (target->ProvidesList == 0)
4818 reason = @"uninstallable";
4820 reason = @"virtual";
4823 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4824 [NSString stringWithUTF8String:start.CompType()], @"operator",
4825 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4828 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4829 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4830 version, @"version",
4832 installed, @"installed",
4835 // yes, seriously. (wtf?)
4843 pkgDepCache::StateCache &state(cache[iterator]);
4845 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4847 if (state.NewInstall())
4848 [installs addObject:name];
4849 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4850 [reinstalls addObject:name];
4851 else if (state.Upgrade())
4852 [upgrades addObject:name];
4853 else if (state.Downgrade())
4854 [downgrades addObject:name];
4855 else if (!state.Delete())
4857 else if (special_r(name))
4858 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4859 [NSNull null], @"package",
4860 [NSArray arrayWithObjects:
4861 [NSDictionary dictionaryWithObjectsAndKeys:
4862 @"Conflicts", @"relationship",
4863 [NSArray arrayWithObjects:
4864 [NSDictionary dictionaryWithObjectsAndKeys:
4866 [NSNull null], @"version",
4867 @"installed", @"reason",
4874 if ([package essential])
4876 [removes addObject:name];
4879 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4880 substrate_ |= DepSubstrate(iterator.CurrentVer());
4885 else if (Advanced_) {
4886 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4888 essential_ = [[UIAlertView alloc]
4889 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4890 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4892 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4894 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4898 [essential_ setContext:@"remove"];
4900 essential_ = [[UIAlertView alloc]
4901 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4902 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4904 cancelButtonTitle:UCLocalize("OKAY")
4905 otherButtonTitles:nil
4908 [essential_ setContext:@"unable"];
4911 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4912 installs, @"installs",
4913 reinstalls, @"reinstalls",
4914 upgrades, @"upgrades",
4915 downgrades, @"downgrades",
4916 removes, @"removes",
4919 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4920 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4921 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4924 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4926 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4927 initWithTitle:UCLocalize("CANCEL")
4928 style:UIBarButtonItemStylePlain
4930 action:@selector(cancelButtonClicked)
4936 - (void) applyRightButton {
4937 if ([issues_ count] == 0 && ![self isLoading])
4938 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4939 initWithTitle:UCLocalize("CONFIRM")
4940 style:UIBarButtonItemStyleDone
4942 action:@selector(confirmButtonClicked)
4945 [[self navigationItem] setRightBarButtonItem:nil];
4949 - (void) cancelButtonClicked {
4950 [self dismissModalViewControllerAnimated:YES];
4951 [delegate_ cancelAndClear:YES];
4955 - (void) confirmButtonClicked {
4956 if (essential_ != nil)
4966 /* Progress Data {{{ */
4967 @interface CydiaProgressData : NSObject {
4968 _transient id delegate_;
4977 _H<NSMutableArray> events_;
4978 _H<NSString> title_;
4980 _H<NSString> status_;
4981 _H<NSString> finish_;
4986 @implementation CydiaProgressData
4988 + (NSArray *) _attributeKeys {
4989 return [NSArray arrayWithObjects:
5001 - (NSArray *) attributeKeys {
5002 return [[self class] _attributeKeys];
5005 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5006 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5010 if ((self = [super init]) != nil) {
5011 events_ = [NSMutableArray arrayWithCapacity:32];
5015 - (void) setDelegate:(id)delegate {
5016 delegate_ = delegate;
5019 - (void) setPercent:(float)value {
5023 - (NSNumber *) percent {
5024 return [NSNumber numberWithFloat:percent_];
5027 - (void) setCurrent:(float)value {
5031 - (NSNumber *) current {
5032 return [NSNumber numberWithFloat:current_];
5035 - (void) setTotal:(float)value {
5039 - (NSNumber *) total {
5040 return [NSNumber numberWithFloat:total_];
5043 - (void) setSpeed:(float)value {
5047 - (NSNumber *) speed {
5048 return [NSNumber numberWithFloat:speed_];
5051 - (NSArray *) events {
5055 - (void) removeAllEvents {
5056 [events_ removeAllObjects];
5059 - (void) addEvent:(CydiaProgressEvent *)event {
5060 [events_ addObject:event];
5063 - (void) setTitle:(NSString *)text {
5067 - (NSString *) title {
5071 - (void) setFinish:(NSString *)text {
5075 - (NSString *) finish {
5076 return (id) finish_ ?: [NSNull null];
5079 - (void) setRunning:(bool)running {
5083 - (NSNumber *) running {
5084 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5089 /* Progress Controller {{{ */
5090 @interface ProgressController : CYBrowserController <
5093 _transient Database *database_;
5094 _H<CydiaProgressData> progress_;
5098 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5100 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5102 - (void) setTitle:(NSString *)title;
5103 - (void) setCancellable:(bool)cancellable;
5107 @implementation ProgressController
5110 [database_ setProgressDelegate:nil];
5111 [progress_ setDelegate:nil];
5115 - (void) updateCancel {
5116 [[self navigationItem] setLeftBarButtonItem:(cancel_ == 1 ? [[[UIBarButtonItem alloc]
5117 initWithTitle:UCLocalize("CANCEL")
5118 style:UIBarButtonItemStylePlain
5120 action:@selector(cancel)
5121 ] autorelease] : nil)];
5124 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5125 if ((self = [super init]) != nil) {
5126 database_ = database;
5127 delegate_ = delegate;
5129 [database_ setProgressDelegate:self];
5131 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5132 [progress_ setDelegate:self];
5134 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5136 [scroller_ setBackgroundColor:[UIColor blackColor]];
5138 [[self navigationItem] setHidesBackButton:YES];
5140 [self updateCancel];
5144 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5145 [super webView:view didClearWindowObject:window forFrame:frame];
5146 [window setValue:progress_ forKey:@"cydiaProgress"];
5149 - (void) updateProgress {
5150 [self dispatchEvent:@"CydiaProgressUpdate"];
5153 - (void) viewWillAppear:(BOOL)animated {
5154 if (![self hasLoaded])
5155 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5157 [super viewWillAppear:animated];
5161 UpdateExternalStatus(0);
5168 [delegate_ terminateWithSuccess];
5169 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5170 [delegate_ suspendWithAnimation:YES];
5172 [delegate_ suspend];*/
5184 system("/usr/bin/sbreload");
5190 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5191 SBReboot(SBSSpringBoardServerPort());
5193 reboot2(RB_AUTOBOOT);
5200 - (void) setTitle:(NSString *)title {
5201 [progress_ setTitle:title];
5202 [self updateProgress];
5205 - (UIBarButtonItem *) rightButton {
5206 return [[progress_ running] boolValue] ? nil : [[[UIBarButtonItem alloc]
5207 initWithTitle:UCLocalize("CLOSE")
5208 style:UIBarButtonItemStylePlain
5210 action:@selector(close)
5214 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5215 UpdateExternalStatus(1);
5217 [progress_ setRunning:true];
5218 [self setTitle:title];
5219 // implicit updateProgress
5221 SHA1SumValue notifyconf; {
5223 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5226 MMap mmap(file, MMap::ReadOnly);
5228 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5229 notifyconf = sha1.Result();
5233 SHA1SumValue springlist; {
5235 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5238 MMap mmap(file, MMap::ReadOnly);
5240 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5241 springlist = sha1.Result();
5245 if (invocation != nil) {
5246 [invocation yieldToSelector:@selector(invoke)];
5247 [self setTitle:@"COMPLETE"];
5252 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5255 MMap mmap(file, MMap::ReadOnly);
5257 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5258 if (!(notifyconf == sha1.Result()))
5265 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5268 MMap mmap(file, MMap::ReadOnly);
5270 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5271 if (!(springlist == sha1.Result()))
5277 if (RestartSubstrate_)
5281 RestartSubstrate_ = false;
5284 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5285 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5286 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5287 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5288 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5292 system("su -c /usr/bin/uicache mobile");
5295 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5297 [progress_ setRunning:false];
5298 [self updateProgress];
5300 [self applyRightButton];
5303 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5304 [progress_ addEvent:event];
5305 [self updateProgress];
5308 - (bool) isProgressCancelled {
5309 return cancel_ == 2;
5314 [self updateCancel];
5317 - (void) setCancellable:(bool)cancellable {
5318 unsigned cancel(cancel_);
5322 else if (cancel_ == 0)
5325 if (cancel != cancel_)
5326 [self updateCancel];
5329 - (void) setProgressCancellable:(NSNumber *)cancellable {
5330 [self setCancellable:[cancellable boolValue]];
5333 - (void) setProgressPercent:(NSNumber *)percent {
5334 [progress_ setPercent:[percent floatValue]];
5335 [self updateProgress];
5338 - (void) setProgressStatus:(NSDictionary *)status {
5339 if (status == nil) {
5340 [progress_ setCurrent:0];
5341 [progress_ setTotal:0];
5342 [progress_ setSpeed:0];
5344 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5346 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5347 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5348 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5351 [self updateProgress];
5357 /* Cell Content View {{{ */
5358 @protocol ContentDelegate
5359 - (void) drawContentRect:(CGRect)rect;
5362 @interface ContentView : UIView {
5363 _transient id<ContentDelegate> delegate_;
5368 @implementation ContentView
5370 - (id) initWithFrame:(CGRect)frame {
5371 if ((self = [super initWithFrame:frame]) != nil) {
5372 [self setNeedsDisplayOnBoundsChange:YES];
5376 - (void) setDelegate:(id<ContentDelegate>)delegate {
5377 delegate_ = delegate;
5380 - (void) drawRect:(CGRect)rect {
5381 [super drawRect:rect];
5382 [delegate_ drawContentRect:rect];
5387 /* Cydia TableView Cell {{{ */
5388 @interface CYTableViewCell : UITableViewCell {
5389 ContentView *content_;
5395 @implementation CYTableViewCell
5402 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5403 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5405 if (view == content_) {
5406 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5407 highlighted_ = highlighted;
5410 [super _updateHighlightColorsForView:view highlighted:highlighted];
5413 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5414 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5415 highlighted_ = selected;
5417 [super setSelected:selected animated:animated];
5418 [content_ setNeedsDisplay];
5424 /* Package Cell {{{ */
5425 @interface PackageCell : CYTableViewCell <
5430 NSString *description_;
5438 - (PackageCell *) init;
5439 - (void) setPackage:(Package *)package;
5441 - (void) drawContentRect:(CGRect)rect;
5445 @implementation PackageCell
5447 - (void) clearPackage {
5458 if (description_ != nil) {
5459 [description_ release];
5463 if (source_ != nil) {
5468 if (badge_ != nil) {
5473 if (placard_ != nil) {
5483 [self clearPackage];
5487 - (PackageCell *) init {
5488 CGRect frame(CGRectMake(0, 0, 320, 74));
5489 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5490 UIView *content([self contentView]);
5491 CGRect bounds([content bounds]);
5493 content_ = [[ContentView alloc] initWithFrame:bounds];
5494 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5495 [content addSubview:content_];
5497 [content_ setDelegate:self];
5498 [content_ setOpaque:YES];
5502 - (NSString *) accessibilityLabel {
5503 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5506 - (void) setPackage:(Package *)package {
5507 [self clearPackage];
5510 Source *source = [package source];
5512 icon_ = [[package icon] retain];
5513 name_ = [[package name] retain];
5516 description_ = [package longDescription];
5517 if (description_ == nil)
5518 description_ = [package shortDescription];
5519 if (description_ != nil)
5520 description_ = [description_ retain];
5522 commercial_ = [package isCommercial];
5524 package_ = [package retain];
5526 NSString *label = nil;
5527 bool trusted = false;
5529 if (source != nil) {
5530 label = [source label];
5531 trusted = [source trusted];
5532 } else if ([[package id] isEqualToString:@"firmware"])
5533 label = UCLocalize("APPLE");
5535 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5537 NSString *from(label);
5539 NSString *section = [package simpleSection];
5540 if (section != nil && ![section isEqualToString:label]) {
5541 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5542 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5545 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5546 source_ = [from retain];
5548 if (NSString *purpose = [package primaryPurpose])
5549 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5550 badge_ = [badge_ retain];
5555 if (NSString *mode = [package_ mode]) {
5556 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5557 color = RemovingColor_;
5558 //placard = @"removing";
5560 color = InstallingColor_;
5561 //placard = @"installing";
5564 // XXX: the removing/installing placards are not @2x
5567 color = [UIColor whiteColor];
5569 if ([package installed] != nil)
5570 placard = @"installed";
5575 [content_ setBackgroundColor:color];
5578 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5579 placard_ = [placard_ retain];
5581 [self setNeedsDisplay];
5582 [content_ setNeedsDisplay];
5585 - (void) drawContentRect:(CGRect)rect {
5586 bool highlighted(highlighted_);
5587 float width([self bounds].size.width);
5590 CGContextRef context(UIGraphicsGetCurrentContext());
5591 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5592 CGContextFillRect(context, rect);
5597 rect.size = [icon_ size];
5599 rect.size.width /= 2;
5600 rect.size.height /= 2;
5602 rect.origin.x = 25 - rect.size.width / 2;
5603 rect.origin.y = 25 - rect.size.height / 2;
5605 [icon_ drawInRect:rect];
5608 if (badge_ != nil) {
5610 rect.size = [badge_ size];
5612 rect.size.width /= 2;
5613 rect.size.height /= 2;
5615 rect.origin.x = 36 - rect.size.width / 2;
5616 rect.origin.y = 36 - rect.size.height / 2;
5618 [badge_ drawInRect:rect];
5625 UISetColor(commercial_ ? Purple_ : Black_);
5626 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5627 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5630 UISetColor(commercial_ ? Purplish_ : Gray_);
5631 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5633 if (placard_ != nil)
5634 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5639 /* Section Cell {{{ */
5640 @interface SectionCell : CYTableViewCell <
5652 - (void) setSection:(Section *)section editing:(BOOL)editing;
5656 @implementation SectionCell
5658 - (void) clearSection {
5659 if (basic_ != nil) {
5664 if (section_ != nil) {
5674 if (count_ != nil) {
5681 [self clearSection];
5687 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5688 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5689 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5690 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5691 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5693 UIView *content([self contentView]);
5694 CGRect bounds([content bounds]);
5696 content_ = [[ContentView alloc] initWithFrame:bounds];
5697 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5698 [content addSubview:content_];
5699 [content_ setBackgroundColor:[UIColor whiteColor]];
5701 [content_ setDelegate:self];
5705 - (void) onSwitch:(id)sender {
5706 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5707 if (metadata == nil) {
5708 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5709 [Sections_ setObject:metadata forKey:basic_];
5712 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5716 - (void) setSection:(Section *)section editing:(BOOL)editing {
5717 if (editing != editing_) {
5719 [switch_ removeFromSuperview];
5721 [self addSubview:switch_];
5725 [self clearSection];
5727 if (section == nil) {
5728 name_ = [UCLocalize("ALL_PACKAGES") retain];
5731 basic_ = [section name];
5733 basic_ = [basic_ retain];
5735 section_ = [section localized];
5736 if (section_ != nil)
5737 section_ = [section_ retain];
5739 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5740 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5743 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5746 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5747 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5749 [content_ setNeedsDisplay];
5752 - (void) setFrame:(CGRect)frame {
5753 [super setFrame:frame];
5755 CGRect rect([switch_ frame]);
5756 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5759 - (NSString *) accessibilityLabel {
5763 - (void) drawContentRect:(CGRect)rect {
5764 bool highlighted(highlighted_ && !editing_);
5766 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5771 float width(rect.size.width);
5777 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5779 CGSize size = [count_ sizeWithFont:Font14_];
5783 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5789 /* File Table {{{ */
5790 @interface FileTable : CYViewController <
5791 UITableViewDataSource,
5794 _transient Database *database_;
5797 NSMutableArray *files_;
5801 - (id) initWithDatabase:(Database *)database;
5802 - (void) setPackage:(Package *)package;
5806 @implementation FileTable
5809 [self releaseSubviews];
5818 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5819 return files_ == nil ? 0 : [files_ count];
5822 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5826 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5827 static NSString *reuseIdentifier = @"Cell";
5829 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5831 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5832 [cell setFont:[UIFont systemFontOfSize:16]];
5834 [cell setText:[files_ objectAtIndex:indexPath.row]];
5835 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5840 - (NSURL *) navigationURL {
5841 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5845 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5847 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5848 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5849 [list_ setRowHeight:24.0f];
5850 [list_ setDataSource:self];
5851 [list_ setDelegate:self];
5852 [[self view] addSubview:list_];
5855 - (void) viewDidLoad {
5856 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5859 - (void) releaseSubviews {
5864 - (id) initWithDatabase:(Database *)database {
5865 if ((self = [super init]) != nil) {
5866 database_ = database;
5868 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5872 - (void) setPackage:(Package *)package {
5873 if (package_ != nil) {
5874 [package_ autorelease];
5883 [files_ removeAllObjects];
5885 if (package != nil) {
5886 package_ = [package retain];
5887 name_ = [[package id] retain];
5889 if (NSArray *files = [package files])
5890 [files_ addObjectsFromArray:files];
5892 if ([files_ count] != 0) {
5893 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5894 [files_ removeObjectAtIndex:0];
5895 [files_ sortUsingSelector:@selector(compareByPath:)];
5897 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5898 [stack addObject:@"/"];
5900 for (int i(0), e([files_ count]); i != e; ++i) {
5901 NSString *file = [files_ objectAtIndex:i];
5902 while (![file hasPrefix:[stack lastObject]])
5903 [stack removeLastObject];
5904 NSString *directory = [stack lastObject];
5905 [stack addObject:[file stringByAppendingString:@"/"]];
5906 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5907 ([stack count] - 2) * 3, "",
5908 [file substringFromIndex:[directory length]]
5917 - (void) reloadData {
5920 [self setPackage:[database_ packageWithName:name_]];
5925 /* Package Controller {{{ */
5926 @interface CYPackageController : CYBrowserController <
5927 UIActionSheetDelegate
5929 _transient Database *database_;
5930 _H<Package> package_;
5933 _H<NSMutableArray> buttons_;
5934 _H<UIBarButtonItem> button_;
5937 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5941 @implementation CYPackageController
5943 - (NSURL *) navigationURL {
5944 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5947 /* XXX: this is not safe at all... localization of /fail/ */
5948 - (void) _clickButtonWithName:(NSString *)name {
5949 if ([name isEqualToString:UCLocalize("CLEAR")])
5950 [delegate_ clearPackage:package_];
5951 else if ([name isEqualToString:UCLocalize("INSTALL")])
5952 [delegate_ installPackage:package_];
5953 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5954 [delegate_ installPackage:package_];
5955 else if ([name isEqualToString:UCLocalize("REMOVE")])
5956 [delegate_ removePackage:package_];
5957 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5958 [delegate_ installPackage:package_];
5959 else _assert(false);
5962 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5963 NSString *context([sheet context]);
5965 if ([context isEqualToString:@"modify"]) {
5966 if (button != [sheet cancelButtonIndex]) {
5967 NSString *buttonName = [buttons_ objectAtIndex:button];
5968 [self _clickButtonWithName:buttonName];
5971 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5975 - (bool) _allowJavaScriptPanel {
5980 - (void) _customButtonClicked {
5981 int count([buttons_ count]);
5986 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5988 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5989 [buttons addObjectsFromArray:buttons_];
5991 UIActionSheet *sheet = [[[UIActionSheet alloc]
5994 cancelButtonTitle:nil
5995 destructiveButtonTitle:nil
5996 otherButtonTitles:nil
5999 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6001 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6002 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6004 [sheet setContext:@"modify"];
6006 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6010 // We don't want to allow non-commercial packages to do custom things to the install button,
6011 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6012 - (void) customButtonClicked {
6014 [super customButtonClicked];
6016 [self _customButtonClicked];
6019 - (void) reloadButtonClicked {
6020 // Don't reload a commerical package by tapping the loading button,
6021 // but if it's not an Install button, we should forward it on.
6022 if (![package_ uninstalled])
6023 [self _customButtonClicked];
6026 - (void) applyLoadingTitle {
6027 // Don't show "Loading" as the title. Ever.
6030 - (UIBarButtonItem *) rightButton {
6035 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
6036 if ((self = [super init]) != nil) {
6037 database_ = database;
6038 buttons_ = [NSMutableArray arrayWithCapacity:4];
6039 name_ = [NSString stringWithString:name];
6040 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
6044 - (void) reloadData {
6045 package_ = [database_ packageWithName:name_];
6047 [buttons_ removeAllObjects];
6049 if (package_ != nil) {
6050 [(Package *) package_ parse];
6052 commercial_ = [package_ isCommercial];
6054 if ([package_ mode] != nil)
6055 [buttons_ addObject:UCLocalize("CLEAR")];
6056 if ([package_ source] == nil);
6057 else if ([package_ upgradableAndEssential:NO])
6058 [buttons_ addObject:UCLocalize("UPGRADE")];
6059 else if ([package_ uninstalled])
6060 [buttons_ addObject:UCLocalize("INSTALL")];
6062 [buttons_ addObject:UCLocalize("REINSTALL")];
6063 if (![package_ uninstalled])
6064 [buttons_ addObject:UCLocalize("REMOVE")];
6068 switch ([buttons_ count]) {
6069 case 0: title = nil; break;
6070 case 1: title = [buttons_ objectAtIndex:0]; break;
6071 default: title = UCLocalize("MODIFY"); break;
6074 button_ = [[[UIBarButtonItem alloc]
6076 style:UIBarButtonItemStylePlain
6078 action:@selector(customButtonClicked)
6084 - (bool) isLoading {
6085 return commercial_ ? [super isLoading] : false;
6091 /* Package List Controller {{{ */
6092 @interface PackageListController : CYViewController <
6093 UITableViewDataSource,
6096 _transient Database *database_;
6098 NSMutableArray *packages_;
6099 NSMutableArray *sections_;
6101 NSMutableArray *index_;
6102 NSMutableDictionary *indices_;
6106 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6107 - (void) setDelegate:(id)delegate;
6108 - (void) resetCursor;
6112 @implementation PackageListController
6115 [packages_ release];
6116 [sections_ release];
6125 - (void) deselectWithAnimation:(BOOL)animated {
6126 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6129 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6130 CGRect base = [[self view] bounds];
6131 base.size.height -= bounds.size.height;
6132 base.origin = [list_ frame].origin;
6134 [UIView beginAnimations:nil context:NULL];
6135 [UIView setAnimationBeginsFromCurrentState:YES];
6136 [UIView setAnimationCurve:curve];
6137 [UIView setAnimationDuration:duration];
6138 [list_ setFrame:base];
6139 [UIView commitAnimations];
6142 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6143 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6146 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6147 [self resizeForKeyboardBounds:bounds duration:0];
6150 - (void) keyboardWillShow:(NSNotification *)notification {
6153 NSTimeInterval duration;
6154 UIViewAnimationCurve curve;
6155 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6156 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6157 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6158 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6160 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);
6161 UIViewController *base = self;
6162 while ([base parentViewController] != nil)
6163 base = [base parentViewController];
6164 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6165 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6167 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6170 - (void) keyboardWillHide:(NSNotification *)notification {
6171 NSTimeInterval duration;
6172 UIViewAnimationCurve curve;
6173 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6174 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6176 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6179 - (void) viewWillAppear:(BOOL)animated {
6180 [super viewWillAppear:animated];
6182 [self resizeForKeyboardBounds:CGRectZero];
6183 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6184 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6187 - (void) viewWillDisappear:(BOOL)animated {
6188 [super viewWillDisappear:animated];
6190 [self resizeForKeyboardBounds:CGRectZero];
6191 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6192 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6195 - (void) viewDidAppear:(BOOL)animated {
6196 [super viewDidAppear:animated];
6197 [self deselectWithAnimation:animated];
6200 - (void) didSelectPackage:(Package *)package {
6201 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6202 [view setDelegate:delegate_];
6203 [[self navigationController] pushViewController:view animated:YES];
6206 #if TryIndexedCollation
6207 + (BOOL) hasIndexedCollation {
6208 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6212 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6213 NSInteger count([sections_ count]);
6214 return count == 0 ? 1 : count;
6217 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6218 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6220 return [[sections_ objectAtIndex:section] name];
6223 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6224 if ([sections_ count] == 0)
6226 return [[sections_ objectAtIndex:section] count];
6229 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6230 @synchronized (database_) {
6231 if ([database_ era] != era_)
6234 Section *section([sections_ objectAtIndex:[path section]]);
6235 NSInteger row([path row]);
6236 Package *package([packages_ objectAtIndex:([section row] + row)]);
6237 return [[package retain] autorelease];
6240 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6241 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6243 cell = [[[PackageCell alloc] init] autorelease];
6244 [cell setPackage:[self packageAtIndexPath:path]];
6248 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6249 Package *package([self packageAtIndexPath:path]);
6250 package = [database_ packageWithName:[package id]];
6251 [self didSelectPackage:package];
6254 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6255 // XXX: is 20 the most optimal number here?
6256 return [packages_ count] > 20 ? index_ : nil;
6259 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6260 #if TryIndexedCollation
6261 if ([[self class] hasIndexedCollation]) {
6262 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6269 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6270 if ((self = [super init]) != nil) {
6271 database_ = database;
6272 title_ = [title copy];
6273 [[self navigationItem] setTitle:title_];
6275 #if TryIndexedCollation
6276 if ([[self class] hasIndexedCollation])
6277 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6280 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6282 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6284 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6285 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6287 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6288 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6289 [list_ setRowHeight:73];
6290 [[self view] addSubview:list_];
6292 [list_ setDataSource:self];
6293 [list_ setDelegate:self];
6297 - (void) setDelegate:(id)delegate {
6298 delegate_ = delegate;
6301 - (bool) hasPackage:(Package *)package {
6305 - (void) reloadData {
6308 era_ = [database_ era];
6309 NSArray *packages = [database_ packages];
6311 [packages_ removeAllObjects];
6312 [sections_ removeAllObjects];
6314 _profile(PackageTable$reloadData$Filter)
6315 for (Package *package in packages)
6316 if ([self hasPackage:package])
6317 [packages_ addObject:package];
6320 [indices_ removeAllObjects];
6322 Section *section = nil;
6324 #if TryIndexedCollation
6325 if ([[self class] hasIndexedCollation]) {
6326 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6327 NSArray *titles = [collation sectionIndexTitles];
6330 _profile(PackageTable$reloadData$Section)
6331 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6335 _profile(PackageTable$reloadData$Section$Package)
6336 package = [packages_ objectAtIndex:offset];
6337 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6340 while (secidx < index) {
6343 _profile(PackageTable$reloadData$Section$Allocate)
6344 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6347 _profile(PackageTable$reloadData$Section$Add)
6348 [sections_ addObject:section];
6352 [section addToCount];
6358 [index_ removeAllObjects];
6360 _profile(PackageTable$reloadData$Section)
6361 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6365 _profile(PackageTable$reloadData$Section$Package)
6366 package = [packages_ objectAtIndex:offset];
6367 index = [package index];
6370 if (section == nil || [section index] != index) {
6371 _profile(PackageTable$reloadData$Section$Allocate)
6372 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6375 [index_ addObject:[section name]];
6376 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6378 _profile(PackageTable$reloadData$Section$Add)
6379 [sections_ addObject:section];
6383 [section addToCount];
6388 _profile(PackageTable$reloadData$List)
6393 - (void) resetCursor {
6394 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6399 /* Filtered Package List Controller {{{ */
6400 @interface FilteredPackageListController : PackageListController {
6406 - (void) setObject:(id)object;
6407 - (void) setObject:(id)object forFilter:(SEL)filter;
6409 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6413 @implementation FilteredPackageListController
6421 - (void) setFilter:(SEL)filter {
6424 /* XXX: this is an unsafe optimization of doomy hell */
6425 Method method(class_getInstanceMethod([Package class], filter));
6426 _assert(method != NULL);
6427 imp_ = method_getImplementation(method);
6428 _assert(imp_ != NULL);
6431 - (void) setObject:(id)object {
6437 object_ = [object retain];
6440 - (void) setObject:(id)object forFilter:(SEL)filter {
6441 [self setFilter:filter];
6442 [self setObject:object];
6445 - (bool) hasPackage:(Package *)package {
6446 _profile(FilteredPackageTable$hasPackage)
6447 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6451 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6452 if ((self = [super initWithDatabase:database title:title]) != nil) {
6453 [self setFilter:filter];
6454 [self setObject:object];
6461 /* Home Controller {{{ */
6462 @interface HomeController : CYBrowserController {
6467 @implementation HomeController
6470 if ((self = [super init]) != nil) {
6471 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6475 - (NSURL *) navigationURL {
6476 return [NSURL URLWithString:@"cydia://home"];
6479 - (void) aboutButtonClicked {
6480 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6482 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6483 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6484 [alert setCancelButtonIndex:0];
6487 @"Copyright (C) 2008-2011\n"
6488 "Jay Freeman (saurik)\n"
6489 "saurik@saurik.com\n"
6490 "http://www.saurik.com/"
6496 - (void) viewDidLoad {
6497 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6498 initWithTitle:UCLocalize("ABOUT")
6499 style:UIBarButtonItemStylePlain
6501 action:@selector(aboutButtonClicked)
6507 /* Manage Controller {{{ */
6508 @interface ManageController : CYBrowserController {
6511 - (void) queueStatusDidChange;
6515 @implementation ManageController
6518 if ((self = [super init]) != nil) {
6519 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6523 - (NSURL *) navigationURL {
6524 return [NSURL URLWithString:@"cydia://manage"];
6527 - (void) viewDidLoad {
6528 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6529 initWithTitle:UCLocalize("SETTINGS")
6530 style:UIBarButtonItemStylePlain
6532 action:@selector(settingsButtonClicked)
6535 [self queueStatusDidChange];
6538 - (void) settingsButtonClicked {
6539 [delegate_ showSettings];
6543 - (void) queueButtonClicked {
6547 - (void) applyLoadingTitle {
6548 // Disable "Loading" title.
6551 - (void) applyRightButton {
6552 // Disable right button.
6556 - (void) queueStatusDidChange {
6558 if (!IsWildcat_ && Queuing_) {
6559 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6560 initWithTitle:UCLocalize("QUEUE")
6561 style:UIBarButtonItemStyleDone
6563 action:@selector(queueButtonClicked)
6566 [[self navigationItem] setRightBarButtonItem:nil];
6571 - (bool) isLoading {
6572 // Never show as loading.
6579 /* Refresh Bar {{{ */
6580 @interface RefreshBar : UINavigationBar {
6581 UIProgressIndicator *indicator_;
6582 UITextLabel *prompt_;
6583 UIProgressBar *progress_;
6584 UINavigationButton *cancel_;
6589 @implementation RefreshBar
6592 [indicator_ release];
6594 [progress_ release];
6599 - (void) positionViews {
6600 CGRect frame = [cancel_ frame];
6601 frame.size = [cancel_ sizeThatFits:frame.size];
6602 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6603 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6604 [cancel_ setFrame:frame];
6606 CGSize prgsize = {75, 100};
6608 [self frame].size.width - prgsize.width - 10,
6609 ([self frame].size.height - prgsize.height) / 2
6611 [progress_ setFrame:prgrect];
6613 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6614 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6615 CGRect indrect = {{indoffset, indoffset}, indsize};
6616 [indicator_ setFrame:indrect];
6618 CGSize prmsize = {215, indsize.height + 4};
6620 indoffset * 2 + indsize.width,
6621 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6623 [prompt_ setFrame:prmrect];
6626 - (void) setFrame:(CGRect)frame {
6627 [super setFrame:frame];
6628 [self positionViews];
6631 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6632 if ((self = [super initWithFrame:frame]) != nil) {
6633 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6635 [self setBarStyle:UIBarStyleBlack];
6637 UIBarStyle barstyle([self _barStyle:NO]);
6638 bool ugly(barstyle == UIBarStyleDefault);
6640 UIProgressIndicatorStyle style = ugly ?
6641 UIProgressIndicatorStyleMediumBrown :
6642 UIProgressIndicatorStyleMediumWhite;
6644 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6645 [indicator_ setStyle:style];
6646 [indicator_ startAnimation];
6647 [self addSubview:indicator_];
6649 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6650 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6651 [prompt_ setBackgroundColor:[UIColor clearColor]];
6652 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6653 [self addSubview:prompt_];
6655 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6656 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6657 [progress_ setStyle:0];
6658 [self addSubview:progress_];
6660 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6661 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6662 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6663 [cancel_ setBarStyle:barstyle];
6665 [self positionViews];
6669 - (void) setCancellable:(bool)cancellable {
6671 [self addSubview:cancel_];
6673 [cancel_ removeFromSuperview];
6677 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6678 [progress_ setProgress:0];
6682 [self setCancellable:NO];
6685 - (void) setPrompt:(NSString *)prompt {
6686 [prompt_ setText:prompt];
6689 - (void) setProgress:(float)progress {
6690 [progress_ setProgress:progress];
6696 @class CYNavigationController;
6698 /* Cydia Tab Bar Controller {{{ */
6699 @interface CYTabBarController : UITabBarController <
6700 UITabBarControllerDelegate,
6703 _transient Database *database_;
6704 RefreshBar *refreshbar_;
6708 // XXX: ok, "updatedelegate_"?...
6709 _transient NSObject<CydiaDelegate> *updatedelegate_;
6712 UIViewController *remembered_;
6713 _transient UIViewController *transient_;
6716 - (NSArray *) navigationURLCollection;
6717 - (void) dropBar:(BOOL)animated;
6718 - (void) beginUpdate;
6719 - (void) raiseBar:(BOOL)animated;
6724 @implementation CYTabBarController
6726 - (void) setUnselectedViewController:(UIViewController *)transient {
6727 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6728 if (transient != nil) {
6729 if (transient_ == nil)
6730 remembered_ = [[controllers objectAtIndex:0] retain];
6731 transient_ = transient;
6732 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6733 [controllers replaceObjectAtIndex:0 withObject:transient_];
6734 [self setSelectedIndex:0];
6735 [self setViewControllers:controllers];
6736 [self concealTabBarSelection];
6737 } else if (remembered_ != nil) {
6738 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6739 transient_ = transient;
6740 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6741 [remembered_ release];
6743 [self setViewControllers:controllers];
6744 [self revealTabBarSelection];
6748 - (UIViewController *) unselectedViewController {
6752 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6753 if ([self unselectedViewController])
6754 [self setUnselectedViewController:nil];
6757 - (NSArray *) navigationURLCollection {
6758 NSMutableArray *items([NSMutableArray array]);
6760 // XXX: Should this deal with transient view controllers?
6761 for (id navigation in [self viewControllers]) {
6762 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6764 [items addObject:stack];
6770 - (void) reloadData {
6771 for (CYViewController *controller in [self viewControllers])
6772 [controller reloadData];
6774 [(CYNavigationController *)[self unselectedViewController] reloadData];
6778 [refreshbar_ release];
6779 [[NSNotificationCenter defaultCenter] removeObserver:self];
6784 - (id) initWithDatabase:(Database *)database {
6785 if ((self = [super init]) != nil) {
6786 database_ = database;
6787 [self setDelegate:self];
6789 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6790 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6792 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6796 - (void) setUpdate:(NSDate *)date {
6800 - (void) beginUpdate {
6801 [refreshbar_ start];
6804 [updatedelegate_ retainNetworkActivityIndicator];
6808 detachNewThreadSelector:@selector(performUpdate)
6814 - (void) performUpdate { _pooled
6816 status.setDelegate(self);
6817 [database_ updateWithStatus:status];
6820 performSelectorOnMainThread:@selector(completeUpdate)
6826 - (void) stopUpdateWithSelector:(SEL)selector {
6828 [updatedelegate_ releaseNetworkActivityIndicator];
6830 [self raiseBar:YES];
6833 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6836 - (void) completeUpdate {
6839 [self stopUpdateWithSelector:@selector(reloadData)];
6842 - (void) cancelUpdate {
6843 [self stopUpdateWithSelector:@selector(updateData)];
6846 - (void) cancelPressed {
6847 [self cancelUpdate];
6854 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6855 [refreshbar_ setPrompt:[event compoundMessage]];
6858 - (bool) isProgressCancelled {
6862 - (void) setProgressCancellable:(NSNumber *)cancellable {
6863 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6866 - (void) setProgressPercent:(NSNumber *)percent {
6867 [refreshbar_ setProgress:[percent floatValue]];
6870 - (void) setProgressStatus:(NSDictionary *)status {
6872 [self setProgressPercent:[status objectForKey:@"Percent"]];
6875 - (void) setUpdateDelegate:(id)delegate {
6876 updatedelegate_ = delegate;
6879 - (CGFloat) statusBarHeight {
6880 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6881 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6883 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6887 - (UIView *) transitionView {
6888 if ([self respondsToSelector:@selector(_transitionView)])
6889 return [self _transitionView];
6891 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6894 - (void) dropBar:(BOOL)animated {
6899 UIView *transition([self transitionView]);
6900 [[self view] addSubview:refreshbar_];
6902 CGRect barframe([refreshbar_ frame]);
6904 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6905 barframe.origin.y = [self statusBarHeight];
6907 barframe.origin.y = 0;
6909 [refreshbar_ setFrame:barframe];
6912 [UIView beginAnimations:nil context:NULL];
6914 CGRect viewframe = [transition frame];
6915 viewframe.origin.y += barframe.size.height;
6916 viewframe.size.height -= barframe.size.height;
6917 [transition setFrame:viewframe];
6920 [UIView commitAnimations];
6922 // Ensure bar has the proper width for our view, it might have changed
6923 barframe.size.width = viewframe.size.width;
6924 [refreshbar_ setFrame:barframe];
6926 // XXX: fix Apple's layout bug
6927 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6930 - (void) raiseBar:(BOOL)animated {
6935 UIView *transition([self transitionView]);
6936 [refreshbar_ removeFromSuperview];
6938 CGRect barframe([refreshbar_ frame]);
6941 [UIView beginAnimations:nil context:NULL];
6943 CGRect viewframe = [transition frame];
6944 viewframe.origin.y -= barframe.size.height;
6945 viewframe.size.height += barframe.size.height;
6946 [transition setFrame:viewframe];
6949 [UIView commitAnimations];
6951 // XXX: fix Apple's layout bug
6952 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6956 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6957 // XXX: fix Apple's layout bug
6958 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6962 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6963 bool dropped(dropped_);
6968 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6973 // XXX: fix Apple's layout bug
6974 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6977 - (void) statusBarFrameChanged:(NSNotification *)notification {
6986 /* Cydia Navigation Controller {{{ */
6987 @interface CYNavigationController : UINavigationController {
6988 _transient Database *database_;
6989 _transient id<UINavigationControllerDelegate> delegate_;
6992 - (NSArray *) navigationURLCollection;
6993 - (id) initWithDatabase:(Database *)database;
6994 - (void) reloadData;
6999 @implementation CYNavigationController
7001 - (NSArray *) navigationURLCollection {
7002 NSMutableArray *stack([NSMutableArray array]);
7004 for (CYViewController *controller in [self viewControllers]) {
7005 NSString *url = [[controller navigationURL] absoluteString];
7007 [stack addObject:url];
7013 - (void) reloadData {
7014 for (CYViewController *page in [self viewControllers]) {
7015 // Only reload controllers that have already loaded.
7016 // This prevents a page from accidentally loading too
7017 // early if it hasn't been shown on the screen yet.
7018 if ([page hasLoaded])
7023 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
7024 delegate_ = delegate;
7027 - (id) initWithDatabase:(Database *)database {
7028 if ((self = [super init]) != nil) {
7029 database_ = database;
7036 /* Cydia:// Protocol {{{ */
7037 @interface CydiaURLProtocol : NSURLProtocol {
7042 @implementation CydiaURLProtocol
7044 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7045 NSURL *url([request URL]);
7049 NSString *scheme([[url scheme] lowercaseString]);
7050 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7052 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7058 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7062 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7063 id<NSURLProtocolClient> client([self client]);
7065 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7067 NSData *data(UIImagePNGRepresentation(icon));
7069 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7070 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7071 [client URLProtocol:self didLoadData:data];
7072 [client URLProtocolDidFinishLoading:self];
7076 - (void) startLoading {
7077 id<NSURLProtocolClient> client([self client]);
7078 NSURLRequest *request([self request]);
7080 NSURL *url([request URL]);
7081 NSString *href([url absoluteString]);
7082 NSString *scheme([[url scheme] lowercaseString]);
7086 if ([scheme isEqualToString:@"cydia"])
7087 path = [href substringFromIndex:8];
7088 else if ([scheme isEqualToString:@"about"])
7089 path = [href substringFromIndex:12];
7090 else _assert(false);
7092 NSRange slash([path rangeOfString:@"/"]);
7095 if (slash.location == NSNotFound) {
7099 command = [path substringToIndex:slash.location];
7100 path = [path substringFromIndex:(slash.location + 1)];
7103 Database *database([Database sharedInstance]);
7105 if ([command isEqualToString:@"package-icon"]) {
7108 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7109 Package *package([database packageWithName:path]);
7112 UIImage *icon([package icon]);
7113 [self _returnPNGWithImage:icon forRequest:request];
7114 } else if ([command isEqualToString:@"source-icon"]) {
7117 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7118 NSString *source(Simplify(path));
7119 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7121 icon = [UIImage applicationImageNamed:@"unknown.png"];
7122 [self _returnPNGWithImage:icon forRequest:request];
7123 } else if ([command isEqualToString:@"uikit-image"]) {
7126 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7127 UIImage *icon(_UIImageWithName(path));
7128 [self _returnPNGWithImage:icon forRequest:request];
7129 } else if ([command isEqualToString:@"section-icon"]) {
7132 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7133 NSString *section(Simplify(path));
7134 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7136 icon = [UIImage applicationImageNamed:@"unknown.png"];
7137 [self _returnPNGWithImage:icon forRequest:request];
7139 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7143 - (void) stopLoading {
7149 /* Section Controller {{{ */
7150 @interface SectionController : FilteredPackageListController {
7151 _H<NSString> section_;
7154 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7158 @implementation SectionController
7160 - (NSURL *) navigationURL {
7161 NSString *name = section_;
7165 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7168 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7171 title = UCLocalize("ALL_PACKAGES");
7172 else if (![name isEqual:@""])
7173 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7175 title = UCLocalize("NO_SECTION");
7177 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7184 /* Sections Controller {{{ */
7185 @interface SectionsController : CYViewController <
7186 UITableViewDataSource,
7189 _transient Database *database_;
7190 NSMutableArray *sections_;
7191 NSMutableArray *filtered_;
7196 - (id) initWithDatabase:(Database *)database;
7197 - (void) editButtonClicked;
7201 @implementation SectionsController
7204 [self releaseSubviews];
7205 [sections_ release];
7206 [filtered_ release];
7211 - (NSURL *) navigationURL {
7212 return [NSURL URLWithString:@"cydia://sections"];
7215 - (void) updateNavigationItem {
7216 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7217 if ([sections_ count] == 0) {
7218 [[self navigationItem] setRightBarButtonItem:nil];
7220 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7221 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7223 action:@selector(editButtonClicked)
7224 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7228 - (BOOL) isEditing {
7232 - (void) setEditing:(BOOL)editing {
7233 if ((editing_ = editing))
7236 [delegate_ updateData];
7238 [self updateNavigationItem];
7241 - (void) viewDidAppear:(BOOL)animated {
7242 [super viewDidAppear:animated];
7243 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7246 - (void) viewWillDisappear:(BOOL)animated {
7247 [super viewWillDisappear:animated];
7248 if (editing_) [self setEditing:NO];
7251 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7252 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7256 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7257 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7260 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7264 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7265 static NSString *reuseIdentifier = @"SectionCell";
7267 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7269 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7271 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7276 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7280 Section *section = [self sectionAtIndexPath:indexPath];
7282 SectionController *controller = [[[SectionController alloc]
7283 initWithDatabase:database_
7284 section:[section name]
7286 [controller setDelegate:delegate_];
7288 [[self navigationController] pushViewController:controller animated:YES];
7292 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7294 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7295 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7296 [list_ setRowHeight:45.0f];
7297 [list_ setDataSource:self];
7298 [list_ setDelegate:self];
7299 [[self view] addSubview:list_];
7302 - (void) viewDidLoad {
7303 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7306 - (void) releaseSubviews {
7311 - (id) initWithDatabase:(Database *)database {
7312 if ((self = [super init]) != nil) {
7313 database_ = database;
7315 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7316 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7320 - (void) reloadData {
7323 NSArray *packages = [database_ packages];
7325 [sections_ removeAllObjects];
7326 [filtered_ removeAllObjects];
7328 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7331 for (Package *package in packages) {
7332 NSString *name([package section]);
7333 NSString *key(name == nil ? @"" : name);
7337 _profile(SectionsView$reloadData$Section)
7338 section = [sections objectForKey:key];
7339 if (section == nil) {
7340 _profile(SectionsView$reloadData$Section$Allocate)
7341 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7342 [sections setObject:section forKey:key];
7347 [section addToCount];
7349 _profile(SectionsView$reloadData$Filter)
7350 if (![package valid] || ![package visible])
7358 [sections_ addObjectsFromArray:[sections allValues]];
7360 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7362 for (Section *section in sections_) {
7363 size_t count([section row]);
7367 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7368 [section setCount:count];
7369 [filtered_ addObject:section];
7372 [self updateNavigationItem];
7377 - (void) editButtonClicked {
7378 [self setEditing:(!editing_)];
7384 /* Changes Controller {{{ */
7385 @interface ChangesController : CYViewController <
7386 UITableViewDataSource,
7389 _transient Database *database_;
7391 CFMutableArrayRef packages_;
7392 NSMutableArray *sections_;
7395 BOOL hasSentFirstLoad_;
7398 - (id) initWithDatabase:(Database *)database;
7402 @implementation ChangesController
7405 [self releaseSubviews];
7406 CFRelease(packages_);
7407 [sections_ release];
7412 - (NSURL *) navigationURL {
7413 return [NSURL URLWithString:@"cydia://changes"];
7416 - (void) viewWillAppear:(BOOL)animated {
7417 // Loads after it appears, so don't load beforehand.
7419 [super viewWillAppear:animated];
7422 - (void) viewDidAppear:(BOOL)animated {
7423 [super viewDidAppear:animated];
7425 if (!hasSentFirstLoad_) {
7426 hasSentFirstLoad_ = YES;
7427 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7429 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7433 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7434 NSInteger count([sections_ count]);
7435 return count == 0 ? 1 : count;
7438 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7439 if ([sections_ count] == 0)
7441 return [[sections_ objectAtIndex:section] name];
7444 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7445 if ([sections_ count] == 0)
7447 return [[sections_ objectAtIndex:section] count];
7450 - (Package *) packageAtIndex:(NSUInteger)index {
7451 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7454 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7455 @synchronized (database_) {
7456 if ([database_ era] != era_)
7459 NSUInteger sectionIndex([path section]);
7460 if (sectionIndex >= [sections_ count])
7462 Section *section([sections_ objectAtIndex:sectionIndex]);
7463 NSInteger row([path row]);
7464 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7467 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7468 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7470 cell = [[[PackageCell alloc] init] autorelease];
7471 [cell setPackage:[self packageAtIndexPath:path]];
7475 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7476 Package *package([self packageAtIndexPath:path]);
7477 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7478 [view setDelegate:delegate_];
7479 [[self navigationController] pushViewController:view animated:YES];
7483 - (void) refreshButtonClicked {
7484 [delegate_ beginUpdate];
7485 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7488 - (void) upgradeButtonClicked {
7489 [delegate_ distUpgrade];
7493 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7495 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7496 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7497 [list_ setRowHeight:73];
7498 [list_ setDataSource:self];
7499 [list_ setDelegate:self];
7500 [[self view] addSubview:list_];
7503 - (void) viewDidLoad {
7504 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7507 - (void) releaseSubviews {
7512 - (id) initWithDatabase:(Database *)database {
7513 if ((self = [super init]) != nil) {
7514 database_ = database;
7516 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7517 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7521 // this mostly works because reloadData (below) is @synchronized (database_)
7522 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7523 - (void) _reloadPackages:(NSArray *)packages {
7524 CFRelease(packages_);
7525 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7528 _profile(ChangesController$_reloadPackages$Filter)
7529 for (Package *package in packages)
7530 if ([package upgradableAndEssential:YES] || [package visible])
7531 CFArrayAppendValue(packages_, package);
7534 _profile(ChangesController$_reloadPackages$radixSort)
7535 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7540 - (void) reloadData {
7541 @synchronized (database_) {
7542 era_ = [database_ era];
7543 NSArray *packages = [database_ packages];
7545 [sections_ removeAllObjects];
7548 UIProgressHUD *hud([delegate_ addProgressHUD]);
7549 [hud setText:UCLocalize("LOADING")];
7550 //NSLog(@"HUD:%@::%@", delegate_, hud);
7551 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7552 [delegate_ removeProgressHUD:hud];
7554 [self _reloadPackages:packages];
7557 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7558 Section *ignored = nil;
7559 Section *section = nil;
7563 bool unseens = false;
7565 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7567 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7568 Package *package = [self packageAtIndex:offset];
7570 BOOL uae = [package upgradableAndEssential:YES];
7574 time_t seen([package seen]);
7576 if (section == nil || last != seen) {
7580 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7583 _profile(ChangesController$reloadData$Allocate)
7584 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7585 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7586 [sections_ addObject:section];
7590 [section addToCount];
7591 } else if ([package ignored]) {
7592 if (ignored == nil) {
7593 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7595 [ignored addToCount];
7598 [upgradable addToCount];
7603 CFRelease(formatter);
7606 Section *last = [sections_ lastObject];
7607 size_t count = [last count];
7608 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7609 [sections_ removeLastObject];
7612 if ([ignored count] != 0)
7613 [sections_ insertObject:ignored atIndex:0];
7615 [sections_ insertObject:upgradable atIndex:0];
7620 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7621 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7622 style:UIBarButtonItemStylePlain
7624 action:@selector(upgradeButtonClicked)
7627 if (![delegate_ updating])
7628 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7629 initWithTitle:UCLocalize("REFRESH")
7630 style:UIBarButtonItemStylePlain
7632 action:@selector(refreshButtonClicked)
7640 /* Search Controller {{{ */
7641 @interface SearchController : FilteredPackageListController <
7644 _H<UISearchBar> search_;
7648 - (id) initWithDatabase:(Database *)database;
7649 - (void) setSearchTerm:(NSString *)term;
7650 - (void) reloadData;
7654 @implementation SearchController
7657 [search_ setDelegate:nil];
7661 - (NSURL *) navigationURL {
7662 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7663 return [NSURL URLWithString:@"cydia://search"];
7665 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7668 - (void) setSearchTerm:(NSString *)searchTerm {
7669 [search_ setText:searchTerm];
7673 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7674 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7675 [search_ resignFirstResponder];
7679 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7680 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7684 - (id) initWithDatabase:(Database *)database {
7685 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7686 search_ = [[[UISearchBar alloc] init] autorelease];
7687 [search_ setDelegate:self];
7691 - (void) viewDidAppear:(BOOL)animated {
7692 [super viewDidAppear:animated];
7694 if (!searchloaded_) {
7695 searchloaded_ = YES;
7696 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7697 [search_ layoutSubviews];
7698 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7700 UITextField *textField;
7701 if ([search_ respondsToSelector:@selector(searchField)])
7702 textField = [search_ searchField];
7704 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7706 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7707 [textField setEnablesReturnKeyAutomatically:NO];
7708 [[self navigationItem] setTitleView:textField];
7712 - (void) reloadData {
7713 [self setObject:[search_ text]];
7718 - (void) didSelectPackage:(Package *)package {
7719 [search_ resignFirstResponder];
7720 [super didSelectPackage:package];
7725 /* Package Settings Controller {{{ */
7726 @interface PackageSettingsController : CYViewController <
7727 UITableViewDataSource,
7730 _transient Database *database_;
7733 UITableView *table_;
7734 UISwitch *subscribedSwitch_;
7735 UISwitch *ignoredSwitch_;
7736 UITableViewCell *subscribedCell_;
7737 UITableViewCell *ignoredCell_;
7740 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7744 @implementation PackageSettingsController
7747 [self releaseSubviews];
7754 - (NSURL *) navigationURL {
7755 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7758 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7759 if (package_ == nil)
7762 if ([package_ installed] == nil)
7768 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7769 if (package_ == nil)
7772 // both sections contain just one item right now.
7776 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7780 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7782 return UCLocalize("SHOW_ALL_CHANGES_EX");
7784 return UCLocalize("IGNORE_UPGRADES_EX");
7787 - (void) onSubscribed:(id)control {
7788 bool value([control isOn]);
7789 if (package_ == nil)
7791 if ([package_ setSubscribed:value])
7792 [delegate_ updateData];
7795 - (void) _updateIgnored {
7796 const char *package([name_ UTF8String]);
7797 bool on([ignoredSwitch_ isOn]);
7799 pid_t pid(ExecFork());
7801 FILE *dpkg(popen("dpkg --set-selections", "w"));
7802 fwrite(package, strlen(package), 1, dpkg);
7805 fwrite(" hold\n", 6, 1, dpkg);
7807 fwrite(" install\n", 9, 1, dpkg);
7817 int result(waitpid(pid, &status, 0));
7820 _assert(result == pid);
7826 - (void) onIgnored:(id)control {
7827 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7828 [invocation setTarget:self];
7829 [invocation setSelector:@selector(_updateIgnored)];
7831 [delegate_ reloadDataWithInvocation:invocation];
7834 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7835 if (package_ == nil)
7838 switch ([indexPath section]) {
7839 case 0: return subscribedCell_;
7840 case 1: return ignoredCell_;
7849 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7851 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7852 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7853 [table_ setDataSource:self];
7854 [table_ setDelegate:self];
7855 [[self view] addSubview:table_];
7857 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7858 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7859 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7861 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7862 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7863 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7865 subscribedCell_ = [[UITableViewCell alloc] init];
7866 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7867 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7868 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7870 ignoredCell_ = [[UITableViewCell alloc] init];
7871 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7872 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7873 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7876 - (void) viewDidLoad {
7877 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7880 - (void) releaseSubviews {
7881 [ignoredCell_ release];
7884 [subscribedCell_ release];
7885 subscribedCell_ = nil;
7890 [ignoredSwitch_ release];
7891 ignoredSwitch_ = nil;
7893 [subscribedSwitch_ release];
7894 subscribedSwitch_ = nil;
7897 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7898 if ((self = [super init]) != nil) {
7899 database_ = database;
7900 name_ = [package retain];
7904 - (void) reloadData {
7907 if (package_ != nil)
7908 [package_ autorelease];
7909 package_ = [database_ packageWithName:name_];
7911 if (package_ != nil) {
7912 package_ = [package_ retain];
7913 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7914 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7915 } // XXX: what now, G?
7917 [table_ reloadData];
7923 /* Installed Controller {{{ */
7924 @interface InstalledController : FilteredPackageListController {
7928 - (id) initWithDatabase:(Database *)database;
7930 - (void) updateRoleButton;
7931 - (void) queueStatusDidChange;
7935 @implementation InstalledController
7941 - (NSURL *) navigationURL {
7942 return [NSURL URLWithString:@"cydia://installed"];
7945 - (id) initWithDatabase:(Database *)database {
7946 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7947 [self updateRoleButton];
7948 [self queueStatusDidChange];
7953 - (void) queueButtonClicked {
7958 - (void) queueStatusDidChange {
7962 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7963 initWithTitle:UCLocalize("QUEUE")
7964 style:UIBarButtonItemStyleDone
7966 action:@selector(queueButtonClicked)
7969 [[self navigationItem] setLeftBarButtonItem:nil];
7975 - (void) updateRoleButton {
7976 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7977 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7978 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7979 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7981 action:@selector(roleButtonClicked)
7985 - (void) roleButtonClicked {
7986 [self setObject:[NSNumber numberWithBool:expert_]];
7990 [self updateRoleButton];
7996 /* Source Cell {{{ */
7997 @interface SourceCell : CYTableViewCell <
8005 - (void) setSource:(Source *)source;
8009 @implementation SourceCell
8011 - (void) clearSource {
8021 - (void) setSource:(Source *)source {
8025 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
8027 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8028 icon_ = [icon_ retain];
8030 origin_ = [[source name] retain];
8031 label_ = [[source uri] retain];
8033 [content_ setNeedsDisplay];
8041 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8042 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8043 UIView *content([self contentView]);
8044 CGRect bounds([content bounds]);
8046 content_ = [[ContentView alloc] initWithFrame:bounds];
8047 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8048 [content_ setBackgroundColor:[UIColor whiteColor]];
8049 [content addSubview:content_];
8051 [content_ setDelegate:self];
8052 [content_ setOpaque:YES];
8056 - (NSString *) accessibilityLabel {
8060 - (void) drawContentRect:(CGRect)rect {
8061 bool highlighted(highlighted_);
8062 float width(rect.size.width);
8065 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8072 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8076 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8081 /* Source Controller {{{ */
8082 @interface SourceController : FilteredPackageListController {
8083 _transient Source *source_;
8087 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8091 @implementation SourceController
8093 - (NSURL *) navigationURL {
8094 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8097 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8098 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8100 key_ = [[source key] retain];
8104 - (void) reloadData {
8105 source_ = [database_ sourceWithKey:key_];
8107 key_ = [[source_ key] retain];
8108 [self setObject:source_];
8109 [[self navigationItem] setTitle:[source_ label]];
8116 /* Sources Controller {{{ */
8117 @interface SourcesController : CYViewController <
8118 UITableViewDataSource,
8121 _transient Database *database_;
8123 NSMutableArray *sources_;
8127 UIProgressHUD *hud_;
8130 //NSURLConnection *installer_;
8131 NSURLConnection *trivial_;
8132 NSURLConnection *trivial_bz2_;
8133 NSURLConnection *trivial_gz_;
8134 //NSURLConnection *automatic_;
8139 - (id) initWithDatabase:(Database *)database;
8140 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8144 @implementation SourcesController
8146 - (void) _releaseConnection:(NSURLConnection *)connection {
8147 if (connection != nil) {
8148 [connection cancel];
8149 //[connection setDelegate:nil];
8150 [connection release];
8155 [self releaseSubviews];
8161 //[self _releaseConnection:installer_];
8162 [self _releaseConnection:trivial_];
8163 [self _releaseConnection:trivial_gz_];
8164 [self _releaseConnection:trivial_bz2_];
8165 //[self _releaseConnection:automatic_];
8171 - (NSURL *) navigationURL {
8172 return [NSURL URLWithString:@"cydia://sources"];
8175 - (void) viewDidAppear:(BOOL)animated {
8176 [super viewDidAppear:animated];
8177 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8180 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8181 return offset_ == 0 ? 1 : 2;
8184 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8185 switch (section + (offset_ == 0 ? 1 : 0)) {
8186 case 0: return UCLocalize("ENTERED_BY_USER");
8187 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8193 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8194 int count = [sources_ count];
8196 case 0: return (offset_ == 0 ? count : offset_);
8197 case 1: return count - offset_;
8203 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8205 switch (indexPath.section) {
8206 case 0: idx = indexPath.row; break;
8207 case 1: idx = indexPath.row + offset_; break;
8211 return [sources_ objectAtIndex:idx];
8214 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8215 static NSString *cellIdentifier = @"SourceCell";
8217 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8218 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8219 [cell setSource:[self sourceAtIndexPath:indexPath]];
8220 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8225 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8226 Source *source = [self sourceAtIndexPath:indexPath];
8228 SourceController *controller = [[[SourceController alloc]
8229 initWithDatabase:database_
8233 [controller setDelegate:delegate_];
8235 [[self navigationController] pushViewController:controller animated:YES];
8238 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8239 Source *source = [self sourceAtIndexPath:indexPath];
8240 return [source record] != nil;
8243 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8244 Source *source = [self sourceAtIndexPath:indexPath];
8245 [Sources_ removeObjectForKey:[source key]];
8246 [delegate_ syncData];
8250 [delegate_ addTrivialSource:href_];
8251 [delegate_ syncData];
8254 - (NSString *) getWarning {
8255 NSString *href(href_);
8256 NSRange colon([href rangeOfString:@"://"]);
8257 if (colon.location != NSNotFound)
8258 href = [href substringFromIndex:(colon.location + 3)];
8259 href = [href stringByAddingPercentEscapes];
8260 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8261 href = [href stringByCachingURLWithCurrentCDN];
8263 NSURL *url([NSURL URLWithString:href]);
8265 NSStringEncoding encoding;
8266 NSError *error(nil);
8268 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8269 return [warning length] == 0 ? nil : warning;
8273 - (void) _endConnection:(NSURLConnection *)connection {
8274 // XXX: the memory management in this method is horribly awkward
8276 NSURLConnection **field = NULL;
8277 if (connection == trivial_)
8279 else if (connection == trivial_bz2_)
8280 field = &trivial_bz2_;
8281 else if (connection == trivial_gz_)
8282 field = &trivial_gz_;
8283 _assert(field != NULL);
8284 [connection release];
8289 trivial_bz2_ == nil &&
8295 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8298 UIAlertView *alert = [[[UIAlertView alloc]
8299 initWithTitle:UCLocalize("SOURCE_WARNING")
8302 cancelButtonTitle:UCLocalize("CANCEL")
8304 UCLocalize("ADD_ANYWAY"),
8308 [alert setContext:@"warning"];
8309 [alert setNumberOfRows:1];
8313 } else if (error_ != nil) {
8314 UIAlertView *alert = [[[UIAlertView alloc]
8315 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8316 message:[error_ localizedDescription]
8318 cancelButtonTitle:UCLocalize("OK")
8319 otherButtonTitles:nil
8322 [alert setContext:@"urlerror"];
8325 UIAlertView *alert = [[[UIAlertView alloc]
8326 initWithTitle:UCLocalize("NOT_REPOSITORY")
8327 message:UCLocalize("NOT_REPOSITORY_EX")
8329 cancelButtonTitle:UCLocalize("OK")
8330 otherButtonTitles:nil
8333 [alert setContext:@"trivial"];
8337 [delegate_ releaseNetworkActivityIndicator];
8339 [delegate_ removeProgressHUD:hud_];
8348 if (error_ != nil) {
8355 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8356 switch ([response statusCode]) {
8362 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8363 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8365 error_ = [error retain];
8366 [self _endConnection:connection];
8369 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8370 [self _endConnection:connection];
8373 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8374 NSMutableURLRequest *request = [NSMutableURLRequest
8375 requestWithURL:[NSURL URLWithString:href]
8376 cachePolicy:NSURLRequestUseProtocolCachePolicy
8377 timeoutInterval:120.0
8380 [request setHTTPMethod:method];
8382 if (Machine_ != NULL)
8383 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8384 if (UniqueID_ != nil)
8385 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8387 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8390 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8391 NSString *context([alert context]);
8393 if ([context isEqualToString:@"source"]) {
8396 NSString *href = [[alert textField] text];
8398 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8400 if (![href hasSuffix:@"/"])
8401 href_ = [href stringByAppendingString:@"/"];
8404 href_ = [href_ retain];
8406 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8407 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8408 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8409 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8413 // XXX: this is stupid
8414 hud_ = [[delegate_ addProgressHUD] retain];
8415 [hud_ setText:UCLocalize("VERIFYING_URL")];
8416 [delegate_ retainNetworkActivityIndicator];
8425 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8426 } else if ([context isEqualToString:@"trivial"])
8427 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8428 else if ([context isEqualToString:@"urlerror"])
8429 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8430 else if ([context isEqualToString:@"warning"]) {
8445 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8450 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8452 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8453 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8454 [list_ setRowHeight:56];
8455 [list_ setDataSource:self];
8456 [list_ setDelegate:self];
8457 [[self view] addSubview:list_];
8460 - (void) viewDidLoad {
8461 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8462 [self updateButtonsForEditingStatus:NO animated:NO];
8465 - (void) releaseSubviews {
8470 - (id) initWithDatabase:(Database *)database {
8471 if ((self = [super init]) != nil) {
8472 database_ = database;
8473 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8477 - (void) reloadData {
8481 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8484 [sources_ removeAllObjects];
8485 [sources_ addObjectsFromArray:[database_ sources]];
8487 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8490 int count([sources_ count]);
8492 for (int i = 0; i != count; i++) {
8493 if ([[sources_ objectAtIndex:i] record] == nil)
8498 [list_ setEditing:NO];
8499 [self updateButtonsForEditingStatus:NO animated:NO];
8503 - (void) showAddSourcePrompt {
8504 UIAlertView *alert = [[[UIAlertView alloc]
8505 initWithTitle:UCLocalize("ENTER_APT_URL")
8508 cancelButtonTitle:UCLocalize("CANCEL")
8510 UCLocalize("ADD_SOURCE"),
8514 [alert setContext:@"source"];
8515 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8517 [alert setNumberOfRows:1];
8518 [alert addTextFieldWithValue:@"http://" label:@""];
8520 UITextInputTraits *traits = [[alert textField] textInputTraits];
8521 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8522 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8523 [traits setKeyboardType:UIKeyboardTypeURL];
8524 // XXX: UIReturnKeyDone
8525 [traits setReturnKeyType:UIReturnKeyNext];
8530 - (void) addButtonClicked {
8531 [self showAddSourcePrompt];
8534 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8535 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8536 initWithTitle:UCLocalize("ADD")
8537 style:UIBarButtonItemStylePlain
8539 action:@selector(addButtonClicked)
8540 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8542 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8543 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8544 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8546 action:@selector(editButtonClicked)
8547 ] autorelease] animated:animated];
8549 if (IsWildcat_ && !editing)
8550 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8551 initWithTitle:UCLocalize("SETTINGS")
8552 style:UIBarButtonItemStylePlain
8554 action:@selector(settingsButtonClicked)
8558 - (void) settingsButtonClicked {
8559 [delegate_ showSettings];
8562 - (void) editButtonClicked {
8563 [list_ setEditing:![list_ isEditing] animated:YES];
8565 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8571 /* Settings Controller {{{ */
8572 @interface SettingsController : CYViewController <
8573 UITableViewDataSource,
8576 _transient Database *database_;
8577 // XXX: ok, "roledelegate_"?...
8578 _transient id roledelegate_;
8579 UITableView *table_;
8580 UISegmentedControl *segment_;
8584 - (void) showDoneButton;
8585 - (void) resizeSegmentedControl;
8589 @implementation SettingsController
8592 [self releaseSubviews];
8598 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8600 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8601 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8602 [table_ setDelegate:self];
8603 [table_ setDataSource:self];
8604 [[self view] addSubview:table_];
8606 NSArray *items = [NSArray arrayWithObjects:
8608 UCLocalize("HACKER"),
8609 UCLocalize("DEVELOPER"),
8611 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8612 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8613 [container_ addSubview:segment_];
8616 - (void) viewDidLoad {
8617 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8620 if ([Role_ isEqualToString:@"User"]) index = 0;
8621 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8622 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8624 [segment_ setSelectedSegmentIndex:index];
8625 [self showDoneButton];
8628 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8629 [self resizeSegmentedControl];
8632 - (void) releaseSubviews {
8639 [container_ release];
8643 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8644 if ((self = [super init]) != nil) {
8645 database_ = database;
8646 roledelegate_ = delegate;
8650 - (void) resizeSegmentedControl {
8651 CGFloat width = [[self view] frame].size.width;
8652 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8655 - (void) viewWillAppear:(BOOL)animated {
8656 [super viewWillAppear:animated];
8658 [self resizeSegmentedControl];
8661 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8662 [self resizeSegmentedControl];
8665 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8666 [self resizeSegmentedControl];
8670 NSString *role(nil);
8672 switch ([segment_ selectedSegmentIndex]) {
8673 case 0: role = @"User"; break;
8674 case 1: role = @"Hacker"; break;
8675 case 2: role = @"Developer"; break;
8680 if (![role isEqualToString:Role_]) {
8681 bool rolling(Role_ == nil);
8684 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8688 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8692 [roledelegate_ loadData];
8694 [roledelegate_ updateData];
8698 - (void) segmentChanged:(UISegmentedControl *)control {
8699 [self showDoneButton];
8702 - (void) saveAndClose {
8705 [[self navigationItem] setRightBarButtonItem:nil];
8706 [[self navigationController] dismissModalViewControllerAnimated:YES];
8709 - (void) doneButtonClicked {
8710 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8711 [spinner startAnimating];
8712 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8713 [[self navigationItem] setRightBarButtonItem:spinItem];
8715 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8718 - (void) showDoneButton {
8719 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8720 initWithTitle:UCLocalize("DONE")
8721 style:UIBarButtonItemStyleDone
8723 action:@selector(doneButtonClicked)
8724 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8727 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8728 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8732 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8736 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8737 return nil; // This method is required by the protocol.
8740 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8742 return UCLocalize("ROLE_EX");
8744 return [NSString stringWithFormat:
8745 @"%@: %@\n%@: %@\n%@: %@",
8746 UCLocalize("USER"), UCLocalize("USER_EX"),
8747 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8748 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8753 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8754 return section == 3 ? 44.0f : 0;
8757 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8758 return section == 3 ? container_ : nil;
8761 - (void) reloadData {
8763 [table_ reloadData];
8768 /* Stash Controller {{{ */
8769 @interface StashController : CYViewController {
8770 UIActivityIndicatorView *spinner_;
8777 @implementation StashController
8780 [self releaseSubviews];
8786 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8787 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8789 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8790 CGRect spinrect = [spinner_ frame];
8791 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8792 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8793 [spinner_ setFrame:spinrect];
8794 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8795 [[self view] addSubview:spinner_];
8796 [spinner_ startAnimating];
8799 captrect.size.width = [[self view] frame].size.width;
8800 captrect.size.height = 40.0f;
8801 captrect.origin.x = 0;
8802 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8803 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8804 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8805 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8806 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8807 [caption_ setTextColor:[UIColor whiteColor]];
8808 [caption_ setBackgroundColor:[UIColor clearColor]];
8809 [caption_ setShadowColor:[UIColor blackColor]];
8810 [caption_ setTextAlignment:UITextAlignmentCenter];
8811 [[self view] addSubview:caption_];
8814 statusrect.size.width = [[self view] frame].size.width;
8815 statusrect.size.height = 30.0f;
8816 statusrect.origin.x = 0;
8817 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8818 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8819 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8820 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8821 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8822 [status_ setTextColor:[UIColor whiteColor]];
8823 [status_ setBackgroundColor:[UIColor clearColor]];
8824 [status_ setShadowColor:[UIColor blackColor]];
8825 [status_ setTextAlignment:UITextAlignmentCenter];
8826 [[self view] addSubview:status_];
8829 - (void) releaseSubviews {
8843 @interface Cydia : UIApplication <
8844 ConfirmationControllerDelegate,
8847 UINavigationControllerDelegate,
8848 UITabBarControllerDelegate
8850 // XXX: evaluate all fields for _transient
8853 CYTabBarController *tabbar_;
8854 CYEmulatedLoadingController *emulated_;
8856 NSMutableArray *essential_;
8857 NSMutableArray *broken_;
8859 Database *database_;
8866 StashController *stash_;
8875 @implementation Cydia
8877 - (void) beginUpdate {
8878 [tabbar_ beginUpdate];
8882 return [tabbar_ updating];
8886 if ([broken_ count] != 0) {
8887 int count = [broken_ count];
8889 UIAlertView *alert = [[[UIAlertView alloc]
8890 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8891 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8893 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8895 UCLocalize("TEMPORARY_IGNORE"),
8899 [alert setContext:@"fixhalf"];
8900 [alert setNumberOfRows:2];
8902 } else if (!Ignored_ && [essential_ count] != 0) {
8903 int count = [essential_ count];
8905 UIAlertView *alert = [[[UIAlertView alloc]
8906 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8907 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8909 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8911 UCLocalize("UPGRADE_ESSENTIAL"),
8912 UCLocalize("COMPLETE_UPGRADE"),
8916 [alert setContext:@"upgrade"];
8921 - (void) _saveConfig {
8927 NSString *error(nil);
8929 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8931 NSError *error(nil);
8932 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8933 NSLog(@"failure to save metadata data: %@", error);
8938 NSLog(@"failure to serialize metadata: %@", error);
8943 // Navigation controller for the queuing badge.
8944 - (CYNavigationController *) queueNavigationController {
8945 NSArray *controllers = [tabbar_ viewControllers];
8946 return [controllers objectAtIndex:3];
8949 - (void) _updateData {
8952 [tabbar_ reloadData];
8954 CYNavigationController *navigation = [self queueNavigationController];
8956 id queuedelegate = nil;
8957 if ([[navigation viewControllers] count] > 0)
8958 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8960 [queuedelegate queueStatusDidChange];
8961 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8964 - (void) _refreshIfPossible:(NSDate *)update {
8965 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8967 bool recently = false;
8968 if (update != nil) {
8969 NSTimeInterval interval([update timeIntervalSinceNow]);
8970 if (interval <= 0 && interval > -(15*60))
8974 // Don't automatic refresh if:
8975 // - We already refreshed recently.
8976 // - We already auto-refreshed this launch.
8977 // - Auto-refresh is disabled.
8978 if (recently || loaded_ || ManualRefresh) {
8979 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8981 // If we are cancelling, we need to make sure it knows it's already loaded.
8985 // We are going to load, so remember that.
8989 SCNetworkReachabilityFlags flags; {
8990 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8991 SCNetworkReachabilityGetFlags(reachability, &flags);
8992 CFRelease(reachability);
8995 // XXX: this elaborate mess is what Apple is using to determine this? :(
8996 // XXX: do we care if the user has to intervene? maybe that's ok?
8998 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8999 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9000 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9001 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9002 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9003 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9007 // If we can reach the server, auto-refresh!
9009 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9014 - (void) refreshIfPossible {
9015 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9018 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
9019 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9020 [hud setText:UCLocalize("RELOADING_DATA")];
9022 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9025 [self removeProgressHUD:hud];
9029 [essential_ removeAllObjects];
9030 [broken_ removeAllObjects];
9032 NSArray *packages([database_ packages]);
9033 for (Package *package in packages) {
9035 [broken_ addObject:package];
9036 if ([package upgradableAndEssential:NO]) {
9037 if ([package essential])
9038 [essential_ addObject:package];
9043 NSLog(@"changes:#%u", changes);
9045 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9048 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9049 [changesItem setBadgeValue:badge];
9050 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9051 [self setApplicationIconBadgeNumber:changes];
9054 [changesItem setBadgeValue:nil];
9055 [changesItem setAnimatedBadge:NO];
9056 [self setApplicationIconBadgeNumber:0];
9061 [self refreshIfPossible];
9064 - (void) updateData {
9073 @synchronized (self) {
9074 [self _reloadDataWithInvocation:nil];
9078 - (void) disemulate {
9079 if (emulated_ == nil)
9082 [window_ addSubview:[tabbar_ view]];
9083 [[emulated_ view] removeFromSuperview];
9084 [emulated_ release];
9086 [window_ setUserInteractionEnabled:YES];
9089 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9090 UINavigationController *navigation([[[CYNavigationController alloc] initWithRootViewController:controller] autorelease]);
9092 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9094 UIViewController *parent;
9095 if (emulated_ == nil)
9104 [parent presentModalViewController:navigation animated:YES];
9107 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9108 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9110 if (navigation != nil)
9111 [navigation pushViewController:progress animated:YES];
9113 [self presentModalViewController:progress force:YES];
9115 [progress invoke:invocation withTitle:title];
9119 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9120 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9123 - (void) repairWithInvocation:(NSInvocation *)invocation {
9125 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9129 - (void) repairWithSelector:(SEL)selector {
9130 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9136 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
9137 _assert(file != NULL);
9139 for (NSString *key in [Sources_ allKeys]) {
9140 NSDictionary *source([Sources_ objectForKey:key]);
9142 fprintf(file, "%s %s %s\n",
9143 [[source objectForKey:@"Type"] UTF8String],
9144 [[source objectForKey:@"URI"] UTF8String],
9145 [[source objectForKey:@"Distribution"] UTF8String]
9151 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9156 - (void) addTrivialSource:(NSString *)href {
9157 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
9160 @"./", @"Distribution",
9161 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
9166 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9167 @synchronized (self) {
9168 [self _reloadDataWithInvocation:invocation];
9172 - (void) reloadData {
9173 [self reloadDataWithInvocation:nil];
9177 pkgProblemResolver *resolver = [database_ resolver];
9179 resolver->InstallProtect();
9180 if (!resolver->Resolve(true))
9185 // XXX: this is a really crappy way of doing this.
9186 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9187 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9188 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9189 if ([tabbar_ updating])
9190 [tabbar_ cancelUpdate];
9192 if (![database_ prepare])
9195 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9196 [page setDelegate:self];
9197 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
9198 [confirm_ setDelegate:self];
9201 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9202 [tabbar_ presentModalViewController:confirm_ animated:YES];
9208 @synchronized (self) {
9213 - (void) clearPackage:(Package *)package {
9214 @synchronized (self) {
9221 - (void) installPackages:(NSArray *)packages {
9222 @synchronized (self) {
9223 for (Package *package in packages)
9230 - (void) installPackage:(Package *)package {
9231 @synchronized (self) {
9238 - (void) removePackage:(Package *)package {
9239 @synchronized (self) {
9246 - (void) distUpgrade {
9247 @synchronized (self) {
9248 if (![database_ upgrade])
9254 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9257 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
9262 - (void) showSettings {
9263 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9264 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9266 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9267 [tabbar_ presentModalViewController:nav animated:YES];
9270 - (void) retainNetworkActivityIndicator {
9271 if (activity_++ == 0)
9272 [self setNetworkActivityIndicatorVisible:YES];
9275 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9279 - (void) releaseNetworkActivityIndicator {
9280 if (--activity_ == 0)
9281 [self setNetworkActivityIndicatorVisible:NO];
9284 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9289 - (void) cancelAndClear:(bool)clear {
9290 @synchronized (self) {
9302 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9303 NSString *context([alert context]);
9305 if ([context isEqualToString:@"conffile"]) {
9306 FILE *input = [database_ input];
9307 if (button == [alert cancelButtonIndex])
9308 fprintf(input, "N\n");
9309 else if (button == [alert firstOtherButtonIndex])
9310 fprintf(input, "Y\n");
9313 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9314 } else if ([context isEqualToString:@"fixhalf"]) {
9315 if (button == [alert cancelButtonIndex]) {
9316 @synchronized (self) {
9317 for (Package *broken in broken_) {
9320 NSString *id = [broken id];
9321 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9322 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9323 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9324 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9330 } else if (button == [alert firstOtherButtonIndex]) {
9331 [broken_ removeAllObjects];
9335 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9336 } else if ([context isEqualToString:@"upgrade"]) {
9337 if (button == [alert firstOtherButtonIndex]) {
9338 @synchronized (self) {
9339 for (Package *essential in essential_)
9340 [essential install];
9345 } else if (button == [alert firstOtherButtonIndex] + 1) {
9347 } else if (button == [alert cancelButtonIndex]) {
9351 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9355 - (void) system:(NSString *)command { _pooled
9357 system([command UTF8String]);
9361 - (void) applicationWillSuspend {
9363 [super applicationWillSuspend];
9366 - (BOOL) isSafeToSuspend {
9369 NSLog(@"isSafeToSuspend: locked_ != 0");
9374 // Use external process status API internally.
9375 // This is probably a really bad idea.
9376 // XXX: what is the point of this? does this solve anything at all?
9377 uint64_t status = 0;
9379 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9380 notify_get_state(notify_token, &status);
9381 notify_cancel(notify_token);
9386 NSLog(@"isSafeToSuspend: status != 0");
9392 NSLog(@"isSafeToSuspend: -> true");
9397 - (void) applicationSuspend:(__GSEvent *)event {
9398 if ([self isSafeToSuspend])
9399 [super applicationSuspend:event];
9402 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9403 if ([self isSafeToSuspend])
9404 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9407 - (void) _setSuspended:(BOOL)value {
9408 if ([self isSafeToSuspend])
9409 [super _setSuspended:value];
9412 - (UIProgressHUD *) addProgressHUD {
9413 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9414 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9416 [window_ setUserInteractionEnabled:NO];
9419 UIViewController *target = tabbar_;
9420 while ([target modalViewController] != nil) target = [target modalViewController];
9421 [[target view] addSubview:hud];
9427 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9429 [hud removeFromSuperview];
9430 [window_ setUserInteractionEnabled:YES];
9434 - (CYViewController *) pageForPackage:(NSString *)name {
9435 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9438 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9439 NSString *scheme([[url scheme] lowercaseString]);
9440 if ([[url absoluteString] length] <= [scheme length] + 3)
9442 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9443 NSArray *components([path pathComponents]);
9445 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9446 return [self pageForPackage:[components objectAtIndex:1]];
9448 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9451 NSString *base([components objectAtIndex:0]);
9453 CYViewController *controller = nil;
9455 if ([base isEqualToString:@"url"]) {
9456 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9457 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9458 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9459 } else if (!external && [components count] == 1) {
9460 if ([base isEqualToString:@"manage"]) {
9461 controller = [[[ManageController alloc] init] autorelease];
9464 if ([base isEqualToString:@"sources"]) {
9465 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9468 if ([base isEqualToString:@"home"]) {
9469 controller = [[[HomeController alloc] init] autorelease];
9472 if ([base isEqualToString:@"sections"]) {
9473 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9476 if ([base isEqualToString:@"search"]) {
9477 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9480 if ([base isEqualToString:@"changes"]) {
9481 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9484 if ([base isEqualToString:@"installed"]) {
9485 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9487 } else if ([components count] == 2) {
9488 NSString *argument = [components objectAtIndex:1];
9490 if ([base isEqualToString:@"package"]) {
9491 controller = [self pageForPackage:argument];
9494 if (!external && [base isEqualToString:@"search"]) {
9495 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9496 [(SearchController *)controller setSearchTerm:argument];
9499 if (!external && [base isEqualToString:@"sections"]) {
9500 if ([argument isEqualToString:@"all"])
9502 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9505 if (!external && [base isEqualToString:@"sources"]) {
9506 if ([argument isEqualToString:@"add"]) {
9507 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9508 [(SourcesController *)controller showAddSourcePrompt];
9510 Source *source = [database_ sourceWithKey:argument];
9511 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9515 if (!external && [base isEqualToString:@"launch"]) {
9516 [self launchApplicationWithIdentifier:argument suspended:NO];
9519 } else if (!external && [components count] == 3) {
9520 NSString *arg1 = [components objectAtIndex:1];
9521 NSString *arg2 = [components objectAtIndex:2];
9523 if ([base isEqualToString:@"package"]) {
9524 if ([arg2 isEqualToString:@"settings"]) {
9525 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9526 } else if ([arg2 isEqualToString:@"files"]) {
9527 if (Package *package = [database_ packageWithName:arg1]) {
9528 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9529 [(FileTable *)controller setPackage:package];
9535 [controller setDelegate:self];
9539 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9540 CYViewController *page([self pageForURL:url forExternal:external]);
9543 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9544 [nav setViewControllers:[NSArray arrayWithObject:page]];
9545 [tabbar_ setUnselectedViewController:nav];
9551 - (void) applicationOpenURL:(NSURL *)url {
9552 [super applicationOpenURL:url];
9554 if (!loaded_) starturl_ = [url retain];
9555 else [self openCydiaURL:url forExternal:YES];
9558 - (void) applicationWillResignActive:(UIApplication *)application {
9559 // Stop refreshing if you get a phone call or lock the device.
9560 if ([tabbar_ updating])
9561 [tabbar_ cancelUpdate];
9563 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9564 [super applicationWillResignActive:application];
9567 - (void) applicationWillTerminate:(UIApplication *)application {
9569 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9570 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9571 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9576 - (void) setConfigurationData:(NSString *)data {
9577 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9579 if (!conffile_r(data)) {
9580 lprintf("E:invalid conffile\n");
9584 NSString *ofile = conffile_r[1];
9585 //NSString *nfile = conffile_r[2];
9587 UIAlertView *alert = [[[UIAlertView alloc]
9588 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9589 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9591 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9593 UCLocalize("ACCEPT_NEW_COPY"),
9594 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9598 [alert setContext:@"conffile"];
9599 [alert setNumberOfRows:2];
9603 - (void) addStashController {
9605 stash_ = [[StashController alloc] init];
9606 [window_ addSubview:[stash_ view]];
9609 - (void) removeStashController {
9610 [[stash_ view] removeFromSuperview];
9616 [self setIdleTimerDisabled:YES];
9618 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9619 UpdateExternalStatus(1);
9620 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9621 UpdateExternalStatus(0);
9623 [self removeStashController];
9625 if (ExecFork() == 0) {
9626 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9627 perror("launchctl stop");
9631 - (void) setupViewControllers {
9632 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9634 NSMutableArray *items([NSMutableArray arrayWithObjects:
9635 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9636 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9637 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9638 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9642 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9643 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9645 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9648 NSMutableArray *controllers([NSMutableArray array]);
9649 for (UITabBarItem *item in items) {
9650 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9651 [controller setTabBarItem:item];
9652 [controllers addObject:controller];
9654 [tabbar_ setViewControllers:controllers];
9656 [tabbar_ setUpdateDelegate:self];
9659 - (void) addCydiaHost:(NSString *)host {
9660 [CydiaHosts_ addObject:host];
9663 - (void) applicationDidFinishLaunching:(id)unused {
9665 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9666 [self setApplicationSupportsShakeToEdit:NO];
9668 [self addCydiaHost:[[NSURL URLWithString:CydiaURL(@"")] host]];
9670 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9671 initWithMemoryCapacity:524288
9672 diskCapacity:10485760
9673 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9676 [CYBrowserController _initialize];
9678 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9680 Font12_ = [[UIFont systemFontOfSize:12] retain];
9681 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9682 Font14_ = [[UIFont systemFontOfSize:14] retain];
9683 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9684 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9686 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9687 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9689 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9690 [window_ orderFront:self];
9691 [window_ makeKey:self];
9692 [window_ setHidden:NO];
9695 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9696 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9697 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9698 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9699 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9700 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9701 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9702 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9703 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9706 [self addStashController];
9707 // XXX: this would be much cleaner as a yieldToSelector:
9708 // that way the removeStashController could happen right here inline
9709 // we also could no longer require the useless stash_ field anymore
9710 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9714 database_ = [Database sharedInstance];
9715 [database_ setDelegate:self];
9717 [window_ setUserInteractionEnabled:NO];
9718 [self setupViewControllers];
9720 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9721 [window_ addSubview:[emulated_ view]];
9723 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9730 [window_ setUserInteractionEnabled:YES];
9731 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9734 if ([emulated_ modalViewController] != nil)
9735 [emulated_ dismissModalViewControllerAnimated:YES];
9736 [window_ setUserInteractionEnabled:NO];
9744 int selectedIndex = 0;
9745 NSMutableArray *items = nil;
9747 bool recently = false;
9748 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9749 if (closed != nil) {
9750 NSTimeInterval interval([closed timeIntervalSinceNow]);
9751 // XXX: Is 15 minutes the optimal time here?
9752 if (interval <= 0 && interval > -(15*60))
9756 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9757 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9760 for (NSArray *entry in items)
9761 if ([entry count] <= 0)
9764 if (!recently || !items || !enough) {
9766 items = [NSMutableArray array];
9767 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9768 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9769 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9771 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9773 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9774 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9776 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9779 [tabbar_ setSelectedIndex:selectedIndex];
9780 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9781 NSArray *stack = [items objectAtIndex:tab];
9782 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9783 NSMutableArray *current = [NSMutableArray array];
9785 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9786 NSString *addr = [stack objectAtIndex:nav];
9787 NSURL *url = [NSURL URLWithString:addr];
9788 CYViewController *page = [self pageForURL:url forExternal:NO];
9790 [current addObject:page];
9793 [navigation setViewControllers:current];
9796 // (Try to) show the startup URL.
9797 if (starturl_ != nil) {
9798 [self openCydiaURL:starturl_ forExternal:NO];
9799 [starturl_ release];
9804 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9805 if (item != nil && IsWildcat_) {
9806 [sheet showFromBarButtonItem:item animated:YES];
9808 [sheet showInView:window_];
9812 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9813 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9814 [progress setTitle:task];
9815 [progress addProgressEvent:event];
9818 - (void) addProgressEventForTask:(NSArray *)data {
9819 CydiaProgressEvent *event([data objectAtIndex:0]);
9820 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9821 [self addProgressEvent:event forTask:task];
9824 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9825 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9831 id Alloc_(id self, SEL selector) {
9832 id object = alloc_(self, selector);
9833 lprintf("[%s]A-%p\n", self->isa->name, object);
9838 id Dealloc_(id self, SEL selector) {
9839 id object = dealloc_(self, selector);
9840 lprintf("[%s]D-%p\n", self->isa->name, object);
9844 Class $WebDefaultUIKitDelegate;
9846 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9847 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9848 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9849 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9852 static NSNumber *shouldPlayKeyboardSounds;
9856 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9858 case 1104: // Keyboard Button Clicked
9859 case 1105: // Keyboard Delete Repeated
9860 if (shouldPlayKeyboardSounds == nil) {
9861 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9862 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9865 if (![shouldPlayKeyboardSounds boolValue])
9869 _UIHardware$_playSystemSound$(self, _cmd, sound);
9873 Class $UIApplication;
9875 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9876 static BOOL initialized = NO;
9877 static BOOL started = NO;
9879 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9880 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9882 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9883 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9884 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9885 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9887 if (initialized && !enabled) {
9889 [bundle performSelector:@selector(_accessibilityStopServer)];
9890 } else if (enabled) {
9894 [bundle performSelector:@selector(_accessibilityStartServer)];
9900 int main(int argc, char *argv[]) { _pooled
9903 UpdateExternalStatus(0);
9905 if (Class $UIDevice = objc_getClass("UIDevice")) {
9906 UIDevice *device([$UIDevice currentDevice]);
9907 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9911 UIScreen *screen([UIScreen mainScreen]);
9912 if ([screen respondsToSelector:@selector(scale)])
9913 ScreenScale_ = [screen scale];
9917 UIDevice *device([UIDevice currentDevice]);
9918 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9921 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9922 if (idiom == UIUserInterfaceIdiomPhone)
9924 else if (idiom == UIUserInterfaceIdiomPad)
9927 NSLog(@"unknown UIUserInterfaceIdiom!");
9930 CydiaHosts_ = [NSMutableSet setWithCapacity:2];
9932 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9934 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9936 /* Library Hacks {{{ */
9937 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9939 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9940 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9941 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9942 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9943 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9946 $UIHardware = objc_getClass("UIHardware");
9947 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9948 if (UIHardware$_playSystemSound$ != NULL) {
9949 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9950 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9953 $UIApplication = objc_getClass("UIApplication");
9954 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9955 if (UIApplication$_updateApplicationAccessibility != NULL) {
9956 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9957 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9960 /* Set Locale {{{ */
9961 Locale_ = CFLocaleCopyCurrent();
9962 Languages_ = [NSLocale preferredLanguages];
9963 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9964 //NSLog(@"%@", [Languages_ description]);
9967 if (Languages_ == nil || [Languages_ count] == 0)
9968 // XXX: consider just setting to C and then falling through?
9971 lang = [[Languages_ objectAtIndex:0] UTF8String];
9972 setenv("LANG", lang, true);
9973 std::setlocale(LC_ALL, lang);
9976 NSLog(@"Setting Language: %s", lang);
9979 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9981 /* Parse Arguments {{{ */
9982 bool substrate(false);
9988 for (int argi(1); argi != argc; ++argi)
9989 if (strcmp(argv[argi], "--") == 0) {
9991 argv[argi] = argv[0];
9997 for (int argi(1); argi != arge; ++argi)
9998 if (strcmp(args[argi], "--substrate") == 0)
10001 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10005 App_ = [[NSBundle mainBundle] bundlePath];
10011 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10012 alloc_ = alloc->method_imp;
10013 alloc->method_imp = (IMP) &Alloc_;*/
10015 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10016 dealloc_ = dealloc->method_imp;
10017 dealloc->method_imp = (IMP) &Dealloc_;*/
10019 /* System Information {{{ */
10023 size = sizeof(maxproc);
10024 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10025 perror("sysctlbyname(\"kern.maxproc\", ?)");
10026 else if (maxproc < 64) {
10028 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10029 perror("sysctlbyname(\"kern.maxproc\", #)");
10032 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10033 char *osversion = new char[size];
10034 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10035 perror("sysctlbyname(\"kern.osversion\", ?)");
10037 System_ = [NSString stringWithUTF8String:osversion];
10039 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10040 char *machine = new char[size];
10041 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10042 perror("sysctlbyname(\"hw.machine\", ?)");
10044 Machine_ = machine;
10046 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
10047 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
10048 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
10049 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
10053 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
10054 NSData *data((NSData *) ecid);
10055 size_t length([data length]);
10056 uint8_t bytes[length];
10057 [data getBytes:bytes];
10058 char string[length * 2 + 1];
10059 for (size_t i(0); i != length; ++i)
10060 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
10061 ChipID_ = [NSString stringWithUTF8String:string];
10065 IOObjectRelease(service);
10069 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
10071 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10072 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10073 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10075 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10076 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10077 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10079 if (mcc != NULL && mnc != NULL)
10080 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10087 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10088 Build_ = [system objectForKey:@"ProductBuildVersion"];
10089 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10090 Product_ = [info objectForKey:@"SafariProductVersion"];
10091 Safari_ = [info objectForKey:@"CFBundleVersion"];
10094 /* Load Database {{{ */
10096 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10098 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10100 if (Metadata_ == NULL)
10101 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10103 Settings_ = [Metadata_ objectForKey:@"Settings"];
10105 Packages_ = [Metadata_ objectForKey:@"Packages"];
10106 Sections_ = [Metadata_ objectForKey:@"Sections"];
10107 Sources_ = [Metadata_ objectForKey:@"Sources"];
10109 Token_ = [Metadata_ objectForKey:@"Token"];
10112 if (Settings_ != nil)
10113 Role_ = [Settings_ objectForKey:@"Role"];
10115 if (Sections_ == nil) {
10116 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10117 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10120 if (Sources_ == nil) {
10121 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10122 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10127 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10130 if (Packages_ != nil) {
10132 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10136 [Metadata_ removeObjectForKey:@"Packages"];
10142 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10144 #define MobileSubstrate_(name) \
10145 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10146 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10147 if (handle == NULL) \
10148 NSLog(@"%s", dlerror()); \
10151 MobileSubstrate_(Activator)
10152 MobileSubstrate_(libstatusbar)
10153 MobileSubstrate_(SimulatedKeyEvents)
10154 MobileSubstrate_(WinterBoard)
10156 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10157 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10159 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10161 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10162 unlink("/tmp/.cydia.fw");
10164 } else if (access("/User", F_OK) != 0 || version < 4) {
10167 system("/usr/libexec/cydia/firmware.sh");
10171 _assert([[NSFileManager defaultManager]
10172 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10173 withIntermediateDirectories:YES
10178 if (access("/tmp/cydia.chk", F_OK) == 0) {
10179 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10180 _assert(errno == ENOENT);
10181 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10182 _assert(errno == ENOENT);
10185 /* APT Initialization {{{ */
10186 _assert(pkgInitConfig(*_config));
10187 _assert(pkgInitSystem(*_config, _system));
10190 _config->Set("APT::Acquire::Translation", lang);
10192 // XXX: this timeout might be important :(
10193 //_config->Set("Acquire::http::Timeout", 15);
10195 _config->Set("Acquire::http::MaxParallel", 3);
10197 /* Color Choices {{{ */
10198 space_ = CGColorSpaceCreateDeviceRGB();
10200 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10201 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10202 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10203 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10204 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10205 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10206 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10207 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10208 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10210 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10211 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10213 /* UIKit Configuration {{{ */
10214 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10215 if ($GSFontSetUseLegacyFontMetrics != NULL)
10216 $GSFontSetUseLegacyFontMetrics(YES);
10218 // XXX: I have a feeling this was important
10219 //UIKeyboardDisableAutomaticAppearance();
10222 Colon_ = UCLocalize("COLON_DELIMITED");
10223 Elision_ = UCLocalize("ELISION");
10224 Error_ = UCLocalize("ERROR");
10225 Warning_ = UCLocalize("WARNING");
10228 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10230 CGColorSpaceRelease(space_);
10231 CFRelease(Locale_);