1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2010 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 // Hash Functions/Structures {{{
210 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
218 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
220 void NSLogPoint(const char *fix, const CGPoint &point) {
221 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
224 void NSLogRect(const char *fix, const CGRect &rect) {
225 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
228 static _finline NSString *CydiaURL(NSString *path) {
230 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
231 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
232 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
233 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
234 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
235 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
238 static _finline void UpdateExternalStatus(uint64_t newStatus) {
240 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
241 notify_set_state(notify_token, newStatus);
242 notify_cancel(notify_token);
244 notify_post("com.saurik.Cydia.status");
247 /* [NSObject yieldToSelector:(withObject:)] {{{*/
248 @interface NSObject (Cydia)
249 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
250 - (id) yieldToSelector:(SEL)selector;
253 @implementation NSObject (Cydia)
258 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
259 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
260 id object([[context objectAtIndex:1] nonretainedObjectValue]);
261 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
263 /* XXX: deal with exceptions */
264 id value([self performSelector:selector withObject:object]);
266 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
267 [context removeAllObjects];
268 if ([signature methodReturnLength] != 0 && value != nil)
269 [context addObject:value];
274 performSelectorOnMainThread:@selector(doNothing)
280 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
281 volatile bool stopped(false);
283 NSMutableArray *context([NSMutableArray arrayWithObjects:
284 [NSValue valueWithPointer:selector],
285 [NSValue valueWithNonretainedObject:object],
286 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
289 NSThread *thread([[[NSThread alloc]
291 selector:@selector(_yieldToContext:)
297 NSRunLoop *loop([NSRunLoop currentRunLoop]);
298 NSDate *future([NSDate distantFuture]);
300 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
302 return [context count] == 0 ? nil : [context objectAtIndex:0];
305 - (id) yieldToSelector:(SEL)selector {
306 return [self yieldToSelector:selector withObject:nil];
312 /* Cydia Action Sheet {{{ */
313 @interface CYActionSheet : UIAlertView {
317 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
320 @implementation CYActionSheet
322 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
323 if ((self = [super init])) {
324 [self setTitle:title];
325 [self setDelegate:self];
326 for (NSString *button in buttons) [self addButtonWithTitle:button];
327 [self setCancelButtonIndex:index];
331 - (void) _updateFrameForDisplay {
332 [super _updateFrameForDisplay];
333 if ([self cancelButtonIndex] == -1) {
334 NSArray *buttons = [self buttons];
335 if ([buttons count]) {
336 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
337 for (UIThreePartButton *button in buttons)
338 [button setBackground:background forState:0];
343 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
344 button_ = buttonIndex + 1;
348 [self dismissWithClickedButtonIndex:-1 animated:YES];
351 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
352 [self setRunsModal:YES];
361 /* NSForcedOrderingSearch doesn't work on the iPhone */
362 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
363 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
364 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
366 /* Information Dictionaries {{{ */
367 @interface NSMutableArray (Cydia)
368 - (void) addInfoDictionary:(NSDictionary *)info;
371 @implementation NSMutableArray (Cydia)
373 - (void) addInfoDictionary:(NSDictionary *)info {
374 [self addObject:info];
379 @interface NSMutableDictionary (Cydia)
380 - (void) addInfoDictionary:(NSDictionary *)info;
383 @implementation NSMutableDictionary (Cydia)
385 - (void) addInfoDictionary:(NSDictionary *)info {
386 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
392 #define lprintf(args...) fprintf(stderr, args)
395 #define TraceLogging (1 && !ForRelease)
396 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
397 #define ProfileTimes (0 && !ForRelease)
398 #define ForSaurik (0 && !ForRelease)
399 #define LogBrowser (0 && !ForRelease)
400 #define TrackResize (0 && !ForRelease)
401 #define ManualRefresh (1 && !ForRelease)
402 #define ShowInternals (0 && !ForRelease)
403 #define IgnoreInstall (0 && !ForRelease)
404 #define AlwaysReload (0 && !ForRelease)
405 #define TryIndexedCollation (0 && !ForRelease)
409 #define _trace(args...)
414 #define _profile(name) {
417 #define PrintTimes() do {} while (false)
421 typedef uint32_t (*SKRadixFunction)(id, void *);
423 @interface NSMutableArray (Radix)
424 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
432 @implementation NSMutableArray (Radix)
434 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
435 size_t count([self count]);
436 struct RadixItem_ *swap(new RadixItem_[count * 2]);
438 for (size_t i(0); i != count; ++i) {
439 RadixItem_ &item(swap[i]);
442 id object([self objectAtIndex:i]);
443 item.key = function(object, argument);
446 struct RadixItem_ *lhs(swap), *rhs(swap + count);
448 static const size_t width = 32;
449 static const size_t bits = 11;
450 static const size_t slots = 1 << bits;
451 static const size_t passes = (width + (bits - 1)) / bits;
453 size_t *hist(new size_t[slots]);
455 for (size_t pass(0); pass != passes; ++pass) {
456 memset(hist, 0, sizeof(size_t) * slots);
458 for (size_t i(0); i != count; ++i) {
459 uint32_t key(lhs[i].key);
461 key &= _not(uint32_t) >> width - bits;
466 for (size_t i(0); i != slots; ++i) {
467 size_t local(offset);
472 for (size_t i(0); i != count; ++i) {
473 uint32_t key(lhs[i].key);
475 key &= _not(uint32_t) >> width - bits;
476 rhs[hist[key]++] = lhs[i];
479 RadixItem_ *tmp(lhs);
486 const void **values(new const void *[count]);
487 for (size_t i(0); i != count; ++i)
488 values[i] = [self objectAtIndex:lhs[i].index];
489 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
497 /* Insertion Sort {{{ */
499 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
500 const char *ptr = (const char *)list;
502 CFIndex half = count / 2;
503 const char *probe = ptr + elementSize * half;
504 CFComparisonResult cr = comparator(element, probe, context);
505 if (0 == cr) return (probe - (const char *)list) / elementSize;
506 ptr = (cr < 0) ? ptr : probe + elementSize;
507 count = (cr < 0) ? half : (half + (count & 1) - 1);
509 return (ptr - (const char *)list) / elementSize;
512 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
513 const char *ptr = (const char *)list;
515 CFIndex half = count / 2;
516 const char *probe = ptr + elementSize * half;
517 CFComparisonResult cr = comparator(element, probe, context);
518 if (0 == cr) return (probe - (const char *)list) / elementSize;
519 ptr = (cr < 0) ? ptr : probe + elementSize;
520 count = (cr < 0) ? half : (half + (count & 1) - 1);
522 return (ptr - (const char *)list) / elementSize;
525 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
526 if (range.length == 0)
528 const void **values(new const void *[range.length]);
529 CFArrayGetValues(array, range, values);
531 #if HistogramInsertionSort > 0
532 uint32_t total(0), *offsets(new uint32_t[range.length]);
535 for (CFIndex index(1); index != range.length; ++index) {
536 const void *value(values[index]);
537 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
538 CFIndex correct(index);
539 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
540 #if HistogramInsertionSort > 1
541 NSLog(@"%@ < %@", value, values[correct - 1]);
546 if (correct != index) {
547 size_t offset(index - correct);
548 #if HistogramInsertionSort
552 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
554 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
555 values[correct] = value;
559 CFArrayReplaceValues(array, range, values, range.length);
562 #if HistogramInsertionSort > 0
563 for (CFIndex index(0); index != range.length; ++index)
564 if (offsets[index] != 0)
565 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
566 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
573 /* Apple Bug Fixes {{{ */
574 @implementation UIWebDocumentView (Cydia)
576 - (void) _setScrollerOffset:(CGPoint)offset {
577 UIScroller *scroller([self _scroller]);
579 CGSize size([scroller contentSize]);
580 CGSize bounds([scroller bounds].size);
583 max.x = size.width - bounds.width;
584 max.y = size.height - bounds.height;
592 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
593 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
595 [scroller setOffset:offset];
601 @implementation WebScriptObject (NSFastEnumeration)
603 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
604 size_t length([self count] - state->state);
607 else if (length > count)
609 for (size_t i(0); i != length; ++i)
610 objects[i] = [self objectAtIndex:state->state++];
611 state->itemsPtr = objects;
612 state->mutationsPtr = (unsigned long *) self;
618 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
619 size_t length([self length] - state->state);
622 else if (length > count)
624 for (size_t i(0); i != length; ++i)
625 objects[i] = [self item:state->state++];
626 state->itemsPtr = objects;
627 state->mutationsPtr = (unsigned long *) self;
631 /* Cydia NSString Additions {{{ */
632 @interface NSString (Cydia)
633 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
634 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
635 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
636 - (NSComparisonResult) compareByPath:(NSString *)other;
637 - (NSString *) stringByCachingURLWithCurrentCDN;
638 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
641 @implementation NSString (Cydia)
643 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
644 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
647 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
648 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
649 memcpy(data, bytes, length);
650 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
653 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
654 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
657 - (NSComparisonResult) compareByPath:(NSString *)other {
658 NSString *prefix = [self commonPrefixWithString:other options:0];
659 size_t length = [prefix length];
661 NSRange lrange = NSMakeRange(length, [self length] - length);
662 NSRange rrange = NSMakeRange(length, [other length] - length);
664 lrange = [self rangeOfString:@"/" options:0 range:lrange];
665 rrange = [other rangeOfString:@"/" options:0 range:rrange];
667 NSComparisonResult value;
669 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
670 value = NSOrderedSame;
671 else if (lrange.location == NSNotFound)
672 value = NSOrderedAscending;
673 else if (rrange.location == NSNotFound)
674 value = NSOrderedDescending;
676 value = NSOrderedSame;
678 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
679 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
680 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
681 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
683 NSComparisonResult result = [lpath compare:rpath];
684 return result == NSOrderedSame ? value : result;
687 - (NSString *) stringByCachingURLWithCurrentCDN {
689 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
690 withString:@"://cache.cydia.saurik.com/"
694 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
695 return [(id)CFURLCreateStringByAddingPercentEscapes(
700 kCFStringEncodingUTF8
707 /* C++ NSString Wrapper Cache {{{ */
708 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
709 return size == 0 ? NULL :
710 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
711 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
714 static _finline CFStringRef CYStringCreate(const char *data) {
715 return CYStringCreate(data, strlen(data));
724 _finline void clear_() {
725 if (cache_ != NULL) {
732 _finline bool empty() const {
736 _finline size_t size() const {
740 _finline char *data() const {
744 _finline void clear() {
749 _finline CYString() :
756 _finline ~CYString() {
760 void operator =(const CYString &rhs) {
764 if (rhs.cache_ == nil)
767 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
770 void copy(apr_pool_t *pool) {
771 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
772 memcpy(temp, data_, size_);
777 void set(apr_pool_t *pool, const char *data, size_t size) {
783 data_ = const_cast<char *>(data);
791 _finline void set(apr_pool_t *pool, const char *data) {
792 set(pool, data, data == NULL ? 0 : strlen(data));
795 _finline void set(apr_pool_t *pool, const std::string &rhs) {
796 set(pool, rhs.data(), rhs.size());
799 bool operator ==(const CYString &rhs) const {
800 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
803 _finline operator CFStringRef() {
805 cache_ = CYStringCreate(data_, size_);
809 _finline operator id() {
810 return (NSString *) static_cast<CFStringRef>(*this);
813 _finline operator const char *() {
814 return reinterpret_cast<const char *>(data_);
818 /* C++ NSString Algorithm Adapters {{{ */
820 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
823 struct NSStringMapHash :
824 std::unary_function<NSString *, size_t>
826 _finline size_t operator ()(NSString *value) const {
827 return CFStringHashNSString((CFStringRef) value);
831 struct NSStringMapLess :
832 std::binary_function<NSString *, NSString *, bool>
834 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
835 return [lhs compare:rhs] == NSOrderedAscending;
839 struct NSStringMapEqual :
840 std::binary_function<NSString *, NSString *, bool>
842 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
843 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
844 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
845 //[lhs isEqualToString:rhs];
850 /* Perl-Compatible RegEx {{{ */
860 Pcre(const char *regex) :
865 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
868 lprintf("%d:%s\n", offset, error);
872 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
873 matches_ = new int[(capture_ + 1) * 3];
881 NSString *operator [](size_t match) {
882 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
885 bool operator ()(NSString *data) {
886 // XXX: length is for characters, not for bytes
887 return operator ()([data UTF8String], [data length]);
890 bool operator ()(const char *data, size_t size) {
892 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
896 /* Mime Addresses {{{ */
897 @interface Address : NSObject {
903 - (NSString *) address;
905 - (void) setAddress:(NSString *)address;
907 + (Address *) addressWithString:(NSString *)string;
908 - (Address *) initWithString:(NSString *)string;
911 @implementation Address
920 - (NSString *) name {
924 - (NSString *) address {
928 - (void) setAddress:(NSString *)address {
930 [address_ autorelease];
934 address_ = [address retain];
937 + (Address *) addressWithString:(NSString *)string {
938 return [[[Address alloc] initWithString:string] autorelease];
941 + (NSArray *) _attributeKeys {
942 return [NSArray arrayWithObjects:@"address", @"name", nil];
945 - (NSArray *) attributeKeys {
946 return [[self class] _attributeKeys];
949 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
950 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
953 - (Address *) initWithString:(NSString *)string {
954 if ((self = [super init]) != nil) {
955 const char *data = [string UTF8String];
956 size_t size = [string length];
958 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
960 if (address_r(data, size)) {
961 name_ = [address_r[1] retain];
962 address_ = [address_r[2] retain];
964 name_ = [string retain];
972 /* CoreGraphics Primitives {{{ */
977 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
978 CGFloat color[] = {red, green, blue, alpha};
979 return CGColorCreate(space, color);
988 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
989 color_(Create_(space, red, green, blue, alpha))
991 Set(space, red, green, blue, alpha);
996 CGColorRelease(color_);
1003 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1005 color_ = Create_(space, red, green, blue, alpha);
1008 operator CGColorRef() {
1014 /* Random Global Variables {{{ */
1015 static const int PulseInterval_ = 50000;
1018 static NSArray *Finishes_;
1020 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1021 #define NotifyConfig_ "/etc/notify.conf"
1023 static bool Queuing_;
1025 static CYColor Blue_;
1026 static CYColor Blueish_;
1027 static CYColor Black_;
1028 static CYColor Off_;
1029 static CYColor White_;
1030 static CYColor Gray_;
1031 static CYColor Green_;
1032 static CYColor Purple_;
1033 static CYColor Purplish_;
1035 static UIColor *InstallingColor_;
1036 static UIColor *RemovingColor_;
1038 static NSString *App_;
1039 static NSString *Home_;
1041 static BOOL Advanced_;
1042 static BOOL Ignored_;
1044 static UIFont *Font12_;
1045 static UIFont *Font12Bold_;
1046 static UIFont *Font14_;
1047 static UIFont *Font18Bold_;
1048 static UIFont *Font22Bold_;
1050 static const char *Machine_ = NULL;
1051 static NSString *System_ = nil;
1052 static NSString *SerialNumber_ = nil;
1053 static NSString *ChipID_ = nil;
1054 static NSString *Token_ = nil;
1055 static NSString *UniqueID_ = nil;
1056 static NSString *PLMN_ = nil;
1057 static NSString *Build_ = nil;
1058 static NSString *Product_ = nil;
1059 static NSString *Safari_ = nil;
1061 static CFLocaleRef Locale_;
1062 static NSArray *Languages_;
1063 static CGColorSpaceRef space_;
1065 static NSDictionary *SectionMap_;
1066 static NSMutableDictionary *Metadata_;
1067 static _transient NSMutableDictionary *Settings_;
1068 static _transient NSString *Role_;
1069 static _transient NSMutableDictionary *Packages_;
1070 static _transient NSMutableDictionary *Sections_;
1071 static _transient NSMutableDictionary *Sources_;
1072 static bool Changed_;
1078 /* Display Helpers {{{ */
1079 inline float Interpolate(float begin, float end, float fraction) {
1080 return (end - begin) * fraction + begin;
1083 /* XXX: localize this! */
1084 NSString *SizeString(double size) {
1085 bool negative = size < 0;
1090 while (size > 1024) {
1095 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1097 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1100 static _finline const char *StripVersion_(const char *version) {
1101 const char *colon(strchr(version, ':'));
1102 return colon == NULL ? version : colon + 1;
1105 NSString *LocalizeSection(NSString *section) {
1106 static Pcre title_r("^(.*?) \\((.*)\\)$");
1107 if (title_r(section)) {
1108 NSString *parent(title_r[1]);
1109 NSString *child(title_r[2]);
1111 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1112 LocalizeSection(parent),
1113 LocalizeSection(child)
1117 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1120 NSString *Simplify(NSString *title) {
1121 const char *data = [title UTF8String];
1122 size_t size = [title length];
1124 static Pcre square_r("^\\[(.*)\\]$");
1125 if (square_r(data, size))
1126 return Simplify(square_r[1]);
1128 static Pcre paren_r("^\\((.*)\\)$");
1129 if (paren_r(data, size))
1130 return Simplify(paren_r[1]);
1132 static Pcre title_r("^(.*?) \\((.*)\\)$");
1133 if (title_r(data, size))
1134 return Simplify(title_r[1]);
1140 NSString *GetLastUpdate() {
1141 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1144 return UCLocalize("NEVER_OR_UNKNOWN");
1146 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1147 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1149 CFRelease(formatter);
1151 return [(NSString *) formatted autorelease];
1154 bool isSectionVisible(NSString *section) {
1155 NSDictionary *metadata([Sections_ objectForKey:section]);
1156 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1157 return hidden == nil || ![hidden boolValue];
1162 /* Delegate Prototypes {{{ */
1166 @interface NSObject (ProgressDelegate)
1169 @protocol ProgressDelegate
1170 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1171 - (void) setProgressTitle:(NSString *)title;
1172 - (void) setProgressPercent:(float)percent;
1173 - (void) startProgress;
1174 - (void) addProgressOutput:(NSString *)output;
1175 - (bool) isCancelling:(size_t)received;
1178 @protocol ConfigurationDelegate
1179 - (void) repairWithSelector:(SEL)selector;
1180 - (void) setConfigurationData:(NSString *)data;
1183 @class CYPackageController;
1185 @protocol CydiaDelegate
1186 - (void) retainNetworkActivityIndicator;
1187 - (void) releaseNetworkActivityIndicator;
1188 - (void) setPackageController:(CYPackageController *)view;
1189 - (void) clearPackage:(Package *)package;
1190 - (void) installPackage:(Package *)package;
1191 - (void) installPackages:(NSArray *)packages;
1192 - (void) removePackage:(Package *)package;
1193 - (void) beginUpdate;
1195 - (void) distUpgrade;
1197 - (void) updateData;
1199 - (void) showSettings;
1200 - (UIProgressHUD *) addProgressHUD;
1201 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1202 - (CYViewController *) pageForPackage:(NSString *)name;
1203 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1206 static id<CydiaDelegate> CydiaApp;
1209 /* Status Delegation {{{ */
1211 public pkgAcquireStatus
1214 _transient NSObject<ProgressDelegate> *delegate_;
1222 void setDelegate(id delegate) {
1223 delegate_ = delegate;
1226 NSObject<ProgressDelegate> *getDelegate() const {
1230 virtual bool MediaChange(std::string media, std::string drive) {
1234 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1237 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1238 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1239 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1242 virtual void Done(pkgAcquire::ItemDesc &item) {
1245 virtual void Fail(pkgAcquire::ItemDesc &item) {
1247 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1248 item.Owner->Status == pkgAcquire::Item::StatDone
1252 std::string &error(item.Owner->ErrorText);
1256 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1257 NSArray *fields([description componentsSeparatedByString:@" "]);
1258 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1260 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1261 withObject:[NSArray arrayWithObjects:
1262 [NSString stringWithUTF8String:error.c_str()],
1269 virtual bool Pulse(pkgAcquire *Owner) {
1270 bool value = pkgAcquireStatus::Pulse(Owner);
1273 double(CurrentBytes + CurrentItems) /
1274 double(TotalBytes + TotalItems)
1277 [delegate_ setProgressPercent:percent];
1278 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1281 virtual void Start() {
1282 [delegate_ startProgress];
1285 virtual void Stop() {
1289 /* Progress Delegation {{{ */
1294 _transient id<ProgressDelegate> delegate_;
1298 virtual void Update() {
1299 /*if (abs(Percent - percent_) > 2)
1300 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1304 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1305 [delegate_ setProgressPercent:(Percent / 100)];*/
1315 void setDelegate(id delegate) {
1316 delegate_ = delegate;
1319 id getDelegate() const {
1323 virtual void Done() {
1325 //[delegate_ setProgressPercent:1];
1330 /* Database Interface {{{ */
1331 typedef std::map< unsigned long, _H<Source> > SourceMap;
1333 @interface Database : NSObject {
1339 pkgCacheFile cache_;
1340 pkgDepCache::Policy *policy_;
1341 pkgRecords *records_;
1342 pkgProblemResolver *resolver_;
1343 pkgAcquire *fetcher_;
1345 SPtr<pkgPackageManager> manager_;
1346 pkgSourceList *list_;
1349 CFMutableArrayRef deadSources_;
1350 CFMutableArrayRef packages_;
1352 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1360 std::map<const char *, _H<NSString> > sections_;
1363 + (Database *) sharedInstance;
1366 - (void) _readCydia:(NSNumber *)fd;
1367 - (void) _readStatus:(NSNumber *)fd;
1368 - (void) _readOutput:(NSNumber *)fd;
1372 - (Package *) packageWithName:(NSString *)name;
1374 - (pkgCacheFile &) cache;
1375 - (pkgDepCache::Policy *) policy;
1376 - (pkgRecords *) records;
1377 - (pkgProblemResolver *) resolver;
1378 - (pkgAcquire &) fetcher;
1379 - (pkgSourceList &) list;
1380 - (NSArray *) packages;
1381 - (NSArray *) sources;
1382 - (void) reloadData;
1390 - (void) updateWithStatus:(Status &)status;
1392 - (void) setDelegate:(id)delegate;
1393 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1395 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1399 /* Delegate Helpers {{{ */
1400 @implementation NSObject (ProgressDelegate)
1402 - (void) _setProgressErrorPackage:(NSArray *)args {
1403 [self performSelector:@selector(setProgressError:forPackage:)
1404 withObject:[args objectAtIndex:0]
1405 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1409 - (void) _setProgressErrorTitle:(NSArray *)args {
1410 [self performSelector:@selector(setProgressError:withTitle:)
1411 withObject:[args objectAtIndex:0]
1412 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1416 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1417 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1418 withObject:[NSArray arrayWithObjects:error, title, nil]
1423 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1424 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1426 [self performSelector:@selector(setProgressError:withTitle:)
1428 withObject:(package == nil ? id : [package name])
1435 // Cytore Definitions {{{
1436 struct PackageValue :
1439 Cytore::Offset<PackageValue> next_;
1441 uint32_t index_ : 23;
1442 uint32_t subscribed_ : 1;
1459 Cytore::Offset<PackageValue> packages_[1 << 16];
1462 static Cytore::File<MetaValue> MetaFile_;
1464 // Cytore Helper Functions {{{
1465 static PackageValue *PackageFind(const char *name, size_t length) {
1466 SplitHash nhash = { hashlittle(name, length) };
1468 PackageValue *metadata;
1470 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1471 offset: if (offset->IsNull()) {
1472 *offset = MetaFile_.New<PackageValue>(length + 1);
1473 metadata = &MetaFile_.Get(*offset);
1475 memcpy(metadata->name_, name, length + 1);
1476 metadata->nhash_ = nhash.u16[1];
1478 metadata = &MetaFile_.Get(*offset);
1480 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1481 offset = &metadata->next_;
1489 static void PackageImport(const void *key, const void *value, void *context) {
1491 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1492 NSLog(@"failed to import package %@", key);
1496 PackageValue *metadata(PackageFind(buffer, strlen(buffer)));
1497 NSDictionary *package((NSDictionary *) value);
1499 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1500 if ([subscribed boolValue] && !metadata->subscribed_)
1501 metadata->subscribed_ = true;
1503 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1504 time_t time([date timeIntervalSince1970]);
1505 if (metadata->first_ > time || metadata->first_ == 0)
1506 metadata->first_ = time;
1509 NSDate *date([package objectForKey:@"LastSeen"]);
1510 NSString *version([package objectForKey:@"LastVersion"]);
1512 if (date != nil && version != nil) {
1513 time_t time([date timeIntervalSince1970]);
1514 if (metadata->last_ < time || metadata->last_ == 0)
1515 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1516 size_t length(strlen(buffer));
1517 uint16_t vhash(hashlittle(buffer, length));
1519 size_t capped(std::min<size_t>(8, length));
1520 char *latest(buffer + length - capped);
1522 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1523 metadata->vhash_ = vhash;
1525 metadata->last_ = time;
1531 /* Source Class {{{ */
1532 @interface Source : NSObject {
1533 CYString depiction_;
1534 CYString description_;
1540 CYString distribution_;
1545 NSString *authority_;
1547 CYString defaultIcon_;
1549 NSDictionary *record_;
1553 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1555 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1557 - (NSString *) depictionForPackage:(NSString *)package;
1558 - (NSString *) supportForPackage:(NSString *)package;
1560 - (NSDictionary *) record;
1564 - (NSString *) distribution;
1565 - (NSString *) type;
1567 - (NSString *) host;
1569 - (NSString *) name;
1570 - (NSString *) description;
1571 - (NSString *) label;
1572 - (NSString *) origin;
1573 - (NSString *) version;
1575 - (NSString *) defaultIcon;
1579 @implementation Source
1583 distribution_.clear();
1586 description_.clear();
1592 defaultIcon_.clear();
1594 if (record_ != nil) {
1604 if (authority_ != nil) {
1605 [authority_ release];
1611 // XXX: this is a very inefficient way to call these deconstructors
1616 + (NSArray *) _attributeKeys {
1617 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1620 - (NSArray *) attributeKeys {
1621 return [[self class] _attributeKeys];
1624 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1625 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1628 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1631 trusted_ = index->IsTrusted();
1633 uri_.set(pool, index->GetURI());
1634 distribution_.set(pool, index->GetDist());
1635 type_.set(pool, index->GetType());
1637 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1638 if (dindex != NULL) {
1640 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1643 pkgTagFile tags(&fd);
1645 pkgTagSection section;
1652 {"default-icon", &defaultIcon_},
1653 {"depiction", &depiction_},
1654 {"description", &description_},
1656 {"origin", &origin_},
1657 {"support", &support_},
1658 {"version", &version_},
1661 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1662 const char *start, *end;
1664 if (section.Find(names[i].name_, start, end)) {
1665 CYString &value(*names[i].value_);
1666 value.set(pool, start, end - start);
1672 record_ = [Sources_ objectForKey:[self key]];
1674 record_ = [record_ retain];
1676 NSURL *url([NSURL URLWithString:uri_]);
1680 host_ = [[host_ lowercaseString] retain];
1685 authority_ = [url path];
1687 if (authority_ != nil)
1688 authority_ = [authority_ retain];
1691 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1692 if ((self = [super init]) != nil) {
1693 [self setMetaIndex:index inPool:pool];
1697 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1698 NSDictionary *lhr = [self record];
1699 NSDictionary *rhr = [source record];
1702 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1704 NSString *lhs = [self name];
1705 NSString *rhs = [source name];
1707 if ([lhs length] != 0 && [rhs length] != 0) {
1708 unichar lhc = [lhs characterAtIndex:0];
1709 unichar rhc = [rhs characterAtIndex:0];
1711 if (isalpha(lhc) && !isalpha(rhc))
1712 return NSOrderedAscending;
1713 else if (!isalpha(lhc) && isalpha(rhc))
1714 return NSOrderedDescending;
1717 return [lhs compare:rhs options:LaxCompareOptions_];
1720 - (NSString *) depictionForPackage:(NSString *)package {
1721 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1724 - (NSString *) supportForPackage:(NSString *)package {
1725 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1728 - (NSDictionary *) record {
1736 - (NSString *) uri {
1740 - (NSString *) distribution {
1741 return distribution_;
1744 - (NSString *) type {
1748 - (NSString *) key {
1749 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1752 - (NSString *) host {
1756 - (NSString *) name {
1757 return origin_.empty() ? authority_ : origin_;
1760 - (NSString *) description {
1761 return description_;
1764 - (NSString *) label {
1765 return label_.empty() ? authority_ : label_;
1768 - (NSString *) origin {
1772 - (NSString *) version {
1776 - (NSString *) defaultIcon {
1777 return defaultIcon_;
1782 /* Relationship Class {{{ */
1783 @interface Relationship : NSObject {
1788 - (NSString *) type;
1790 - (NSString *) name;
1794 @implementation Relationship
1802 - (NSString *) type {
1810 - (NSString *) name {
1817 /* Package Class {{{ */
1818 struct ParsedPackage {
1823 CYString depiction_;
1833 @interface Package : NSObject {
1836 uint32_t essential_ : 1;
1837 uint32_t obsolete_ : 1;
1838 uint32_t ignored_ : 1;
1842 _transient Database *database_;
1844 pkgCache::VerIterator version_;
1845 pkgCache::PkgIterator iterator_;
1846 pkgCache::VerFileIterator file_;
1852 CYString installed_;
1854 const char *section_;
1855 _transient NSString *section$_;
1859 PackageValue *metadata_;
1860 ParsedPackage *parsed_;
1862 NSMutableArray *tags_;
1865 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1866 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1868 - (pkgCache::PkgIterator) iterator;
1871 - (NSString *) section;
1872 - (NSString *) simpleSection;
1874 - (NSString *) longSection;
1875 - (NSString *) shortSection;
1879 - (Address *) maintainer;
1881 - (NSString *) longDescription;
1882 - (NSString *) shortDescription;
1885 - (PackageValue *) metadata;
1888 - (bool) subscribed;
1889 - (bool) setSubscribed:(bool)subscribed;
1893 - (NSString *) latest;
1894 - (NSString *) installed;
1895 - (BOOL) uninstalled;
1898 - (BOOL) upgradableAndEssential:(BOOL)essential;
1901 - (BOOL) unfiltered;
1905 - (BOOL) halfConfigured;
1906 - (BOOL) halfInstalled;
1908 - (NSString *) mode;
1911 - (NSString *) name;
1913 - (NSString *) homepage;
1914 - (NSString *) depiction;
1915 - (Address *) author;
1917 - (NSString *) support;
1919 - (NSArray *) files;
1920 - (NSArray *) warnings;
1921 - (NSArray *) applications;
1923 - (Source *) source;
1925 - (BOOL) matches:(NSString *)text;
1927 - (bool) hasSupportingRole;
1928 - (BOOL) hasTag:(NSString *)tag;
1929 - (NSString *) primaryPurpose;
1930 - (NSArray *) purposes;
1931 - (bool) isCommercial;
1933 - (void) setIndex:(size_t)index;
1935 - (CYString &) cyname;
1937 - (uint32_t) compareBySection:(NSArray *)sections;
1942 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1943 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1944 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1945 - (bool) isVisibleInSection:(NSString *)section;
1946 - (bool) isVisibleInSource:(Source *)source;
1950 uint32_t PackageChangesRadix(Package *self, void *) {
1955 uint32_t timestamp : 30;
1956 uint32_t ignored : 1;
1957 uint32_t upgradable : 1;
1961 bool upgradable([self upgradableAndEssential:YES]);
1962 value.bits.upgradable = upgradable ? 1 : 0;
1965 value.bits.timestamp = 0;
1966 value.bits.ignored = [self ignored] ? 0 : 1;
1967 value.bits.upgradable = 1;
1969 value.bits.timestamp = [self seen] >> 2;
1970 value.bits.ignored = 0;
1971 value.bits.upgradable = 0;
1974 return _not(uint32_t) - value.key;
1977 uint32_t PackagePrefixRadix(Package *self, void *context) {
1978 size_t offset(reinterpret_cast<size_t>(context));
1979 CYString &name([self cyname]);
1981 size_t size(name.size());
1984 char *text(name.data());
1987 if (!isdigit(text[0]))
1991 while (size != digits && isdigit(text[digits]))
1999 if (offset == 0 && zeros != 0) {
2000 memset(data, '0', zeros);
2001 memcpy(data + zeros, text, 4 - zeros);
2003 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2004 if (size <= offset - zeros)
2007 text += offset - zeros;
2008 size -= offset - zeros;
2011 memcpy(data, text, 4);
2013 memcpy(data, text, size);
2014 memset(data + size, 0, 4 - size);
2017 for (size_t i(0); i != 4; ++i)
2018 if (isalpha(data[i]))
2026 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2028 /* XXX: ntohl may be more honest */
2029 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2032 CYString &(*PackageName)(Package *self, SEL sel);
2034 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2035 _profile(PackageNameCompare)
2036 CYString &lhi(PackageName(lhs, @selector(cyname)));
2037 CYString &rhi(PackageName(rhs, @selector(cyname)));
2038 CFStringRef lhn(lhi), rhn(rhi);
2041 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2042 else if (rhn == NULL)
2043 return NSOrderedDescending;
2045 _profile(PackageNameCompare$NumbersLast)
2046 if (!lhi.empty() && !rhi.empty()) {
2047 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2048 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2049 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2050 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2051 return lha ? NSOrderedAscending : NSOrderedDescending;
2055 CFIndex length = CFStringGetLength(lhn);
2057 _profile(PackageNameCompare$Compare)
2058 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2063 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2064 return PackageNameCompare(*lhs, *rhs, context);
2067 struct PackageNameOrdering :
2068 std::binary_function<Package *, Package *, bool>
2070 _finline bool operator ()(Package *lhs, Package *rhs) const {
2071 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2075 @implementation Package
2077 - (NSString *) description {
2078 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2082 if (parsed_ != NULL)
2091 + (NSString *) webScriptNameForSelector:(SEL)selector {
2092 if (selector == @selector(hasTag:))
2098 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2099 return [self webScriptNameForSelector:selector] == nil;
2102 + (NSArray *) _attributeKeys {
2103 return [NSArray arrayWithObjects:@"applications", @"author", @"depiction", @"longDescription", @"essential", @"homepage", @"icon", @"id", @"installed", @"latest", @"longSection", @"maintainer", @"mode", @"name", @"purposes", @"section", @"shortDescription", @"shortSection", @"simpleSection", @"size", @"source", @"sponsor", @"support", @"warnings", nil];
2106 - (NSArray *) attributeKeys {
2107 return [[self class] _attributeKeys];
2110 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2111 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2115 if (parsed_ != NULL)
2117 @synchronized (database_) {
2118 if ([database_ era] != era_ || file_.end())
2121 ParsedPackage *parsed(new ParsedPackage);
2124 _profile(Package$parse)
2125 pkgRecords::Parser *parser;
2127 _profile(Package$parse$Lookup)
2128 parser = &[database_ records]->Lookup(file_);
2133 _profile(Package$parse$Find)
2138 {"icon", &parsed->icon_},
2139 {"depiction", &parsed->depiction_},
2140 {"homepage", &parsed->homepage_},
2141 {"website", &website},
2142 {"bugs", &parsed->bugs_},
2143 {"support", &parsed->support_},
2144 {"sponsor", &parsed->sponsor_},
2145 {"author", &parsed->author_},
2148 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2149 const char *start, *end;
2151 if (parser->Find(names[i].name_, start, end)) {
2152 CYString &value(*names[i].value_);
2153 _profile(Package$parse$Value)
2154 value.set(pool_, start, end - start);
2160 _profile(Package$parse$Tagline)
2161 const char *start, *end;
2162 if (parser->ShortDesc(start, end)) {
2163 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2166 while (stop != start && stop[-1] == '\r')
2168 parsed->tagline_.set(pool_, start, stop - start);
2172 _profile(Package$parse$Retain)
2173 if (parsed->homepage_.empty())
2174 parsed->homepage_ = website;
2175 if (parsed->homepage_ == parsed->depiction_)
2176 parsed->homepage_.clear();
2181 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2182 if ((self = [super init]) != nil) {
2183 _profile(Package$initWithVersion)
2186 database_ = database;
2187 era_ = [database era];
2191 pkgCache::PkgIterator iterator(version.ParentPkg());
2192 iterator_ = iterator;
2194 _profile(Package$initWithVersion$Version)
2195 if (!version_.end())
2196 file_ = version_.FileList();
2198 pkgCache &cache([database_ cache]);
2199 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2203 _profile(Package$initWithVersion$Cache)
2204 name_.set(NULL, iterator.Display());
2206 latest_.set(NULL, StripVersion_(version_.VerStr()));
2208 pkgCache::VerIterator current(iterator.CurrentVer());
2210 installed_.set(NULL, StripVersion_(current.VerStr()));
2213 _profile(Package$initWithVersion$Tags)
2214 pkgCache::TagIterator tag(iterator.TagList());
2216 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2218 const char *name(tag.Name());
2219 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2221 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2222 if (strcmp(name + 6, "enduser") == 0)
2224 else if (strcmp(name + 6, "hacker") == 0)
2226 else if (strcmp(name + 6, "developer") == 0)
2228 else if (strcmp(name + 6, "cydia") == 0)
2234 if (strncmp(name, "cydia::", 7) == 0) {
2235 if (strcmp(name + 7, "essential") == 0)
2237 else if (strcmp(name + 7, "obsolete") == 0)
2242 } while (!tag.end());
2246 _profile(Package$initWithVersion$Metadata)
2247 const char *mixed(iterator.Name());
2248 size_t size(strlen(mixed));
2249 char lower[size + 1];
2251 for (size_t i(0); i != size; ++i)
2252 lower[i] = mixed[i] | 0x20;
2255 PackageValue *metadata(PackageFind(lower, size));
2256 metadata_ = metadata;
2258 id_.set(NULL, metadata->name_, size);
2260 const char *latest(version_.VerStr());
2261 size_t length(strlen(latest));
2263 uint16_t vhash(hashlittle(latest, length));
2265 size_t capped(std::min<size_t>(8, length));
2266 latest = latest + length - capped;
2268 if (metadata->first_ == 0)
2269 metadata->first_ = now_;
2271 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2272 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2273 metadata->vhash_ = vhash;
2274 metadata->last_ = now_;
2275 } else if (metadata->last_ == 0)
2276 metadata->last_ = metadata->first_;
2279 _profile(Package$initWithVersion$Section)
2280 section_ = iterator.Section();
2283 _profile(Package$initWithVersion$Flags)
2284 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2285 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2290 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2291 pkgCache::VerIterator version;
2293 _profile(Package$packageWithIterator$GetCandidateVer)
2294 version = [database policy]->GetCandidateVer(iterator);
2302 _profile(Package$packageWithIterator$Allocate)
2303 package = [Package allocWithZone:zone];
2306 _profile(Package$packageWithIterator$Initialize)
2308 initWithVersion:version
2315 _profile(Package$packageWithIterator$Autorelease)
2316 package = [package autorelease];
2322 - (pkgCache::PkgIterator) iterator {
2326 - (NSString *) section {
2327 if (section$_ == nil) {
2328 if (section_ == NULL)
2331 _profile(Package$section$mappedSectionForPointer)
2332 section$_ = [database_ mappedSectionForPointer:section_];
2337 - (NSString *) simpleSection {
2338 if (NSString *section = [self section])
2339 return Simplify(section);
2344 - (NSString *) longSection {
2345 return LocalizeSection([self section]);
2348 - (NSString *) shortSection {
2349 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2352 - (NSString *) uri {
2355 pkgIndexFile *index;
2356 pkgCache::PkgFileIterator file(file_.File());
2357 if (![database_ list].FindIndex(file, index))
2359 return [NSString stringWithUTF8String:iterator_->Path];
2360 //return [NSString stringWithUTF8String:file.Site()];
2361 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2365 - (Address *) maintainer {
2366 @synchronized (database_) {
2367 if ([database_ era] != era_ || file_.end())
2370 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2371 const std::string &maintainer(parser->Maintainer());
2372 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2376 @synchronized (database_) {
2377 if ([database_ era] != era_ || version_.end())
2380 return version_->InstalledSize;
2383 - (NSString *) longDescription {
2384 @synchronized (database_) {
2385 if ([database_ era] != era_ || file_.end())
2388 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2389 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2391 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2392 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2393 if ([lines count] < 2)
2396 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2397 for (size_t i(1), e([lines count]); i != e; ++i) {
2398 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2399 [trimmed addObject:trim];
2402 return [trimmed componentsJoinedByString:@"\n"];
2405 - (NSString *) shortDescription {
2406 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2410 _profile(Package$index)
2411 CFStringRef name((CFStringRef) [self name]);
2412 if (CFStringGetLength(name) == 0)
2414 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2415 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2417 return toupper(character);
2421 - (PackageValue *) metadata {
2426 PackageValue *metadata([self metadata]);
2427 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2430 - (bool) subscribed {
2431 return [self metadata]->subscribed_;
2434 - (bool) setSubscribed:(bool)subscribed {
2435 PackageValue *metadata([self metadata]);
2436 if (metadata->subscribed_ == subscribed)
2438 metadata->subscribed_ = subscribed;
2446 - (NSString *) latest {
2450 - (NSString *) installed {
2454 - (BOOL) uninstalled {
2455 return installed_.empty();
2459 return !version_.end();
2462 - (BOOL) upgradableAndEssential:(BOOL)essential {
2463 _profile(Package$upgradableAndEssential)
2464 pkgCache::VerIterator current(iterator_.CurrentVer());
2466 return essential && essential_;
2468 return !version_.end() && version_ != current;
2472 - (BOOL) essential {
2477 return [database_ cache][iterator_].InstBroken();
2480 - (BOOL) unfiltered {
2481 _profile(Package$unfiltered$obsolete)
2482 if (_unlikely(obsolete_))
2486 _profile(Package$unfiltered$hasSupportingRole)
2487 if (_unlikely(![self hasSupportingRole]))
2495 if (![self unfiltered])
2500 _profile(Package$visible$section)
2501 section = [self section];
2504 _profile(Package$visible$isSectionVisible)
2505 if (section != nil && !isSectionVisible(section))
2513 unsigned char current(iterator_->CurrentState);
2514 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2517 - (BOOL) halfConfigured {
2518 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2521 - (BOOL) halfInstalled {
2522 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2526 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2527 return state.Mode != pkgDepCache::ModeKeep;
2530 - (NSString *) mode {
2531 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2533 switch (state.Mode) {
2534 case pkgDepCache::ModeDelete:
2535 if ((state.iFlags & pkgDepCache::Purge) != 0)
2539 case pkgDepCache::ModeKeep:
2540 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2541 return @"REINSTALL";
2542 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2546 case pkgDepCache::ModeInstall:
2547 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2548 return @"REINSTALL";
2549 else*/ switch (state.Status) {
2551 return @"DOWNGRADE";
2557 return @"NEW_INSTALL";
2568 - (NSString *) name {
2569 return name_.empty() ? id_ : name_;
2572 - (UIImage *) icon {
2573 NSString *section = [self simpleSection];
2576 if (parsed_ != NULL)
2577 if (NSString *href = parsed_->icon_)
2578 if ([href hasPrefix:@"file:///"])
2579 // XXX: correct escaping
2580 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2581 if (icon == nil) if (section != nil)
2582 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2583 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2584 if ([dicon hasPrefix:@"file:///"])
2585 // XXX: correct escaping
2586 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2588 icon = [UIImage applicationImageNamed:@"unknown.png"];
2592 - (NSString *) homepage {
2593 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2596 - (NSString *) depiction {
2597 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2600 - (Address *) sponsor {
2601 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2604 - (Address *) author {
2605 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2608 - (NSString *) support {
2609 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2612 - (NSArray *) files {
2613 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2614 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2617 fin.open([path UTF8String]);
2622 while (std::getline(fin, line))
2623 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2628 - (NSArray *) warnings {
2629 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2630 const char *name(iterator_.Name());
2632 size_t length(strlen(name));
2633 if (length < 2) invalid:
2634 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2635 else for (size_t i(0); i != length; ++i)
2637 /* XXX: technically this is not allowed */
2638 (name[i] < 'A' || name[i] > 'Z') &&
2639 (name[i] < 'a' || name[i] > 'z') &&
2640 (name[i] < '0' || name[i] > '9') &&
2641 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2644 if (strcmp(name, "cydia") != 0) {
2647 bool _private = false;
2650 bool repository = [[self section] isEqualToString:@"Repositories"];
2652 if (NSArray *files = [self files])
2653 for (NSString *file in files)
2654 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2656 else if (!user && [file isEqualToString:@"/User"])
2658 else if (!_private && [file isEqualToString:@"/private"])
2660 else if (!stash && [file isEqualToString:@"/var/stash"])
2663 /* XXX: this is not sensitive enough. only some folders are valid. */
2664 if (cydia && !repository)
2665 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2667 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2669 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2671 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2674 return [warnings count] == 0 ? nil : warnings;
2677 - (NSArray *) applications {
2678 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2680 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2682 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2683 if (NSArray *files = [self files])
2684 for (NSString *file in files)
2685 if (application_r(file)) {
2686 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2687 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2688 if ([id isEqualToString:me])
2691 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2693 display = application_r[1];
2695 NSString *bundle([file stringByDeletingLastPathComponent]);
2696 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2697 if (icon == nil || [icon length] == 0)
2699 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2701 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2702 [applications addObject:application];
2704 [application addObject:id];
2705 [application addObject:display];
2706 [application addObject:url];
2709 return [applications count] == 0 ? nil : applications;
2712 - (Source *) source {
2713 if (source_ == nil) {
2714 @synchronized (database_) {
2715 if ([database_ era] != era_ || file_.end())
2716 source_ = (Source *) [NSNull null];
2718 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2722 return source_ == (Source *) [NSNull null] ? nil : source_;
2725 - (BOOL) matches:(NSString *)text {
2731 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2732 if (range.location != NSNotFound)
2735 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2736 if (range.location != NSNotFound)
2739 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2740 if (range.location != NSNotFound)
2746 - (bool) hasSupportingRole {
2751 if ([Role_ isEqualToString:@"User"])
2755 if ([Role_ isEqualToString:@"Hacker"])
2759 if ([Role_ isEqualToString:@"Developer"])
2764 - (BOOL) hasTag:(NSString *)tag {
2765 return tags_ == nil ? NO : [tags_ containsObject:tag];
2768 - (NSString *) primaryPurpose {
2769 for (NSString *tag in tags_)
2770 if ([tag hasPrefix:@"purpose::"])
2771 return [tag substringFromIndex:9];
2775 - (NSArray *) purposes {
2776 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2777 for (NSString *tag in tags_)
2778 if ([tag hasPrefix:@"purpose::"])
2779 [purposes addObject:[tag substringFromIndex:9]];
2780 return [purposes count] == 0 ? nil : purposes;
2783 - (bool) isCommercial {
2784 return [self hasTag:@"cydia::commercial"];
2787 - (void) setIndex:(size_t)index {
2788 if (metadata_->index_ != index)
2789 metadata_->index_ = index;
2792 - (CYString &) cyname {
2793 return name_.empty() ? id_ : name_;
2796 - (uint32_t) compareBySection:(NSArray *)sections {
2797 NSString *section([self section]);
2798 for (size_t i(0), e([sections count]); i != e; ++i) {
2799 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2803 return _not(uint32_t);
2807 @synchronized (database_) {
2808 pkgProblemResolver *resolver = [database_ resolver];
2809 resolver->Clear(iterator_);
2811 pkgCacheFile &cache([database_ cache]);
2812 cache->SetReInstall(iterator_, false);
2813 cache->MarkKeep(iterator_, false);
2817 @synchronized (database_) {
2818 pkgProblemResolver *resolver = [database_ resolver];
2819 resolver->Clear(iterator_);
2820 resolver->Protect(iterator_);
2822 pkgCacheFile &cache([database_ cache]);
2823 cache->SetReInstall(iterator_, false);
2824 cache->MarkInstall(iterator_, false);
2826 pkgDepCache::StateCache &state((*cache)[iterator_]);
2827 if (!state.Install())
2828 cache->SetReInstall(iterator_, true);
2832 @synchronized (database_) {
2833 pkgProblemResolver *resolver = [database_ resolver];
2834 resolver->Clear(iterator_);
2835 resolver->Remove(iterator_);
2836 resolver->Protect(iterator_);
2838 pkgCacheFile &cache([database_ cache]);
2839 cache->SetReInstall(iterator_, false);
2840 cache->MarkDelete(iterator_, true);
2843 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2844 _profile(Package$isUnfilteredAndSearchedForBy)
2847 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2848 value &= [self unfiltered];
2851 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2852 value &= [self matches:search];
2859 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2860 if ([search length] == 0)
2863 _profile(Package$isUnfilteredAndSelectedForBy)
2866 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2867 value &= [self unfiltered];
2870 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2871 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2878 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2879 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2882 - (bool) isVisibleInSection:(NSString *)name {
2883 NSString *section([self section]);
2887 section == nil && [name length] == 0 ||
2888 [name isEqualToString:section]
2889 ) && [self visible];
2892 - (bool) isVisibleInSource:(Source *)source {
2893 return [self source] == source && [self visible];
2898 /* Section Class {{{ */
2899 @interface Section : NSObject {
2904 NSString *localized_;
2907 - (NSComparisonResult) compareByLocalized:(Section *)section;
2908 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2909 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2910 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2911 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2912 - (NSString *) name;
2919 - (void) addToCount;
2921 - (void) setCount:(size_t)count;
2922 - (NSString *) localized;
2926 @implementation Section
2930 if (localized_ != nil)
2931 [localized_ release];
2935 - (NSComparisonResult) compareByLocalized:(Section *)section {
2936 NSString *lhs(localized_);
2937 NSString *rhs([section localized]);
2939 /*if ([lhs length] != 0 && [rhs length] != 0) {
2940 unichar lhc = [lhs characterAtIndex:0];
2941 unichar rhc = [rhs characterAtIndex:0];
2943 if (isalpha(lhc) && !isalpha(rhc))
2944 return NSOrderedAscending;
2945 else if (!isalpha(lhc) && isalpha(rhc))
2946 return NSOrderedDescending;
2949 return [lhs compare:rhs options:LaxCompareOptions_];
2952 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2953 if ((self = [self initWithName:name localize:NO]) != nil) {
2954 if (localized != nil)
2955 localized_ = [localized retain];
2959 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2960 return [self initWithName:name row:0 localize:localize];
2963 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2964 if ((self = [super init]) != nil) {
2965 name_ = [name retain];
2969 localized_ = [LocalizeSection(name_) retain];
2973 /* XXX: localize the index thingees */
2974 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2975 if ((self = [super init]) != nil) {
2976 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2982 - (NSString *) name {
3002 - (void) addToCount {
3006 - (void) setCount:(size_t)count {
3010 - (NSString *) localized {
3017 static NSString *Colon_;
3018 static NSString *Elision_;
3019 static NSString *Error_;
3020 static NSString *Warning_;
3022 /* Database Implementation {{{ */
3023 @implementation Database
3025 + (Database *) sharedInstance {
3026 static Database *instance;
3027 if (instance == nil)
3028 instance = [[Database alloc] init];
3036 - (void) releasePackages {
3037 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3038 CFArrayRemoveAllValues(packages_);
3042 // XXX: actually implement this thing
3045 CFRelease(deadSources_);
3046 [self releasePackages];
3047 apr_pool_destroy(pool_);
3048 NSRecycleZone(zone_);
3052 - (void) _readCydia:(NSNumber *)fd { _pooled
3053 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3054 std::istream is(&ib);
3057 static Pcre finish_r("^finish:([^:]*)$");
3059 while (std::getline(is, line)) {
3060 const char *data(line.c_str());
3061 size_t size = line.size();
3062 lprintf("C:%s\n", data);
3064 if (finish_r(data, size)) {
3065 NSString *finish = finish_r[1];
3066 int index = [Finishes_ indexOfObject:finish];
3067 if (index != INT_MAX && index > Finish_)
3075 - (void) _readStatus:(NSNumber *)fd { _pooled
3076 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3077 std::istream is(&ib);
3080 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3081 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3083 while (std::getline(is, line)) {
3084 const char *data(line.c_str());
3085 size_t size(line.size());
3086 lprintf("S:%s\n", data);
3088 if (conffile_r(data, size)) {
3089 [delegate_ setConfigurationData:conffile_r[1]];
3090 } else if (strncmp(data, "status: ", 8) == 0) {
3091 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3092 [delegate_ setProgressTitle:string];
3093 } else if (pmstatus_r(data, size)) {
3094 std::string type([pmstatus_r[1] UTF8String]);
3095 NSString *id = pmstatus_r[2];
3097 float percent([pmstatus_r[3] floatValue]);
3098 [delegate_ setProgressPercent:(percent / 100)];
3100 NSString *string = pmstatus_r[4];
3102 if (type == "pmerror")
3103 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3104 withObject:[NSArray arrayWithObjects:string, id, nil]
3107 else if (type == "pmstatus") {
3108 [delegate_ setProgressTitle:string];
3109 } else if (type == "pmconffile")
3110 [delegate_ setConfigurationData:string];
3112 lprintf("E:unknown pmstatus\n");
3114 lprintf("E:unknown status\n");
3120 - (void) _readOutput:(NSNumber *)fd { _pooled
3121 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3122 std::istream is(&ib);
3125 while (std::getline(is, line)) {
3126 lprintf("O:%s\n", line.c_str());
3127 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3137 - (Package *) packageWithName:(NSString *)name {
3138 @synchronized (self) {
3139 if (static_cast<pkgDepCache *>(cache_) == NULL)
3141 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3142 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3146 if ((self = [super init]) != nil) {
3153 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3154 apr_pool_create(&pool_, NULL);
3156 size_t capacity(MetaFile_->active_);
3162 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3163 deadSources_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
3167 _assert(pipe(fds) != -1);
3170 _config->Set("APT::Keep-Fds::", cydiafd_);
3171 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3174 detachNewThreadSelector:@selector(_readCydia:)
3176 withObject:[NSNumber numberWithInt:fds[0]]
3179 _assert(pipe(fds) != -1);
3183 detachNewThreadSelector:@selector(_readStatus:)
3185 withObject:[NSNumber numberWithInt:fds[0]]
3188 _assert(pipe(fds) != -1);
3189 _assert(dup2(fds[0], 0) != -1);
3190 _assert(close(fds[0]) != -1);
3192 input_ = fdopen(fds[1], "a");
3194 _assert(pipe(fds) != -1);
3195 _assert(dup2(fds[1], 1) != -1);
3196 _assert(close(fds[1]) != -1);
3199 detachNewThreadSelector:@selector(_readOutput:)
3201 withObject:[NSNumber numberWithInt:fds[0]]
3206 - (pkgCacheFile &) cache {
3210 - (pkgDepCache::Policy *) policy {
3214 - (pkgRecords *) records {
3218 - (pkgProblemResolver *) resolver {
3222 - (pkgAcquire &) fetcher {
3226 - (pkgSourceList &) list {
3230 - (NSArray *) packages {
3231 return (NSArray *) packages_;
3234 - (NSArray *) sources {
3235 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3236 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3237 [sources addObject:i->second];
3238 [sources addObjectsFromArray:(NSArray *)deadSources_];
3242 - (NSArray *) issues {
3243 if (cache_->BrokenCount() == 0)
3246 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3248 for (Package *package in [self packages]) {
3249 if (![package broken])
3251 pkgCache::PkgIterator pkg([package iterator]);
3253 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3254 [entry addObject:[package name]];
3255 [issues addObject:entry];
3257 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3261 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3262 pkgCache::DepIterator start;
3263 pkgCache::DepIterator end;
3264 dep.GlobOr(start, end); // ++dep
3266 if (!cache_->IsImportantDep(end))
3268 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3271 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3272 [entry addObject:failure];
3273 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3275 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3276 if (Package *package = [self packageWithName:name])
3277 name = [package name];
3278 [failure addObject:name];
3280 pkgCache::PkgIterator target(start.TargetPkg());
3281 if (target->ProvidesList != 0)
3282 [failure addObject:@"?"];
3284 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3286 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3287 else if (!cache_[target].CandidateVerIter(cache_).end())
3288 [failure addObject:@"-"];
3289 else if (target->ProvidesList == 0)
3290 [failure addObject:@"!"];
3292 [failure addObject:@"%"];
3296 if (start.TargetVer() != 0)
3297 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3308 - (bool) popErrorWithTitle:(NSString *)title {
3310 std::string message;
3312 while (!_error->empty()) {
3314 bool warning(!_error->PopMessage(error));
3318 size_t size(error.size());
3319 if (size == 0 || error[size - 1] != '\n')
3321 error.resize(size - 1);
3323 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3325 if (!message.empty())
3330 if (fatal && !message.empty())
3331 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3336 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3337 return [self popErrorWithTitle:title] || !success;
3340 - (void) reloadData { CYPoolStart() {
3341 @synchronized (self) {
3344 [self releasePackages];
3347 CFArrayRemoveAllValues(deadSources_);
3367 apr_pool_clear(pool_);
3369 NSRecycleZone(zone_);
3370 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3372 int chk(creat("/tmp/cydia.chk", 0644));
3376 NSString *title(UCLocalize("DATABASE"));
3379 if (!cache_.Open(progress_, true)) { pop:
3381 bool warning(!_error->PopMessage(error));
3382 lprintf("cache_.Open():[%s]\n", error.c_str());
3384 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3385 [delegate_ repairWithSelector:@selector(configure)];
3386 else if (error == "The package lists or status file could not be parsed or opened.")
3387 [delegate_ repairWithSelector:@selector(update)];
3388 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3389 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3390 // else if (error == "The list of sources could not be read.")
3392 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3401 unlink("/tmp/cydia.chk");
3403 now_ = [[NSDate date] timeIntervalSince1970];
3405 policy_ = new pkgDepCache::Policy();
3406 records_ = new pkgRecords(cache_);
3407 resolver_ = new pkgProblemResolver(cache_);
3408 fetcher_ = new pkgAcquire(&status_);
3411 list_ = new pkgSourceList();
3412 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3415 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3416 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3420 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3423 if (cache_->BrokenCount() != 0) {
3424 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3427 if (cache_->BrokenCount() != 0) {
3428 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3432 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3436 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3438 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3439 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3440 // XXX: this could be more intelligent
3441 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3442 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3443 if (!cached.end()) {
3444 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3449 CFArrayAppendValue(deadSources_, [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3453 /*std::vector<Package *> packages;
3454 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3455 [packages_ release];
3460 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3461 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3462 //packages.push_back(package);
3463 CFArrayAppendValue(packages_, [package retain]);
3467 /*if (packages.empty())
3468 packages_ = [[NSArray alloc] init];
3470 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3473 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3474 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3475 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3483 /*if (!packages.empty())
3484 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3485 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3487 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3489 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3491 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3495 size_t count(CFArrayGetCount(packages_));
3496 MetaFile_->active_ = count;
3498 for (size_t index(0); index != count; ++index)
3499 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3503 } } CYPoolEnd() _trace(); }
3506 @synchronized (self) {
3508 resolver_ = new pkgProblemResolver(cache_);
3510 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3511 if (!cache_[iterator].Keep()) {
3512 cache_->MarkKeep(iterator, false);
3513 cache_->SetReInstall(iterator, false);
3518 - (void) configure {
3519 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3521 system([dpkg UTF8String]);
3526 // XXX: I don't remember this condition
3531 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3533 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3535 if ([self popErrorWithTitle:title])
3539 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3542 public pkgArchiveCleaner
3545 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3550 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3557 fetcher_->Shutdown();
3559 pkgRecords records(cache_);
3561 lock_ = new FileFd();
3562 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3564 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3566 if ([self popErrorWithTitle:title])
3570 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3573 manager_ = (_system->CreatePM(cache_));
3574 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3581 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3583 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3585 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3587 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3588 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3591 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3596 [CydiaApp retainNetworkActivityIndicator];
3598 bool failed = false;
3599 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3600 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3602 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3605 std::string uri = (*item)->DescURI();
3606 std::string error = (*item)->ErrorText;
3608 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3611 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3612 withObject:[NSArray arrayWithObjects:
3613 [NSString stringWithUTF8String:error.c_str()],
3619 [CydiaApp releaseNetworkActivityIndicator];
3627 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3629 if (_error->PendingError()) {
3634 if (result == pkgPackageManager::Failed) {
3639 if (result != pkgPackageManager::Completed) {
3644 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3646 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3648 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3649 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3652 if (![before isEqualToArray:after])
3657 NSString *title(UCLocalize("UPGRADE"));
3658 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3664 [self updateWithStatus:status_];
3667 - (void) updateWithStatus:(Status &)status {
3668 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3669 NSString *title(UCLocalize("REFRESHING_DATA"));
3672 if (!list.ReadMainList())
3673 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3676 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3677 if ([self popErrorWithTitle:title])
3680 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3681 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3682 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3684 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3688 - (void) setDelegate:(id)delegate {
3689 delegate_ = delegate;
3690 status_.setDelegate(delegate);
3691 progress_.setDelegate(delegate);
3694 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3695 SourceMap::const_iterator i(sources_.find(file->ID));
3696 return i == sources_.end() ? nil : i->second;
3699 - (NSString *) mappedSectionForPointer:(const char *)section {
3700 _H<NSString> *mapped;
3702 _profile(Database$mappedSectionForPointer$Cache)
3703 mapped = §ions_[section];
3706 if (*mapped == NULL) {
3707 size_t length(strlen(section));
3708 char spaced[length + 1];
3710 _profile(Database$mappedSectionForPointer$Replace)
3711 for (size_t index(0); index != length; ++index)
3712 spaced[index] = section[index] == '_' ? ' ' : section[index];
3713 spaced[length] = '\0';
3718 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3719 string = [NSString stringWithUTF8String:spaced];
3722 _profile(Database$mappedSectionForPointer$Map)
3723 string = [SectionMap_ objectForKey:string] ?: string;
3733 /* Web Scripting {{{ */
3734 @interface CydiaObject : NSObject {
3736 _transient id delegate_;
3739 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3742 @implementation CydiaObject
3745 [indirect_ release];
3749 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3750 if ((self = [super init]) != nil) {
3751 indirect_ = [indirect retain];
3755 - (void) setDelegate:(id)delegate {
3756 delegate_ = delegate;
3759 + (NSArray *) _attributeKeys {
3760 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3763 - (NSArray *) attributeKeys {
3764 return [[self class] _attributeKeys];
3767 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3768 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3771 - (NSString *) device {
3772 return [[UIDevice currentDevice] uniqueIdentifier];
3775 #if 0 // XXX: implement!
3776 - (NSString *) mac {
3777 if (![indirect_ promptForSensitive:@"Mac Address"])
3781 - (NSString *) serial {
3782 if (![indirect_ promptForSensitive:@"Serial #"])
3786 - (NSString *) firewire {
3787 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3791 - (NSString *) imei {
3792 if (![indirect_ promptForSensitive:@"IMEI"])
3797 + (NSString *) webScriptNameForSelector:(SEL)selector {
3798 if (selector == @selector(close))
3800 else if (selector == @selector(getInstalledPackages))
3801 return @"getInstalledPackages";
3802 else if (selector == @selector(getPackageById:))
3803 return @"getPackageById";
3804 else if (selector == @selector(installPackages:))
3805 return @"installPackages";
3806 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3807 return @"setButtonImage";
3808 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3809 return @"setButtonTitle";
3810 else if (selector == @selector(setPopupHook:))
3811 return @"setPopupHook";
3812 else if (selector == @selector(setSpecial:))
3813 return @"setSpecial";
3814 else if (selector == @selector(setToken:))
3816 else if (selector == @selector(setViewportWidth:))
3817 return @"setViewportWidth";
3818 else if (selector == @selector(supports:))
3820 else if (selector == @selector(stringWithFormat:arguments:))
3822 else if (selector == @selector(localizedStringForKey:value:table:))
3824 else if (selector == @selector(du:))
3826 else if (selector == @selector(statfs:))
3832 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3833 return [self webScriptNameForSelector:selector] == nil;
3836 - (BOOL) supports:(NSString *)feature {
3837 return [feature isEqualToString:@"window.open"];
3840 - (NSArray *) getInstalledPackages {
3841 NSArray *packages([[Database sharedInstance] packages]);
3842 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3843 for (Package *package in packages)
3844 if ([package installed] != nil)
3845 [installed addObject:package];
3849 - (Package *) getPackageById:(NSString *)id {
3850 Package *package([[Database sharedInstance] packageWithName:id]);
3855 - (NSArray *) statfs:(NSString *)path {
3858 if (path == nil || statfs([path UTF8String], &stat) == -1)
3861 return [NSArray arrayWithObjects:
3862 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3863 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3864 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3868 - (NSNumber *) du:(NSString *)path {
3869 NSNumber *value(nil);
3872 _assert(pipe(fds) != -1);
3874 pid_t pid(ExecFork());
3876 _assert(dup2(fds[1], 1) != -1);
3877 _assert(close(fds[0]) != -1);
3878 _assert(close(fds[1]) != -1);
3879 /* XXX: this should probably not use du */
3880 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3885 _assert(close(fds[1]) != -1);
3887 if (FILE *du = fdopen(fds[0], "r")) {
3889 while (fgets(line, sizeof(line), du) != NULL) {
3890 size_t length(strlen(line));
3891 while (length != 0 && line[length - 1] == '\n')
3892 line[--length] = '\0';
3893 if (char *tab = strchr(line, '\t')) {
3895 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3900 } else _assert(close(fds[0]));
3904 if (waitpid(pid, &status, 0) == -1)
3907 else _assert(false);
3916 - (void) installPackages:(NSArray *)packages {
3917 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3920 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3921 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3924 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3925 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3928 - (void) setSpecial:(id)function {
3929 [indirect_ setSpecial:function];
3932 - (void) setToken:(NSString *)token {
3935 Token_ = [token retain];
3937 [Metadata_ setObject:Token_ forKey:@"Token"];
3941 - (void) setPopupHook:(id)function {
3942 [indirect_ setPopupHook:function];
3945 - (void) setViewportWidth:(float)width {
3946 [indirect_ setViewportWidth:width];
3949 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3950 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3951 unsigned count([arguments count]);
3953 for (unsigned i(0); i != count; ++i)
3954 values[i] = [arguments objectAtIndex:i];
3955 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3958 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3959 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3961 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3963 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3969 /* @ Loading... Indicator {{{ */
3970 @interface CYLoadingIndicator : UIView {
3971 UIActivityIndicatorView *spinner_;
3976 @property (readonly, nonatomic) UILabel *label;
3977 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
3981 @implementation CYLoadingIndicator
3983 - (id)initWithFrame:(CGRect)frame {
3984 if ((self = [super initWithFrame:frame])) {
3985 container_ = [[[UIView alloc] init] autorelease];
3986 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
3988 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
3989 [spinner_ startAnimating];
3990 [container_ addSubview:spinner_];
3992 label_ = [[[UILabel alloc] init] autorelease];
3993 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
3994 [label_ setBackgroundColor:[UIColor clearColor]];
3995 [label_ setTextColor:[UIColor blackColor]];
3996 [label_ setShadowColor:[UIColor whiteColor]];
3997 [label_ setShadowOffset:CGSizeMake(0, 1)];
3998 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
3999 [container_ addSubview:label_];
4001 CGSize viewsize = frame.size;
4002 CGSize spinnersize = [spinner_ bounds].size;
4003 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4004 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4006 CGRect containrect = {
4007 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4008 CGSizeMake(bothwidth, spinnersize.height)
4011 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4019 [container_ setFrame:containrect];
4020 [spinner_ setFrame:spinrect];
4021 [label_ setFrame:textrect];
4022 [self addSubview:container_];
4028 - (UILabel *)label { return label_; }
4029 - (UIActivityIndicatorView *)activityIndicatorView { return spinner_; }
4033 /* Emulated Loading Controller {{{ */
4034 @interface CYEmulatedLoadingController : CYViewController {
4035 CYLoadingIndicator *indicator_;
4037 UINavigationBar *navbar_;
4041 @implementation CYEmulatedLoadingController
4043 - (CYEmulatedLoadingController *) init {
4044 if ((self = [super init])) {
4045 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4047 indicator_ = [[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]];
4048 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4049 [[self view] addSubview:indicator_];
4050 [indicator_ release];
4052 tabbar_ = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
4053 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4054 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4055 [[self view] addSubview:tabbar_];
4058 navbar_ = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
4059 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4060 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4061 [[self view] addSubview:navbar_];
4069 /* Cydia Browser Controller {{{ */
4070 @interface CYBrowserController : BrowserController {
4071 CydiaObject *cydia_;
4076 @implementation CYBrowserController
4083 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4086 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4087 [super webView:view didClearWindowObject:window forFrame:frame];
4089 WebDataSource *source([frame dataSource]);
4090 NSURLResponse *response([source response]);
4091 NSURL *url([response URL]);
4092 NSString *scheme([url scheme]);
4094 NSHTTPURLResponse *http;
4095 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
4096 http = (NSHTTPURLResponse *) response;
4100 NSDictionary *headers([http allHeaderFields]);
4101 NSString *host([url host]);
4102 [self setHeaders:headers forHost:host];
4105 [host isEqualToString:@"cydia.saurik.com"] ||
4106 [host hasSuffix:@".cydia.saurik.com"] ||
4107 [scheme isEqualToString:@"file"]
4109 [window setValue:cydia_ forKey:@"cydia"];
4112 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4113 if (System_ != NULL)
4114 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4115 if (Machine_ != NULL)
4116 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4118 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4120 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4123 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4124 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4125 [self _setMoreHeaders:copy];
4129 - (void) setDelegate:(id)delegate {
4130 [super setDelegate:delegate];
4131 [cydia_ setDelegate:delegate];
4135 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4136 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4138 WebView *webview([[webview_ _documentView] webView]);
4140 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4142 NSString *application = package == nil ? @"Cydia" : [NSString
4143 stringWithFormat:@"Cydia/%@",
4148 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4150 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4151 if (Product_ != nil)
4152 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4154 [webview setApplicationNameForUserAgent:application];
4161 /* Confirmation Controller {{{ */
4162 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4163 if (!iterator.end())
4164 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4165 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4167 pkgCache::PkgIterator package(dep.TargetPkg());
4170 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4177 @protocol ConfirmationControllerDelegate
4178 - (void) cancelAndClear:(bool)clear;
4179 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4183 @interface ConfirmationController : CYBrowserController {
4184 _transient Database *database_;
4185 UIAlertView *essential_;
4192 - (id) initWithDatabase:(Database *)database;
4196 @implementation ConfirmationController
4203 if (essential_ != nil)
4204 [essential_ release];
4208 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4209 NSString *context([alert context]);
4211 if ([context isEqualToString:@"remove"]) {
4212 if (button == [alert cancelButtonIndex]) {
4213 [self dismissModalViewControllerAnimated:YES];
4214 } else if (button == [alert firstOtherButtonIndex]) {
4217 [delegate_ confirmWithNavigationController:[self navigationController]];
4220 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4221 } else if ([context isEqualToString:@"unable"]) {
4222 [self dismissModalViewControllerAnimated:YES];
4223 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4225 [super alertView:alert clickedButtonAtIndex:button];
4229 - (void) _doContinue {
4230 [self dismissModalViewControllerAnimated:YES];
4231 [delegate_ cancelAndClear:NO];
4234 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4235 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4239 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4240 [super webView:view didClearWindowObject:window forFrame:frame];
4241 [window setValue:changes_ forKey:@"changes"];
4242 [window setValue:issues_ forKey:@"issues"];
4243 [window setValue:sizes_ forKey:@"sizes"];
4244 [window setValue:self forKey:@"queue"];
4247 - (id) initWithDatabase:(Database *)database {
4248 if ((self = [super init]) != nil) {
4249 database_ = database;
4251 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4253 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4254 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4255 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4256 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4257 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4261 pkgDepCache::Policy *policy([database_ policy]);
4263 pkgCacheFile &cache([database_ cache]);
4264 NSArray *packages = [database_ packages];
4265 for (Package *package in packages) {
4266 pkgCache::PkgIterator iterator = [package iterator];
4267 pkgDepCache::StateCache &state(cache[iterator]);
4269 NSString *name([package name]);
4271 if (state.NewInstall())
4272 [installing addObject:name];
4273 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4274 [reinstalling addObject:name];
4275 else if (state.Upgrade())
4276 [upgrading addObject:name];
4277 else if (state.Downgrade())
4278 [downgrading addObject:name];
4279 else if (state.Delete()) {
4280 if ([package essential])
4282 [removing addObject:name];
4285 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4286 substrate_ |= DepSubstrate(iterator.CurrentVer());
4291 else if (Advanced_) {
4292 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4294 essential_ = [[UIAlertView alloc]
4295 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4296 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4298 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4299 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4302 [essential_ setContext:@"remove"];
4304 essential_ = [[UIAlertView alloc]
4305 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4306 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4308 cancelButtonTitle:UCLocalize("OKAY")
4309 otherButtonTitles:nil
4312 [essential_ setContext:@"unable"];
4315 changes_ = [[NSArray alloc] initWithObjects:
4323 issues_ = [database_ issues];
4325 issues_ = [issues_ retain];
4327 sizes_ = [[NSArray alloc] initWithObjects:
4328 SizeString([database_ fetcher].FetchNeeded()),
4329 SizeString([database_ fetcher].PartialPresent()),
4332 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4334 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4335 initWithTitle:UCLocalize("CANCEL")
4336 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4337 style:UIBarButtonItemStylePlain
4339 action:@selector(cancelButtonClicked)
4344 - (void) applyRightButton {
4345 #if !AlwaysReload && !IgnoreInstall
4346 if (issues_ == nil && ![self isLoading])
4347 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4348 initWithTitle:UCLocalize("CONFIRM")
4349 style:UIBarButtonItemStylePlain
4351 action:@selector(confirmButtonClicked)
4354 [super applyRightButton];
4356 [[self navigationItem] setRightBarButtonItem:nil];
4360 - (void) cancelButtonClicked {
4361 [self dismissModalViewControllerAnimated:YES];
4362 [delegate_ cancelAndClear:YES];
4366 - (void) confirmButtonClicked {
4370 if (essential_ != nil)
4375 [delegate_ confirmWithNavigationController:[self navigationController]];
4383 /* Progress Data {{{ */
4384 @interface ProgressData : NSObject {
4386 // XXX: should these really both be _transient?
4387 _transient id target_;
4388 _transient id object_;
4391 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4398 @implementation ProgressData
4400 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4401 if ((self = [super init]) != nil) {
4402 selector_ = selector;
4422 /* Progress Controller {{{ */
4423 @interface ProgressController : CYViewController <
4424 ConfigurationDelegate,
4427 _transient Database *database_;
4428 UIProgressBar *progress_;
4429 UITextView *output_;
4430 UITextLabel *status_;
4431 UIPushButton *close_;
4433 SHA1SumValue springlist_;
4434 SHA1SumValue notifyconf_;
4438 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4440 - (void) _retachThread;
4441 - (void) _detachNewThreadData:(ProgressData *)data;
4442 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4448 @protocol ProgressControllerDelegate
4449 - (void) progressControllerIsComplete:(ProgressController *)sender;
4452 @implementation ProgressController
4455 [database_ setDelegate:nil];
4456 [progress_ release];
4465 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4466 if ((self = [super init]) != nil) {
4467 database_ = database;
4468 [database_ setDelegate:self];
4469 delegate_ = delegate;
4471 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4473 progress_ = [[UIProgressBar alloc] init];
4474 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4475 [progress_ setStyle:0];
4477 status_ = [[UITextLabel alloc] init];
4478 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4479 [status_ setColor:[UIColor whiteColor]];
4480 [status_ setBackgroundColor:[UIColor clearColor]];
4481 [status_ setCentersHorizontally:YES];
4482 //[status_ setFont:font];
4484 output_ = [[UITextView alloc] init];
4485 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4486 //[output_ setTextFont:@"Courier New"];
4487 [output_ setFont:[[output_ font] fontWithSize:12]];
4488 [output_ setTextColor:[UIColor whiteColor]];
4489 [output_ setBackgroundColor:[UIColor clearColor]];
4490 [output_ setMarginTop:0];
4491 [output_ setAllowsRubberBanding:YES];
4492 [output_ setEditable:NO];
4493 [[self view] addSubview:output_];
4495 close_ = [[UIPushButton alloc] init];
4496 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4497 [close_ setAutosizesToFit:NO];
4498 [close_ setDrawsShadow:YES];
4499 [close_ setStretchBackground:YES];
4500 [close_ setEnabled:YES];
4501 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4502 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4503 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4504 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4508 - (void) positionViews {
4509 CGRect bounds = [[self view] bounds];
4510 CGSize prgsize = [UIProgressBar defaultSize];
4513 (bounds.size.width - prgsize.width) / 2,
4514 bounds.size.height - prgsize.height - 20
4517 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4519 [progress_ setFrame:prgrect];
4520 [status_ setFrame:CGRectMake(
4522 bounds.size.height - prgsize.height - 50,
4523 bounds.size.width - 20,
4526 [output_ setFrame:CGRectMake(
4529 bounds.size.width - 20,
4530 bounds.size.height - 96
4532 [close_ setFrame:CGRectMake(
4533 (bounds.size.width - closewidth) / 2,
4534 bounds.size.height - prgsize.height - 50,
4540 - (void) viewWillAppear:(BOOL)animated {
4541 [super viewDidAppear:animated];
4542 [[self navigationItem] setHidesBackButton:YES];
4543 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4545 [self positionViews];
4548 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4549 [self positionViews];
4552 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4553 NSString *context([alert context]);
4555 if ([context isEqualToString:@"conffile"]) {
4556 FILE *input = [database_ input];
4557 if (button == [alert cancelButtonIndex])
4558 fprintf(input, "N\n");
4559 else if (button == [alert firstOtherButtonIndex])
4560 fprintf(input, "Y\n");
4565 - (void) closeButtonPushed {
4568 UpdateExternalStatus(0);
4572 [self dismissModalViewControllerAnimated:YES];
4576 [delegate_ terminateWithSuccess];
4577 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4578 [delegate_ suspendWithAnimation:YES];
4580 [delegate_ suspend];*/
4592 system("/usr/bin/sbreload");
4598 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4599 SBReboot(SBSSpringBoardServerPort());
4601 reboot2(RB_AUTOBOOT);
4606 - (void) _retachThread {
4607 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4609 [[self view] addSubview:close_];
4610 [progress_ removeFromSuperview];
4611 [status_ removeFromSuperview];
4613 [database_ popErrorWithTitle:title_];
4614 [delegate_ progressControllerIsComplete:self];
4618 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4621 MMap mmap(file, MMap::ReadOnly);
4623 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4624 if (!(notifyconf_ == sha1.Result()))
4631 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4634 MMap mmap(file, MMap::ReadOnly);
4636 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4637 if (!(springlist_ == sha1.Result()))
4643 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4644 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4645 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4646 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4647 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4651 system("su -c /usr/bin/uicache mobile");
4654 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4656 [delegate_ setStatusBarShowsProgress:NO];
4659 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4660 [[data target] performSelector:[data selector] withObject:[data object]];
4661 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4664 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4665 UpdateExternalStatus(1);
4672 title_ = [title retain];
4674 [[self navigationItem] setTitle:title_];
4676 [status_ setText:nil];
4677 [output_ setText:@""];
4678 [progress_ setProgress:0];
4680 [close_ removeFromSuperview];
4681 [[self view] addSubview:progress_];
4682 [[self view] addSubview:status_];
4684 [delegate_ setStatusBarShowsProgress:YES];
4689 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4692 MMap mmap(file, MMap::ReadOnly);
4694 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4695 notifyconf_ = sha1.Result();
4701 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4704 MMap mmap(file, MMap::ReadOnly);
4706 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4707 springlist_ = sha1.Result();
4712 detachNewThreadSelector:@selector(_detachNewThreadData:)
4714 withObject:[[[ProgressData alloc]
4715 initWithSelector:selector
4722 - (void) repairWithSelector:(SEL)selector {
4724 detachNewThreadSelector:selector
4727 title:UCLocalize("REPAIRING")
4731 - (void) setConfigurationData:(NSString *)data {
4733 performSelectorOnMainThread:@selector(_setConfigurationData:)
4739 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4740 CYActionSheet *sheet([[[CYActionSheet alloc]
4742 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4743 defaultButtonIndex:0
4746 [sheet setMessage:error];
4747 [sheet yieldToPopupAlertAnimated:YES];
4751 - (void) setProgressTitle:(NSString *)title {
4753 performSelectorOnMainThread:@selector(_setProgressTitle:)
4759 - (void) setProgressPercent:(float)percent {
4761 performSelectorOnMainThread:@selector(_setProgressPercent:)
4762 withObject:[NSNumber numberWithFloat:percent]
4767 - (void) startProgress {
4770 - (void) addProgressOutput:(NSString *)output {
4772 performSelectorOnMainThread:@selector(_addProgressOutput:)
4778 - (bool) isCancelling:(size_t)received {
4782 - (void) _setConfigurationData:(NSString *)data {
4783 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4785 if (!conffile_r(data)) {
4786 lprintf("E:invalid conffile\n");
4790 NSString *ofile = conffile_r[1];
4791 //NSString *nfile = conffile_r[2];
4793 UIAlertView *alert = [[[UIAlertView alloc]
4794 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4795 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4797 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4798 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4799 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4803 [alert setContext:@"conffile"];
4807 - (void) _setProgressTitle:(NSString *)title {
4808 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4809 for (size_t i(0), e([words count]); i != e; ++i) {
4810 NSString *word([words objectAtIndex:i]);
4811 if (Package *package = [database_ packageWithName:word])
4812 [words replaceObjectAtIndex:i withObject:[package name]];
4815 [status_ setText:[words componentsJoinedByString:@" "]];
4818 - (void) _setProgressPercent:(NSNumber *)percent {
4819 [progress_ setProgress:[percent floatValue]];
4822 - (void) _addProgressOutput:(NSString *)output {
4823 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4824 CGSize size = [output_ contentSize];
4825 CGPoint offset = [output_ contentOffset];
4826 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
4827 CGRect rect = {{0, size.height-1}, {size.width, 1}};
4828 [output_ scrollRectToVisible:rect animated:YES];
4832 - (BOOL) isRunning {
4839 /* Cell Content View {{{ */
4840 @protocol ContentDelegate
4841 - (void) drawContentRect:(CGRect)rect;
4844 @interface ContentView : UIView {
4845 _transient id<ContentDelegate> delegate_;
4850 @implementation ContentView
4852 - (id) initWithFrame:(CGRect)frame {
4853 if ((self = [super initWithFrame:frame]) != nil) {
4854 [self setNeedsDisplayOnBoundsChange:YES];
4858 - (void) setDelegate:(id<ContentDelegate>)delegate {
4859 delegate_ = delegate;
4862 - (void) drawRect:(CGRect)rect {
4863 [super drawRect:rect];
4864 [delegate_ drawContentRect:rect];
4869 /* Cydia TableView Cell {{{ */
4870 @interface CYTableViewCell : UITableViewCell {
4871 ContentView *content_;
4877 @implementation CYTableViewCell
4884 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4885 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4887 if (view == content_) {
4888 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4889 highlighted_ = highlighted;
4892 [super _updateHighlightColorsForView:view highlighted:highlighted];
4895 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4896 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4897 highlighted_ = selected;
4899 [super setSelected:selected animated:animated];
4900 [content_ setNeedsDisplay];
4906 /* Package Cell {{{ */
4907 @interface PackageCell : CYTableViewCell <
4912 NSString *description_;
4920 - (PackageCell *) init;
4921 - (void) setPackage:(Package *)package;
4923 - (void) drawContentRect:(CGRect)rect;
4927 @implementation PackageCell
4929 - (void) clearPackage {
4940 if (description_ != nil) {
4941 [description_ release];
4945 if (source_ != nil) {
4950 if (badge_ != nil) {
4955 if (placard_ != nil) {
4965 [self clearPackage];
4969 - (PackageCell *) init {
4970 CGRect frame(CGRectMake(0, 0, 320, 74));
4971 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4972 UIView *content([self contentView]);
4973 CGRect bounds([content bounds]);
4975 content_ = [[ContentView alloc] initWithFrame:bounds];
4976 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4977 [content addSubview:content_];
4979 [content_ setDelegate:self];
4980 [content_ setOpaque:YES];
4984 - (void) _setBackgroundColor {
4986 if (NSString *mode = [package_ mode]) {
4987 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4988 color = remove ? RemovingColor_ : InstallingColor_;
4990 color = [UIColor whiteColor];
4992 [content_ setBackgroundColor:color];
4993 [self setNeedsDisplay];
4996 - (NSString *) accessibilityLabel {
4997 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5000 - (void) setPackage:(Package *)package {
5001 [self clearPackage];
5004 Source *source = [package source];
5006 icon_ = [[package icon] retain];
5007 name_ = [[package name] retain];
5010 description_ = [package longDescription];
5011 if (description_ == nil)
5012 description_ = [package shortDescription];
5013 if (description_ != nil)
5014 description_ = [description_ retain];
5016 commercial_ = [package isCommercial];
5018 package_ = [package retain];
5020 NSString *label = nil;
5021 bool trusted = false;
5023 if (source != nil) {
5024 label = [source label];
5025 trusted = [source trusted];
5026 } else if ([[package id] isEqualToString:@"firmware"])
5027 label = UCLocalize("APPLE");
5029 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5031 NSString *from(label);
5033 NSString *section = [package simpleSection];
5034 if (section != nil && ![section isEqualToString:label]) {
5035 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5036 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5039 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5040 source_ = [from retain];
5042 if (NSString *purpose = [package primaryPurpose])
5043 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5044 badge_ = [badge_ retain];
5046 if ([package installed] != nil)
5047 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
5048 placard_ = [placard_ retain];
5050 [self _setBackgroundColor];
5051 [content_ setNeedsDisplay];
5054 - (void) drawContentRect:(CGRect)rect {
5055 bool highlighted(highlighted_);
5056 float width([self bounds].size.width);
5059 CGContextRef context(UIGraphicsGetCurrentContext());
5060 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5061 CGContextFillRect(context, rect);
5066 rect.size = [icon_ size];
5068 rect.size.width /= 2;
5069 rect.size.height /= 2;
5071 rect.origin.x = 25 - rect.size.width / 2;
5072 rect.origin.y = 25 - rect.size.height / 2;
5074 [icon_ drawInRect:rect];
5077 if (badge_ != nil) {
5079 rect.size = [badge_ size];
5081 rect.size.width /= 2;
5082 rect.size.height /= 2;
5084 rect.origin.x = 36 - rect.size.width / 2;
5085 rect.origin.y = 36 - rect.size.height / 2;
5087 [badge_ drawInRect:rect];
5094 UISetColor(commercial_ ? Purple_ : Black_);
5095 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5096 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5099 UISetColor(commercial_ ? Purplish_ : Gray_);
5100 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5102 if (placard_ != nil)
5103 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5108 /* Section Cell {{{ */
5109 @interface SectionCell : CYTableViewCell <
5121 - (void) setSection:(Section *)section editing:(BOOL)editing;
5125 @implementation SectionCell
5127 - (void) clearSection {
5128 if (basic_ != nil) {
5133 if (section_ != nil) {
5143 if (count_ != nil) {
5150 [self clearSection];
5156 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5157 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5158 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5159 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5160 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5162 UIView *content([self contentView]);
5163 CGRect bounds([content bounds]);
5165 content_ = [[ContentView alloc] initWithFrame:bounds];
5166 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5167 [content addSubview:content_];
5168 [content_ setBackgroundColor:[UIColor whiteColor]];
5170 [content_ setDelegate:self];
5174 - (void) onSwitch:(id)sender {
5175 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5176 if (metadata == nil) {
5177 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5178 [Sections_ setObject:metadata forKey:basic_];
5181 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5185 - (void) setSection:(Section *)section editing:(BOOL)editing {
5186 if (editing != editing_) {
5188 [switch_ removeFromSuperview];
5190 [self addSubview:switch_];
5194 [self clearSection];
5196 if (section == nil) {
5197 name_ = [UCLocalize("ALL_PACKAGES") retain];
5200 basic_ = [section name];
5202 basic_ = [basic_ retain];
5204 section_ = [section localized];
5205 if (section_ != nil)
5206 section_ = [section_ retain];
5208 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5209 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5212 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5215 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5216 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5218 [content_ setNeedsDisplay];
5221 - (void) setFrame:(CGRect)frame {
5222 [super setFrame:frame];
5224 CGRect rect([switch_ frame]);
5225 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5228 - (NSString *) accessibilityLabel {
5232 - (void) drawContentRect:(CGRect)rect {
5233 bool highlighted(highlighted_ && !editing_);
5235 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5240 float width(rect.size.width);
5246 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5248 CGSize size = [count_ sizeWithFont:Font14_];
5252 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5258 /* File Table {{{ */
5259 @interface FileTable : CYViewController <
5260 UITableViewDataSource,
5263 _transient Database *database_;
5266 NSMutableArray *files_;
5270 - (id) initWithDatabase:(Database *)database;
5271 - (void) setPackage:(Package *)package;
5275 @implementation FileTable
5278 if (package_ != nil)
5287 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5288 return files_ == nil ? 0 : [files_ count];
5291 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5295 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5296 static NSString *reuseIdentifier = @"Cell";
5298 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5300 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5301 [cell setFont:[UIFont systemFontOfSize:16]];
5303 [cell setText:[files_ objectAtIndex:indexPath.row]];
5304 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5309 - (id) initWithDatabase:(Database *)database {
5310 if ((self = [super init]) != nil) {
5311 database_ = database;
5313 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5315 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5317 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5318 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5319 [list_ setRowHeight:24.0f];
5320 [[self view] addSubview:list_];
5322 [list_ setDataSource:self];
5323 [list_ setDelegate:self];
5327 - (void) setPackage:(Package *)package {
5328 if (package_ != nil) {
5329 [package_ autorelease];
5338 [files_ removeAllObjects];
5340 if (package != nil) {
5341 package_ = [package retain];
5342 name_ = [[package id] retain];
5344 if (NSArray *files = [package files])
5345 [files_ addObjectsFromArray:files];
5347 if ([files_ count] != 0) {
5348 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5349 [files_ removeObjectAtIndex:0];
5350 [files_ sortUsingSelector:@selector(compareByPath:)];
5352 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5353 [stack addObject:@"/"];
5355 for (int i(0), e([files_ count]); i != e; ++i) {
5356 NSString *file = [files_ objectAtIndex:i];
5357 while (![file hasPrefix:[stack lastObject]])
5358 [stack removeLastObject];
5359 NSString *directory = [stack lastObject];
5360 [stack addObject:[file stringByAppendingString:@"/"]];
5361 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5362 ([stack count] - 2) * 3, "",
5363 [file substringFromIndex:[directory length]]
5372 - (void) reloadData {
5373 [self setPackage:[database_ packageWithName:name_]];
5378 /* Package Controller {{{ */
5379 @interface CYPackageController : CYBrowserController <
5380 UIActionSheetDelegate
5382 _transient Database *database_;
5386 NSMutableArray *buttons_;
5387 UIBarButtonItem *button_;
5390 - (id) initWithDatabase:(Database *)database;
5391 - (void) setPackage:(Package *)package;
5395 @implementation CYPackageController
5398 if (package_ != nil)
5412 if ([self retainCount] == 1)
5413 [delegate_ setPackageController:self];
5417 /* XXX: this is not safe at all... localization of /fail/ */
5418 - (void) _clickButtonWithName:(NSString *)name {
5419 if ([name isEqualToString:UCLocalize("CLEAR")])
5420 [delegate_ clearPackage:package_];
5421 else if ([name isEqualToString:UCLocalize("INSTALL")])
5422 [delegate_ installPackage:package_];
5423 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5424 [delegate_ installPackage:package_];
5425 else if ([name isEqualToString:UCLocalize("REMOVE")])
5426 [delegate_ removePackage:package_];
5427 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5428 [delegate_ installPackage:package_];
5429 else _assert(false);
5432 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5433 NSString *context([sheet context]);
5435 if ([context isEqualToString:@"modify"]) {
5436 if (button != [sheet cancelButtonIndex]) {
5437 NSString *buttonName = [buttons_ objectAtIndex:button];
5438 [self _clickButtonWithName:buttonName];
5441 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5445 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5446 [super webView:view didClearWindowObject:window forFrame:frame];
5447 [window setValue:package_ forKey:@"package"];
5450 - (bool) _allowJavaScriptPanel {
5455 - (void) _customButtonClicked {
5456 int count([buttons_ count]);
5461 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5463 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5464 [buttons addObjectsFromArray:buttons_];
5466 UIActionSheet *sheet = [[[UIActionSheet alloc]
5469 cancelButtonTitle:nil
5470 destructiveButtonTitle:nil
5471 otherButtonTitles:nil
5474 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5476 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5477 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5479 [sheet setContext:@"modify"];
5481 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5485 // We don't want to allow non-commercial packages to do custom things to the install button,
5486 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5487 - (void) customButtonClicked {
5489 [super customButtonClicked];
5491 [self _customButtonClicked];
5494 - (void) reloadButtonClicked {
5495 // Don't reload a commerical package by tapping the loading button,
5496 // but if it's not an Install button, we should forward it on.
5497 if (![package_ uninstalled])
5498 [self _customButtonClicked];
5501 - (void) applyLoadingTitle {
5502 // Don't show "Loading" as the title. Ever.
5505 - (UIBarButtonItem *) rightButton {
5510 - (id) initWithDatabase:(Database *)database {
5511 if ((self = [super init]) != nil) {
5512 database_ = database;
5513 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5514 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5518 - (void) setPackage:(Package *)package {
5519 if (package_ != nil) {
5520 [package_ autorelease];
5529 [buttons_ removeAllObjects];
5531 if (package != nil) {
5534 package_ = [package retain];
5535 name_ = [[package id] retain];
5536 commercial_ = [package isCommercial];
5538 if ([package_ mode] != nil)
5539 [buttons_ addObject:UCLocalize("CLEAR")];
5540 if ([package_ source] == nil);
5541 else if ([package_ upgradableAndEssential:NO])
5542 [buttons_ addObject:UCLocalize("UPGRADE")];
5543 else if ([package_ uninstalled])
5544 [buttons_ addObject:UCLocalize("INSTALL")];
5546 [buttons_ addObject:UCLocalize("REINSTALL")];
5547 if (![package_ uninstalled])
5548 [buttons_ addObject:UCLocalize("REMOVE")];
5555 switch ([buttons_ count]) {
5556 case 0: title = nil; break;
5557 case 1: title = [buttons_ objectAtIndex:0]; break;
5558 default: title = UCLocalize("MODIFY"); break;
5561 button_ = [[UIBarButtonItem alloc]
5563 style:UIBarButtonItemStylePlain
5565 action:@selector(customButtonClicked)
5571 - (bool) isLoading {
5572 return commercial_ ? [super isLoading] : false;
5575 - (void) reloadData {
5576 [self setPackage:[database_ packageWithName:name_]];
5582 /* Package Table {{{ */
5583 @interface PackageTable : UIView <
5584 UITableViewDataSource,
5587 _transient Database *database_;
5589 NSMutableArray *packages_;
5590 NSMutableArray *sections_;
5592 NSMutableArray *index_;
5593 NSMutableDictionary *indices_;
5594 // XXX: this target_ seems to be delegate_. :(
5595 _transient id target_;
5597 // XXX: why do we even have this delegate_?
5598 _transient id delegate_;
5601 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5603 - (void) setDelegate:(id)delegate;
5605 - (void) reloadData;
5606 - (void) resetCursor;
5608 - (UITableView *) list;
5610 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5612 - (void) deselectWithAnimation:(BOOL)animated;
5616 @implementation PackageTable
5619 [packages_ release];
5620 [sections_ release];
5628 #if TryIndexedCollation
5629 + (BOOL) hasIndexedCollation {
5630 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5634 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5635 NSInteger count([sections_ count]);
5636 return count == 0 ? 1 : count;
5639 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5640 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5642 return [[sections_ objectAtIndex:section] name];
5645 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5646 if ([sections_ count] == 0)
5648 return [[sections_ objectAtIndex:section] count];
5651 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5652 @synchronized (database_) {
5653 if ([database_ era] != era_)
5656 Section *section([sections_ objectAtIndex:[path section]]);
5657 NSInteger row([path row]);
5658 Package *package([packages_ objectAtIndex:([section row] + row)]);
5659 return [[package retain] autorelease];
5662 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5663 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5665 cell = [[[PackageCell alloc] init] autorelease];
5666 [cell setPackage:[self packageAtIndexPath:path]];
5670 - (void) deselectWithAnimation:(BOOL)animated {
5671 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5674 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5675 Package *package([self packageAtIndexPath:path]);
5676 package = [database_ packageWithName:[package id]];
5677 [target_ performSelector:action_ withObject:package];
5681 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5682 // XXX: is 20 the most optimal number here?
5683 return [packages_ count] > 20 ? index_ : nil;
5686 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5687 #if TryIndexedCollation
5688 if ([[self class] hasIndexedCollation]) {
5689 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5696 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5697 if ((self = [super initWithFrame:frame]) != nil) {
5698 database_ = database;
5703 #if TryIndexedCollation
5704 if ([[self class] hasIndexedCollation])
5705 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
5708 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5710 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5712 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5713 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5715 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5716 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5717 [list_ setRowHeight:73];
5718 [self addSubview:list_];
5720 [list_ setDataSource:self];
5721 [list_ setDelegate:self];
5725 - (void) setDelegate:(id)delegate {
5726 delegate_ = delegate;
5729 - (bool) hasPackage:(Package *)package {
5733 - (void) reloadData {
5734 era_ = [database_ era];
5735 NSArray *packages = [database_ packages];
5737 [packages_ removeAllObjects];
5738 [sections_ removeAllObjects];
5740 _profile(PackageTable$reloadData$Filter)
5741 for (Package *package in packages)
5742 if ([self hasPackage:package])
5743 [packages_ addObject:package];
5746 [indices_ removeAllObjects];
5748 Section *section = nil;
5750 #if TryIndexedCollation
5751 if ([[self class] hasIndexedCollation]) {
5752 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
5753 NSArray *titles = [collation sectionIndexTitles];
5756 _profile(PackageTable$reloadData$Section)
5757 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5761 _profile(PackageTable$reloadData$Section$Package)
5762 package = [packages_ objectAtIndex:offset];
5763 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
5766 while (secidx < index) {
5769 _profile(PackageTable$reloadData$Section$Allocate)
5770 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
5773 _profile(PackageTable$reloadData$Section$Add)
5774 [sections_ addObject:section];
5778 [section addToCount];
5784 [index_ removeAllObjects];
5786 _profile(PackageTable$reloadData$Section)
5787 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5791 _profile(PackageTable$reloadData$Section$Package)
5792 package = [packages_ objectAtIndex:offset];
5793 index = [package index];
5796 if (section == nil || [section index] != index) {
5797 _profile(PackageTable$reloadData$Section$Allocate)
5798 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5801 [index_ addObject:[section name]];
5802 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5804 _profile(PackageTable$reloadData$Section$Add)
5805 [sections_ addObject:section];
5809 [section addToCount];
5814 _profile(PackageTable$reloadData$List)
5819 - (void) resetCursor {
5820 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5823 - (UITableView *) list {
5827 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5828 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5833 /* Filtered Package Table {{{ */
5834 @interface FilteredPackageTable : PackageTable {
5840 - (void) setObject:(id)object;
5841 - (void) setObject:(id)object forFilter:(SEL)filter;
5843 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5847 @implementation FilteredPackageTable
5855 - (void) setFilter:(SEL)filter {
5858 /* XXX: this is an unsafe optimization of doomy hell */
5859 Method method(class_getInstanceMethod([Package class], filter));
5860 _assert(method != NULL);
5861 imp_ = method_getImplementation(method);
5862 _assert(imp_ != NULL);
5865 - (void) setObject:(id)object {
5871 object_ = [object retain];
5874 - (void) setObject:(id)object forFilter:(SEL)filter {
5875 [self setFilter:filter];
5876 [self setObject:object];
5879 - (bool) hasPackage:(Package *)package {
5880 _profile(FilteredPackageTable$hasPackage)
5881 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5885 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5886 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5887 [self setFilter:filter];
5888 object_ = [object retain];
5895 /* Filtered Package Controller {{{ */
5896 @interface FilteredPackageController : CYViewController {
5897 _transient Database *database_;
5898 FilteredPackageTable *packages_;
5902 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5906 @implementation FilteredPackageController
5909 [packages_ release];
5915 - (void) viewDidAppear:(BOOL)animated {
5916 [super viewDidAppear:animated];
5917 [packages_ deselectWithAnimation:animated];
5920 - (void) didSelectPackage:(Package *)package {
5921 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_] autorelease]);
5922 [view setPackage:package];
5923 [view setDelegate:delegate_];
5924 [[self navigationController] pushViewController:view animated:YES];
5927 - (NSString *) title { return title_; }
5929 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5930 if ((self = [super init]) != nil) {
5931 database_ = database;
5932 title_ = [title copy];
5933 [[self navigationItem] setTitle:title_];
5935 packages_ = [[FilteredPackageTable alloc]
5936 initWithFrame:[[self view] bounds]
5939 action:@selector(didSelectPackage:)
5944 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5945 [[self view] addSubview:packages_];
5949 - (void) reloadData {
5950 [packages_ reloadData];
5953 - (void) setDelegate:(id)delegate {
5954 [super setDelegate:delegate];
5955 [packages_ setDelegate:delegate];
5962 /* Home Controller {{{ */
5963 @interface HomeController : CYBrowserController {
5967 @implementation HomeController
5969 + (BOOL)shouldHideNavigationBar {
5973 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
5974 [super _setMoreHeaders:request];
5977 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
5978 if (UniqueID_ != nil)
5979 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5981 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
5984 - (void) aboutButtonClicked {
5985 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
5987 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
5988 [alert addButtonWithTitle:UCLocalize("CLOSE")];
5989 [alert setCancelButtonIndex:0];
5992 @"Copyright (C) 2008-2010\n"
5993 "Jay Freeman (saurik)\n"
5994 "saurik@saurik.com\n"
5995 "http://www.saurik.com/"
6001 - (void) viewWillAppear:(BOOL)animated {
6002 [super viewWillAppear:animated];
6004 if ([[self class] shouldHideNavigationBar])
6005 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6008 - (void) viewWillDisappear:(BOOL)animated {
6009 [super viewWillDisappear:animated];
6011 if ([[self class] shouldHideNavigationBar])
6012 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6016 if ((self = [super init]) != nil) {
6017 [self loadURL:[NSURL URLWithString:CydiaURL(@"")]];
6019 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6020 initWithTitle:UCLocalize("ABOUT")
6021 style:UIBarButtonItemStylePlain
6023 action:@selector(aboutButtonClicked)
6030 /* Manage Controller {{{ */
6031 @interface ManageController : CYBrowserController {
6034 - (void) queueStatusDidChange;
6037 @implementation ManageController
6040 if ((self = [super init]) != nil) {
6041 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6043 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6045 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6046 initWithTitle:UCLocalize("SETTINGS")
6047 style:UIBarButtonItemStylePlain
6049 action:@selector(settingsButtonClicked)
6052 [self queueStatusDidChange];
6056 - (void) settingsButtonClicked {
6057 [delegate_ showSettings];
6061 - (void) queueButtonClicked {
6065 - (void) applyLoadingTitle {
6066 // No "Loading" title.
6069 - (void) applyRightButton {
6074 - (void) queueStatusDidChange {
6076 if (!IsWildcat_ && Queuing_) {
6077 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6078 initWithTitle:UCLocalize("QUEUE")
6079 style:UIBarButtonItemStyleDone
6081 action:@selector(queueButtonClicked)
6084 [[self navigationItem] setRightBarButtonItem:nil];
6089 - (bool) isLoading {
6096 /* Refresh Bar {{{ */
6097 @interface RefreshBar : UINavigationBar {
6098 UIProgressIndicator *indicator_;
6099 UITextLabel *prompt_;
6100 UIProgressBar *progress_;
6101 UINavigationButton *cancel_;
6106 @implementation RefreshBar
6109 [indicator_ release];
6111 [progress_ release];
6116 - (void) positionViews {
6117 CGRect frame = [cancel_ frame];
6118 frame.size = [cancel_ sizeThatFits:frame.size];
6119 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6120 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6121 [cancel_ setFrame:frame];
6123 CGSize prgsize = {75, 100};
6125 [self frame].size.width - prgsize.width - 10,
6126 ([self frame].size.height - prgsize.height) / 2
6128 [progress_ setFrame:prgrect];
6130 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6131 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6132 CGRect indrect = {{indoffset, indoffset}, indsize};
6133 [indicator_ setFrame:indrect];
6135 CGSize prmsize = {215, indsize.height + 4};
6137 indoffset * 2 + indsize.width,
6138 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6140 [prompt_ setFrame:prmrect];
6143 - (void)setFrame:(CGRect)frame {
6144 [super setFrame:frame];
6146 [self positionViews];
6149 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6150 if ((self = [super initWithFrame:frame])) {
6151 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6153 [self setBarStyle:UIBarStyleBlack];
6155 UIBarStyle barstyle([self _barStyle:NO]);
6156 bool ugly(barstyle == UIBarStyleDefault);
6158 UIProgressIndicatorStyle style = ugly ?
6159 UIProgressIndicatorStyleMediumBrown :
6160 UIProgressIndicatorStyleMediumWhite;
6162 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6163 [indicator_ setStyle:style];
6164 [indicator_ startAnimation];
6165 [self addSubview:indicator_];
6167 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6168 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6169 [prompt_ setBackgroundColor:[UIColor clearColor]];
6170 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6171 [self addSubview:prompt_];
6173 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6174 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6175 [progress_ setStyle:0];
6176 [self addSubview:progress_];
6178 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6179 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6180 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6181 [cancel_ setBarStyle:barstyle];
6183 [self positionViews];
6188 [cancel_ removeFromSuperview];
6192 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6193 [progress_ setProgress:0];
6194 [self addSubview:cancel_];
6198 [cancel_ removeFromSuperview];
6201 - (void) setPrompt:(NSString *)prompt {
6202 [prompt_ setText:prompt];
6205 - (void) setProgress:(float)progress {
6206 [progress_ setProgress:progress];
6212 @class CYNavigationController;
6214 /* Cydia Tab Bar Controller {{{ */
6215 @interface CYTabBarController : UITabBarController <
6218 _transient Database *database_;
6219 RefreshBar *refreshbar_;
6223 // XXX: ok, "updatedelegate_"?...
6224 _transient NSObject<CydiaDelegate> *updatedelegate_;
6229 - (void) dropBar:(BOOL)animated;
6230 - (void) beginUpdate;
6231 - (void) raiseBar:(BOOL)animated;
6236 @implementation CYTabBarController
6238 - (void) reloadData {
6239 size_t count([[self viewControllers] count]);
6240 for (size_t i(0); i != count; ++i) {
6241 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6245 [(CYNavigationController *)[self transientViewController] reloadData];
6248 - (id) initWithDatabase:(Database *)database {
6249 if ((self = [super init]) != nil) {
6250 database_ = database;
6252 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6253 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6255 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6259 - (void) setUpdate:(NSDate *)date {
6263 - (void) beginUpdate {
6264 [refreshbar_ start];
6267 [updatedelegate_ retainNetworkActivityIndicator];
6271 detachNewThreadSelector:@selector(performUpdate)
6277 - (void) performUpdate { _pooled
6279 status.setDelegate(self);
6280 [database_ updateWithStatus:status];
6283 performSelectorOnMainThread:@selector(completeUpdate)
6289 - (void) stopUpdateWithSelector:(SEL)selector {
6291 [updatedelegate_ releaseNetworkActivityIndicator];
6293 [self raiseBar:YES];
6296 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6299 - (void) completeUpdate {
6302 [self stopUpdateWithSelector:@selector(reloadData)];
6305 - (void) cancelUpdate {
6306 [self stopUpdateWithSelector:@selector(updateData)];
6309 - (void) cancelPressed {
6310 [self cancelUpdate];
6317 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6318 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6321 - (void) startProgress {
6324 - (void) setProgressTitle:(NSString *)title {
6326 performSelectorOnMainThread:@selector(_setProgressTitle:)
6332 - (bool) isCancelling:(size_t)received {
6336 - (void) setProgressPercent:(float)percent {
6338 performSelectorOnMainThread:@selector(_setProgressPercent:)
6339 withObject:[NSNumber numberWithFloat:percent]
6344 - (void) addProgressOutput:(NSString *)output {
6346 performSelectorOnMainThread:@selector(_addProgressOutput:)
6352 - (void) _setProgressTitle:(NSString *)title {
6353 [refreshbar_ setPrompt:title];
6356 - (void) _setProgressPercent:(NSNumber *)percent {
6357 [refreshbar_ setProgress:[percent floatValue]];
6360 - (void) _addProgressOutput:(NSString *)output {
6363 - (void) setUpdateDelegate:(id)delegate {
6364 updatedelegate_ = delegate;
6367 - (CGFloat) statusBarHeight {
6368 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6369 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6371 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6375 - (UIView *) transitionView {
6376 if ([self respondsToSelector:@selector(_transitionView)])
6377 return [self _transitionView];
6379 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6382 - (void) dropBar:(BOOL)animated {
6387 UIView *transition([self transitionView]);
6388 [[self view] addSubview:refreshbar_];
6390 CGRect barframe([refreshbar_ frame]);
6392 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6393 barframe.origin.y = [self statusBarHeight];
6395 barframe.origin.y = 0;
6397 [refreshbar_ setFrame:barframe];
6400 [UIView beginAnimations:nil context:NULL];
6402 CGRect viewframe = [transition frame];
6403 viewframe.origin.y += barframe.size.height;
6404 viewframe.size.height -= barframe.size.height;
6405 [transition setFrame:viewframe];
6408 [UIView commitAnimations];
6410 // Ensure bar has the proper width for our view, it might have changed
6411 barframe.size.width = viewframe.size.width;
6412 [refreshbar_ setFrame:barframe];
6414 // XXX: fix Apple's layout bug
6415 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6418 - (void) raiseBar:(BOOL)animated {
6423 UIView *transition([self transitionView]);
6424 [refreshbar_ removeFromSuperview];
6426 CGRect barframe([refreshbar_ frame]);
6429 [UIView beginAnimations:nil context:NULL];
6431 CGRect viewframe = [transition frame];
6432 viewframe.origin.y -= barframe.size.height;
6433 viewframe.size.height += barframe.size.height;
6434 [transition setFrame:viewframe];
6437 [UIView commitAnimations];
6439 // XXX: fix Apple's layout bug
6440 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6444 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6445 // XXX: fix Apple's layout bug
6446 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6450 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6451 bool dropped(dropped_);
6456 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6461 // XXX: fix Apple's layout bug
6462 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6465 - (void) statusBarFrameChanged:(NSNotification *)notification {
6473 [refreshbar_ release];
6474 [[NSNotificationCenter defaultCenter] removeObserver:self];
6480 /* Cydia Navigation Controller {{{ */
6481 @interface CYNavigationController : UINavigationController {
6482 _transient Database *database_;
6483 _transient id<UINavigationControllerDelegate> delegate_;
6486 - (id) initWithDatabase:(Database *)database;
6487 - (void) reloadData;
6492 @implementation CYNavigationController
6498 - (void) reloadData {
6499 size_t count([[self viewControllers] count]);
6500 for (size_t i(0); i != count; ++i) {
6501 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6506 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6507 delegate_ = delegate;
6510 - (id) initWithDatabase:(Database *)database {
6511 if ((self = [super init]) != nil) {
6512 database_ = database;
6519 /* Cydia:// Protocol {{{ */
6520 @interface CydiaURLProtocol : NSURLProtocol {
6525 @implementation CydiaURLProtocol
6527 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6528 NSURL *url([request URL]);
6531 NSString *scheme([[url scheme] lowercaseString]);
6532 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6537 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6541 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6542 id<NSURLProtocolClient> client([self client]);
6544 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6546 NSData *data(UIImagePNGRepresentation(icon));
6548 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6549 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6550 [client URLProtocol:self didLoadData:data];
6551 [client URLProtocolDidFinishLoading:self];
6555 - (void) startLoading {
6556 id<NSURLProtocolClient> client([self client]);
6557 NSURLRequest *request([self request]);
6559 NSURL *url([request URL]);
6560 NSString *href([url absoluteString]);
6562 NSString *path([href substringFromIndex:8]);
6563 NSRange slash([path rangeOfString:@"/"]);
6566 if (slash.location == NSNotFound) {
6570 command = [path substringToIndex:slash.location];
6571 path = [path substringFromIndex:(slash.location + 1)];
6574 Database *database([Database sharedInstance]);
6576 if ([command isEqualToString:@"package-icon"]) {
6579 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6580 Package *package([database packageWithName:path]);
6583 UIImage *icon([package icon]);
6584 [self _returnPNGWithImage:icon forRequest:request];
6585 } else if ([command isEqualToString:@"source-icon"]) {
6588 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6589 NSString *source(Simplify(path));
6590 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6592 icon = [UIImage applicationImageNamed:@"unknown.png"];
6593 [self _returnPNGWithImage:icon forRequest:request];
6594 } else if ([command isEqualToString:@"uikit-image"]) {
6597 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6598 UIImage *icon(_UIImageWithName(path));
6599 [self _returnPNGWithImage:icon forRequest:request];
6600 } else if ([command isEqualToString:@"section-icon"]) {
6603 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6604 NSString *section(Simplify(path));
6605 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6607 icon = [UIImage applicationImageNamed:@"unknown.png"];
6608 [self _returnPNGWithImage:icon forRequest:request];
6610 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6614 - (void) stopLoading {
6620 /* Section Controller {{{ */
6621 @interface SectionController : FilteredPackageController {
6624 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6628 @implementation SectionController
6630 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6634 title = UCLocalize("ALL_PACKAGES");
6635 } else if (![name isEqual:@""]) {
6636 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6638 title = UCLocalize("NO_SECTION");
6641 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6647 /* Sections Controller {{{ */
6648 @interface SectionsController : CYViewController <
6649 UITableViewDataSource,
6652 _transient Database *database_;
6653 NSMutableArray *sections_;
6654 NSMutableArray *filtered_;
6659 - (id) initWithDatabase:(Database *)database;
6660 - (void) reloadData;
6663 - (void) editButtonClicked;
6667 @implementation SectionsController
6670 [list_ setDataSource:nil];
6671 [list_ setDelegate:nil];
6673 [sections_ release];
6674 [filtered_ release];
6679 - (void) updateNavigationItem {
6680 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6681 if ([sections_ count] == 0) {
6682 [[self navigationItem] setRightBarButtonItem:nil];
6684 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6685 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6687 action:@selector(editButtonClicked)
6688 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6692 - (void) setEditing:(BOOL)editing {
6693 if ((editing_ = editing))
6696 [delegate_ updateData];
6698 [self updateNavigationItem];
6701 - (void) viewDidAppear:(BOOL)animated {
6702 [super viewDidAppear:animated];
6703 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6706 - (void) viewWillDisappear:(BOOL)animated {
6707 [super viewWillDisappear:animated];
6708 if (editing_) [self setEditing:NO];
6711 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6712 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6716 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6717 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6720 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6724 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6725 static NSString *reuseIdentifier = @"SectionCell";
6727 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6729 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6731 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6736 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6740 Section *section = [self sectionAtIndexPath:indexPath];
6742 SectionController *controller = [[[SectionController alloc]
6743 initWithDatabase:database_
6744 section:[section name]
6746 [controller setDelegate:delegate_];
6748 [[self navigationController] pushViewController:controller animated:YES];
6751 - (id) initWithDatabase:(Database *)database {
6752 if ((self = [super init]) != nil) {
6753 database_ = database;
6755 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6757 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6758 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6760 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6761 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6762 [list_ setRowHeight:45.0f];
6763 [[self view] addSubview:list_];
6765 [list_ setDataSource:self];
6766 [list_ setDelegate:self];
6772 - (void) reloadData {
6773 NSArray *packages = [database_ packages];
6775 [sections_ removeAllObjects];
6776 [filtered_ removeAllObjects];
6778 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6781 for (Package *package in packages) {
6782 NSString *name([package section]);
6783 NSString *key(name == nil ? @"" : name);
6787 _profile(SectionsView$reloadData$Section)
6788 section = [sections objectForKey:key];
6789 if (section == nil) {
6790 _profile(SectionsView$reloadData$Section$Allocate)
6791 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6792 [sections setObject:section forKey:key];
6797 [section addToCount];
6799 _profile(SectionsView$reloadData$Filter)
6800 if (![package valid] || ![package visible])
6808 [sections_ addObjectsFromArray:[sections allValues]];
6810 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6812 for (Section *section in sections_) {
6813 size_t count([section row]);
6817 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6818 [section setCount:count];
6819 [filtered_ addObject:section];
6822 [self updateNavigationItem];
6827 - (void) resetView {
6829 [self editButtonClicked];
6832 - (void)editButtonClicked {
6833 [self setEditing:!editing_];
6839 /* Changes Controller {{{ */
6840 @interface ChangesController : CYViewController <
6841 UITableViewDataSource,
6844 _transient Database *database_;
6846 CFMutableArrayRef packages_;
6847 NSMutableArray *sections_;
6850 BOOL hasSentFirstLoad_;
6853 - (id) initWithDatabase:(Database *)database;
6857 @implementation ChangesController
6860 [list_ setDelegate:nil];
6861 [list_ setDataSource:nil];
6863 CFRelease(packages_);
6865 [sections_ release];
6870 - (void) viewDidAppear:(BOOL)animated {
6871 [super viewDidAppear:animated];
6872 if (!hasSentFirstLoad_) {
6873 hasSentFirstLoad_ = YES;
6874 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6876 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6880 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6881 NSInteger count([sections_ count]);
6882 return count == 0 ? 1 : count;
6885 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6886 if ([sections_ count] == 0)
6888 return [[sections_ objectAtIndex:section] name];
6891 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6892 if ([sections_ count] == 0)
6894 return [[sections_ objectAtIndex:section] count];
6897 - (Package *) packageAtIndex:(NSUInteger)index {
6898 return (Package *) CFArrayGetValueAtIndex(packages_, index);
6901 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6902 @synchronized (database_) {
6903 if ([database_ era] != era_)
6906 NSUInteger sectionIndex([path section]);
6907 if (sectionIndex >= [sections_ count])
6909 Section *section([sections_ objectAtIndex:sectionIndex]);
6910 NSInteger row([path row]);
6911 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
6914 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6915 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6917 cell = [[[PackageCell alloc] init] autorelease];
6918 [cell setPackage:[self packageAtIndexPath:path]];
6922 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6923 Package *package([self packageAtIndexPath:path]);
6924 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_] autorelease]);
6925 [view setDelegate:delegate_];
6926 [view setPackage:package];
6927 [[self navigationController] pushViewController:view animated:YES];
6931 - (void) refreshButtonClicked {
6932 [delegate_ beginUpdate];
6933 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
6936 - (void) upgradeButtonClicked {
6937 [delegate_ distUpgrade];
6940 - (NSString *) title { return UCLocalize("CHANGES"); }
6942 - (id) initWithDatabase:(Database *)database {
6943 if ((self = [super init]) != nil) {
6944 database_ = database;
6945 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
6947 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
6948 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6950 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6951 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6952 [list_ setRowHeight:73];
6953 [[self view] addSubview:list_];
6955 [list_ setDataSource:self];
6956 [list_ setDelegate:self];
6960 - (void) _reloadPackages:(NSArray *)packages {
6961 CFRelease(packages_);
6962 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
6965 _profile(ChangesController$_reloadPackages$Filter)
6966 for (Package *package in packages)
6967 if ([package upgradableAndEssential:YES] || [package visible])
6968 CFArrayAppendValue(packages_, package);
6971 _profile(ChangesController$_reloadPackages$radixSort)
6972 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6977 - (void) reloadData {
6978 @synchronized (database_) {
6979 era_ = [database_ era];
6980 NSArray *packages = [database_ packages];
6982 [sections_ removeAllObjects];
6985 UIProgressHUD *hud([delegate_ addProgressHUD]);
6986 [hud setText:UCLocalize("LOADING")];
6987 //NSLog(@"HUD:%@::%@", delegate_, hud);
6988 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
6989 [delegate_ removeProgressHUD:hud];
6991 [self _reloadPackages:packages];
6994 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6995 Section *ignored = nil;
6996 Section *section = nil;
7000 bool unseens = false;
7002 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7004 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7005 Package *package = [self packageAtIndex:offset];
7007 BOOL uae = [package upgradableAndEssential:YES];
7011 time_t seen([package seen]);
7013 if (section == nil || last != seen) {
7017 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7020 _profile(ChangesController$reloadData$Allocate)
7021 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7022 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7023 [sections_ addObject:section];
7027 [section addToCount];
7028 } else if ([package ignored]) {
7029 if (ignored == nil) {
7030 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7032 [ignored addToCount];
7035 [upgradable addToCount];
7040 CFRelease(formatter);
7043 Section *last = [sections_ lastObject];
7044 size_t count = [last count];
7045 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7046 [sections_ removeLastObject];
7049 if ([ignored count] != 0)
7050 [sections_ insertObject:ignored atIndex:0];
7052 [sections_ insertObject:upgradable atIndex:0];
7057 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7058 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7059 style:UIBarButtonItemStylePlain
7061 action:@selector(upgradeButtonClicked)
7064 if (![delegate_ updating])
7065 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7066 initWithTitle:UCLocalize("REFRESH")
7067 style:UIBarButtonItemStylePlain
7069 action:@selector(refreshButtonClicked)
7077 /* Search Controller {{{ */
7078 @interface SearchController : FilteredPackageController <
7081 UISearchBar *search_;
7084 - (id) initWithDatabase:(Database *)database;
7085 - (void) setSearchTerm:(NSString *)term;
7086 - (void) reloadData;
7090 @implementation SearchController
7097 - (void) setSearchTerm:(NSString *)searchTerm {
7098 [search_ setText:searchTerm];
7101 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7102 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7103 [search_ resignFirstResponder];
7107 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7108 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7112 - (id) initWithDatabase:(Database *)database {
7113 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7116 - (void)viewDidAppear:(BOOL)animated {
7117 [super viewDidAppear:animated];
7119 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7120 [search_ layoutSubviews];
7121 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7123 UITextField *textField;
7124 if ([search_ respondsToSelector:@selector(searchField)])
7125 textField = [search_ searchField];
7127 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7129 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7130 [search_ setDelegate:self];
7131 [textField setEnablesReturnKeyAutomatically:NO];
7132 [[self navigationItem] setTitleView:textField];
7136 - (void) _reloadData {
7139 - (void) reloadData {
7140 _profile(SearchController$reloadData)
7141 [packages_ reloadData];
7144 [packages_ resetCursor];
7147 - (void) didSelectPackage:(Package *)package {
7148 [search_ resignFirstResponder];
7149 [super didSelectPackage:package];
7154 /* Package Settings Controller {{{ */
7155 @interface PackageSettingsController : CYViewController <
7156 UITableViewDataSource,
7159 _transient Database *database_;
7162 UITableView *table_;
7163 UISwitch *subscribedSwitch_;
7164 UISwitch *ignoredSwitch_;
7165 UITableViewCell *subscribedCell_;
7166 UITableViewCell *ignoredCell_;
7169 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7173 @implementation PackageSettingsController
7177 if (package_ != nil)
7180 [subscribedSwitch_ release];
7181 [ignoredSwitch_ release];
7182 [subscribedCell_ release];
7183 [ignoredCell_ release];
7188 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7189 if (package_ == nil)
7195 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7196 if (package_ == nil)
7202 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7203 return UCLocalize("CHANGE_PACKAGE_SETTINGS");
7206 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7207 return UCLocalize("SHOW_ALL_CHANGES_EX");
7210 - (void) onSubscribed:(id)control {
7211 bool value([control isOn]);
7212 if (package_ == nil)
7214 if ([package_ setSubscribed:value])
7215 [delegate_ updateData];
7218 - (void) onIgnored:(id)control {
7219 // TODO: set Held state - possibly call out to dpkg, etc.
7222 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7223 if (package_ == nil)
7226 switch ([indexPath row]) {
7227 case 0: return subscribedCell_;
7228 case 1: return ignoredCell_;
7236 - (NSString *) title { return UCLocalize("SETTINGS"); }
7238 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7239 if ((self = [super init])) {
7240 database_ = database;
7241 name_ = [package retain];
7243 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7245 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7246 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7247 [[self view] addSubview:table_];
7249 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7250 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7251 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7253 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7254 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7255 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7256 // Disable this switch, since it only reflects (not modifies) the ignored state.
7257 [ignoredSwitch_ setUserInteractionEnabled:NO];
7259 subscribedCell_ = [[UITableViewCell alloc] init];
7260 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7261 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7262 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7264 ignoredCell_ = [[UITableViewCell alloc] init];
7265 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7266 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7267 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7268 // FIXME: Ignored state is not saved.
7269 [ignoredCell_ setUserInteractionEnabled:NO];
7271 [table_ setDataSource:self];
7272 [table_ setDelegate:self];
7277 - (void) reloadData {
7278 if (package_ != nil)
7279 [package_ autorelease];
7280 package_ = [database_ packageWithName:name_];
7281 if (package_ != nil) {
7283 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7284 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7287 [table_ reloadData];
7292 /* Signature Controller {{{ */
7293 @interface SignatureController : CYBrowserController {
7294 _transient Database *database_;
7298 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7302 @implementation SignatureController
7309 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7311 [super webView:view didClearWindowObject:window forFrame:frame];
7314 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7315 if ((self = [super init]) != nil) {
7316 database_ = database;
7317 package_ = [package retain];
7322 - (void) reloadData {
7323 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7329 /* Installed Controller {{{ */
7330 @interface InstalledController : FilteredPackageController {
7334 - (id) initWithDatabase:(Database *)database;
7336 - (void) updateRoleButton;
7337 - (void) queueStatusDidChange;
7341 @implementation InstalledController
7347 - (NSString *) title { return UCLocalize("INSTALLED"); }
7349 - (id) initWithDatabase:(Database *)database {
7350 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7351 [self updateRoleButton];
7352 [self queueStatusDidChange];
7357 - (void) queueButtonClicked {
7362 - (void) queueStatusDidChange {
7366 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7367 initWithTitle:UCLocalize("QUEUE")
7368 style:UIBarButtonItemStyleDone
7370 action:@selector(queueButtonClicked)
7373 [[self navigationItem] setLeftBarButtonItem:nil];
7379 - (void) reloadData {
7380 [packages_ reloadData];
7383 - (void) updateRoleButton {
7384 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7385 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7386 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7387 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7389 action:@selector(roleButtonClicked)
7393 - (void) roleButtonClicked {
7394 [packages_ setObject:[NSNumber numberWithBool:expert_]];
7395 [packages_ reloadData];
7398 [self updateRoleButton];
7401 - (void) setDelegate:(id)delegate {
7402 [super setDelegate:delegate];
7403 [packages_ setDelegate:delegate];
7409 /* Source Cell {{{ */
7410 @interface SourceCell : CYTableViewCell <
7418 - (void) setSource:(Source *)source;
7422 @implementation SourceCell
7424 - (void) clearSource {
7434 - (void) setSource:(Source *)source {
7438 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7440 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7441 icon_ = [icon_ retain];
7443 origin_ = [[source name] retain];
7444 label_ = [[source uri] retain];
7446 [content_ setNeedsDisplay];
7454 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7455 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7456 UIView *content([self contentView]);
7457 CGRect bounds([content bounds]);
7459 content_ = [[ContentView alloc] initWithFrame:bounds];
7460 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7461 [content_ setBackgroundColor:[UIColor whiteColor]];
7462 [content addSubview:content_];
7464 [content_ setDelegate:self];
7465 [content_ setOpaque:YES];
7469 - (NSString *) accessibilityLabel {
7473 - (void) drawContentRect:(CGRect)rect {
7474 bool highlighted(highlighted_);
7475 float width(rect.size.width);
7478 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7485 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7489 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7494 /* Source Controller {{{ */
7495 @interface SourceController : FilteredPackageController {
7498 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7502 @implementation SourceController
7504 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7505 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7511 /* Sources Controller {{{ */
7512 @interface SourcesController : CYViewController <
7513 UITableViewDataSource,
7516 _transient Database *database_;
7518 NSMutableArray *sources_;
7522 UIProgressHUD *hud_;
7525 //NSURLConnection *installer_;
7526 NSURLConnection *trivial_;
7527 NSURLConnection *trivial_bz2_;
7528 NSURLConnection *trivial_gz_;
7529 //NSURLConnection *automatic_;
7534 - (id) initWithDatabase:(Database *)database;
7536 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7540 @implementation SourcesController
7542 - (void) _releaseConnection:(NSURLConnection *)connection {
7543 if (connection != nil) {
7544 [connection cancel];
7545 //[connection setDelegate:nil];
7546 [connection release];
7558 //[self _releaseConnection:installer_];
7559 [self _releaseConnection:trivial_];
7560 [self _releaseConnection:trivial_gz_];
7561 [self _releaseConnection:trivial_bz2_];
7562 //[self _releaseConnection:automatic_];
7569 - (void) viewDidAppear:(BOOL)animated {
7570 [super viewDidAppear:animated];
7571 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7574 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7575 return offset_ == 0 ? 1 : 2;
7578 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7579 switch (section + (offset_ == 0 ? 1 : 0)) {
7580 case 0: return UCLocalize("ENTERED_BY_USER");
7581 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7587 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7588 int count = [sources_ count];
7590 case 0: return (offset_ == 0 ? count : offset_);
7591 case 1: return count - offset_;
7597 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7599 switch (indexPath.section) {
7600 case 0: idx = indexPath.row; break;
7601 case 1: idx = indexPath.row + offset_; break;
7605 return [sources_ objectAtIndex:idx];
7608 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7609 static NSString *cellIdentifier = @"SourceCell";
7611 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7612 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7613 [cell setSource:[self sourceAtIndexPath:indexPath]];
7614 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7619 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7620 Source *source = [self sourceAtIndexPath:indexPath];
7622 SourceController *controller = [[[SourceController alloc]
7623 initWithDatabase:database_
7627 [controller setDelegate:delegate_];
7629 [[self navigationController] pushViewController:controller animated:YES];
7632 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7633 Source *source = [self sourceAtIndexPath:indexPath];
7634 return [source record] != nil;
7637 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7638 Source *source = [self sourceAtIndexPath:indexPath];
7639 [Sources_ removeObjectForKey:[source key]];
7640 [delegate_ syncData];
7644 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
7647 @"./", @"Distribution",
7648 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
7650 [delegate_ syncData];
7653 - (NSString *) getWarning {
7654 NSString *href(href_);
7655 NSRange colon([href rangeOfString:@"://"]);
7656 if (colon.location != NSNotFound)
7657 href = [href substringFromIndex:(colon.location + 3)];
7658 href = [href stringByAddingPercentEscapes];
7659 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7660 href = [href stringByCachingURLWithCurrentCDN];
7662 NSURL *url([NSURL URLWithString:href]);
7664 NSStringEncoding encoding;
7665 NSError *error(nil);
7667 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7668 return [warning length] == 0 ? nil : warning;
7672 - (void) _endConnection:(NSURLConnection *)connection {
7673 // XXX: the memory management in this method is horribly awkward
7675 NSURLConnection **field = NULL;
7676 if (connection == trivial_)
7678 else if (connection == trivial_bz2_)
7679 field = &trivial_bz2_;
7680 else if (connection == trivial_gz_)
7681 field = &trivial_gz_;
7682 _assert(field != NULL);
7683 [connection release];
7688 trivial_bz2_ == nil &&
7694 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
7697 UIAlertView *alert = [[[UIAlertView alloc]
7698 initWithTitle:UCLocalize("SOURCE_WARNING")
7701 cancelButtonTitle:UCLocalize("CANCEL")
7702 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
7705 [alert setContext:@"warning"];
7706 [alert setNumberOfRows:1];
7710 } else if (error_ != nil) {
7711 UIAlertView *alert = [[[UIAlertView alloc]
7712 initWithTitle:UCLocalize("VERIFICATION_ERROR")
7713 message:[error_ localizedDescription]
7715 cancelButtonTitle:UCLocalize("OK")
7716 otherButtonTitles:nil
7719 [alert setContext:@"urlerror"];
7722 UIAlertView *alert = [[[UIAlertView alloc]
7723 initWithTitle:UCLocalize("NOT_REPOSITORY")
7724 message:UCLocalize("NOT_REPOSITORY_EX")
7726 cancelButtonTitle:UCLocalize("OK")
7727 otherButtonTitles:nil
7730 [alert setContext:@"trivial"];
7734 [delegate_ setStatusBarShowsProgress:NO];
7735 [delegate_ removeProgressHUD:hud_];
7745 if (error_ != nil) {
7752 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
7753 switch ([response statusCode]) {
7759 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
7760 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
7762 error_ = [error retain];
7763 [self _endConnection:connection];
7766 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
7767 [self _endConnection:connection];
7770 - (NSString *) title { return UCLocalize("SOURCES"); }
7772 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
7773 NSMutableURLRequest *request = [NSMutableURLRequest
7774 requestWithURL:[NSURL URLWithString:href]
7775 cachePolicy:NSURLRequestUseProtocolCachePolicy
7776 timeoutInterval:120.0
7779 [request setHTTPMethod:method];
7781 if (Machine_ != NULL)
7782 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
7783 if (UniqueID_ != nil)
7784 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
7786 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
7788 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
7791 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7792 NSString *context([alert context]);
7794 if ([context isEqualToString:@"source"]) {
7797 NSString *href = [[alert textField] text];
7799 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
7801 if (![href hasSuffix:@"/"])
7802 href_ = [href stringByAppendingString:@"/"];
7805 href_ = [href_ retain];
7807 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
7808 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
7809 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
7810 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
7814 // XXX: this is stupid
7815 hud_ = [[delegate_ addProgressHUD] retain];
7816 [hud_ setText:UCLocalize("VERIFYING_URL")];
7825 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7826 } else if ([context isEqualToString:@"trivial"])
7827 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7828 else if ([context isEqualToString:@"urlerror"])
7829 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7830 else if ([context isEqualToString:@"warning"]) {
7845 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7849 - (id) initWithDatabase:(Database *)database {
7850 if ((self = [super init]) != nil) {
7851 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
7852 [self updateButtonsForEditingStatus:NO animated:NO];
7854 database_ = database;
7855 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
7857 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7858 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7859 [list_ setRowHeight:56];
7860 [[self view] addSubview:list_];
7862 [list_ setDataSource:self];
7863 [list_ setDelegate:self];
7869 - (void) reloadData {
7871 if (!list.ReadMainList())
7874 [sources_ removeAllObjects];
7875 [sources_ addObjectsFromArray:[database_ sources]];
7877 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
7880 int count([sources_ count]);
7882 for (int i = 0; i != count; i++) {
7883 if ([[sources_ objectAtIndex:i] record] == nil)
7888 [list_ setEditing:NO];
7889 [self updateButtonsForEditingStatus:NO animated:NO];
7893 - (void) showAddSourcePrompt {
7894 UIAlertView *alert = [[[UIAlertView alloc]
7895 initWithTitle:UCLocalize("ENTER_APT_URL")
7898 cancelButtonTitle:UCLocalize("CANCEL")
7899 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
7902 [alert setContext:@"source"];
7903 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
7905 [alert setNumberOfRows:1];
7906 [alert addTextFieldWithValue:@"http://" label:@""];
7908 UITextInputTraits *traits = [[alert textField] textInputTraits];
7909 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
7910 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
7911 [traits setKeyboardType:UIKeyboardTypeURL];
7912 // XXX: UIReturnKeyDone
7913 [traits setReturnKeyType:UIReturnKeyNext];
7918 - (void) addButtonClicked {
7919 [self showAddSourcePrompt];
7922 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
7923 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
7924 initWithTitle:UCLocalize("ADD")
7925 style:UIBarButtonItemStylePlain
7927 action:@selector(addButtonClicked)
7928 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
7930 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7931 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
7932 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7934 action:@selector(editButtonClicked)
7935 ] autorelease] animated:animated];
7937 if (IsWildcat_ && !editing)
7938 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7939 initWithTitle:UCLocalize("SETTINGS")
7940 style:UIBarButtonItemStylePlain
7942 action:@selector(settingsButtonClicked)
7946 - (void) settingsButtonClicked {
7947 [delegate_ showSettings];
7950 - (void) editButtonClicked {
7951 [list_ setEditing:![list_ isEditing] animated:YES];
7953 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
7959 /* Settings Controller {{{ */
7960 @interface SettingsController : CYViewController <
7961 UITableViewDataSource,
7964 _transient Database *database_;
7965 // XXX: ok, "roledelegate_"?...
7966 _transient id roledelegate_;
7967 UITableView *table_;
7968 UISegmentedControl *segment_;
7972 - (void) showDoneButton;
7973 - (void) resizeSegmentedControl;
7977 @implementation SettingsController
7981 [container_ release];
7986 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7987 if ((self = [super init])) {
7988 database_ = database;
7989 roledelegate_ = delegate;
7991 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7993 NSArray *items = [NSArray arrayWithObjects:
7995 UCLocalize("HACKER"),
7996 UCLocalize("DEVELOPER"),
7998 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7999 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8000 [container_ addSubview:segment_];
8003 if ([Role_ isEqualToString:@"User"]) index = 0;
8004 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8005 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8007 [segment_ setSelectedSegmentIndex:index];
8008 [self showDoneButton];
8011 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8012 [self resizeSegmentedControl];
8014 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8015 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8016 [table_ setDelegate:self];
8017 [table_ setDataSource:self];
8018 [[self view] addSubview:table_];
8019 [table_ reloadData];
8023 - (void) resizeSegmentedControl {
8024 CGFloat width = [[self view] frame].size.width;
8025 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8028 - (void) viewWillAppear:(BOOL)animated {
8029 [super viewWillAppear:animated];
8031 [self resizeSegmentedControl];
8034 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8035 [self resizeSegmentedControl];
8038 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8039 [self resizeSegmentedControl];
8043 NSString *role(nil);
8045 switch ([segment_ selectedSegmentIndex]) {
8046 case 0: role = @"User"; break;
8047 case 1: role = @"Hacker"; break;
8048 case 2: role = @"Developer"; break;
8053 if (![role isEqualToString:Role_]) {
8054 bool rolling(Role_ == nil);
8057 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8061 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8065 [roledelegate_ loadData];
8067 [roledelegate_ updateData];
8071 - (void) segmentChanged:(UISegmentedControl *)control {
8072 [self showDoneButton];
8075 - (void) saveAndClose {
8078 [[self navigationItem] setRightBarButtonItem:nil];
8079 [[self navigationController] dismissModalViewControllerAnimated:YES];
8082 - (void) doneButtonClicked {
8083 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8084 [spinner startAnimating];
8085 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8086 [[self navigationItem] setRightBarButtonItem:spinItem];
8088 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8091 - (void) showDoneButton {
8092 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8093 initWithTitle:UCLocalize("DONE")
8094 style:UIBarButtonItemStyleDone
8096 action:@selector(doneButtonClicked)
8097 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8100 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8101 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8105 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8109 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8110 return nil; // This method is required by the protocol.
8113 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8115 return UCLocalize("ROLE_EX");
8117 return [NSString stringWithFormat:
8118 @"%@: %@\n%@: %@\n%@: %@",
8119 UCLocalize("USER"), UCLocalize("USER_EX"),
8120 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8121 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8126 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8127 return section == 3 ? 44.0f : 0;
8130 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8131 return section == 3 ? container_ : nil;
8136 /* Stash Controller {{{ */
8137 @interface StashController : CYViewController {
8138 // XXX: just delete these things
8139 _transient UIActivityIndicatorView *spinner_;
8140 _transient UILabel *status_;
8141 _transient UILabel *caption_;
8145 @implementation StashController
8147 if ((self = [super init])) {
8148 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8150 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8151 CGRect spinrect = [spinner_ frame];
8152 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8153 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8154 [spinner_ setFrame:spinrect];
8155 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8156 [[self view] addSubview:spinner_];
8157 [spinner_ startAnimating];
8160 captrect.size.width = [[self view] frame].size.width;
8161 captrect.size.height = 40.0f;
8162 captrect.origin.x = 0;
8163 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8164 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8165 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8166 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8167 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8168 [caption_ setTextColor:[UIColor whiteColor]];
8169 [caption_ setBackgroundColor:[UIColor clearColor]];
8170 [caption_ setShadowColor:[UIColor blackColor]];
8171 [caption_ setTextAlignment:UITextAlignmentCenter];
8172 [[self view] addSubview:caption_];
8175 statusrect.size.width = [[self view] frame].size.width;
8176 statusrect.size.height = 30.0f;
8177 statusrect.origin.x = 0;
8178 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8179 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8180 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8181 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8182 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8183 [status_ setTextColor:[UIColor whiteColor]];
8184 [status_ setBackgroundColor:[UIColor clearColor]];
8185 [status_ setShadowColor:[UIColor blackColor]];
8186 [status_ setTextAlignment:UITextAlignmentCenter];
8187 [[self view] addSubview:status_];
8194 @interface Cydia : UIApplication <
8195 ConfirmationControllerDelegate,
8196 ProgressControllerDelegate,
8198 UINavigationControllerDelegate,
8199 UITabBarControllerDelegate
8201 // XXX: evaluate all fields for _transient
8204 CYTabBarController *tabbar_;
8206 NSMutableArray *essential_;
8207 NSMutableArray *broken_;
8209 Database *database_;
8216 StashController *stash_;
8225 @implementation Cydia
8227 - (void) beginUpdate {
8228 [tabbar_ beginUpdate];
8232 return [tabbar_ updating];
8236 if ([broken_ count] != 0) {
8237 int count = [broken_ count];
8239 UIAlertView *alert = [[[UIAlertView alloc]
8240 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8241 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8243 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8244 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8247 [alert setContext:@"fixhalf"];
8249 } else if (!Ignored_ && [essential_ count] != 0) {
8250 int count = [essential_ count];
8252 UIAlertView *alert = [[[UIAlertView alloc]
8253 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8254 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8256 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8257 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8260 [alert setContext:@"upgrade"];
8265 - (void) _saveConfig {
8271 NSString *error(nil);
8273 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8275 NSError *error(nil);
8276 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8277 NSLog(@"failure to save metadata data: %@", error);
8282 NSLog(@"failure to serialize metadata: %@", error);
8287 // Navigation controller for the queuing badge.
8288 - (CYNavigationController *) queueNavigationController {
8289 NSArray *controllers = [tabbar_ viewControllers];
8290 return [controllers objectAtIndex:3];
8293 - (void) _updateData {
8296 [tabbar_ reloadData];
8298 CYNavigationController *navigation = [self queueNavigationController];
8300 id queuedelegate = nil;
8301 if ([[navigation viewControllers] count] > 0)
8302 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8304 [queuedelegate queueStatusDidChange];
8305 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8308 - (void) _refreshIfPossible {
8309 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8311 bool recently = false;
8312 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8313 if (update != nil) {
8314 NSTimeInterval interval([update timeIntervalSinceNow]);
8315 if (interval <= 0 && interval > -(15*60))
8319 // Don't automatic refresh if:
8320 // - We already refreshed recently.
8321 // - We already auto-refreshed this launch.
8322 // - Auto-refresh is disabled.
8323 if (recently || loaded_ || ManualRefresh) {
8324 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8326 // If we are cancelling due to ManualRefresh or a recent refresh
8327 // we need to make sure it knows it's already loaded.
8331 // We are going to load, so remember that.
8335 SCNetworkReachabilityFlags flags; {
8336 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8337 SCNetworkReachabilityGetFlags(reachability, &flags);
8338 CFRelease(reachability);
8341 // XXX: this elaborate mess is what Apple is using to determine this? :(
8342 // XXX: do we care if the user has to intervene? maybe that's ok?
8344 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8345 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8346 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8347 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8348 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8349 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8353 // If we can reach the server, auto-refresh!
8355 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8360 - (void) refreshIfPossible {
8361 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8364 - (void) _reloadData {
8365 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8366 [hud setText:UCLocalize("RELOADING_DATA")];
8368 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8371 [self removeProgressHUD:hud];
8375 [essential_ removeAllObjects];
8376 [broken_ removeAllObjects];
8378 NSArray *packages([database_ packages]);
8379 for (Package *package in packages) {
8381 [broken_ addObject:package];
8382 if ([package upgradableAndEssential:NO]) {
8383 if ([package essential])
8384 [essential_ addObject:package];
8389 NSLog(@"changes:#%u", changes);
8391 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8394 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8395 [changesItem setBadgeValue:badge];
8396 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8397 [self setApplicationIconBadgeNumber:changes];
8400 [changesItem setBadgeValue:nil];
8401 [changesItem setAnimatedBadge:NO];
8402 [self setApplicationIconBadgeNumber:0];
8407 [self refreshIfPossible];
8410 - (void) updateData {
8419 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8420 _assert(file != NULL);
8422 for (NSString *key in [Sources_ allKeys]) {
8423 NSDictionary *source([Sources_ objectForKey:key]);
8425 fprintf(file, "%s %s %s\n",
8426 [[source objectForKey:@"Type"] UTF8String],
8427 [[source objectForKey:@"URI"] UTF8String],
8428 [[source objectForKey:@"Distribution"] UTF8String]
8436 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8437 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8439 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8440 [tabbar_ presentModalViewController:navigation animated:YES];
8443 detachNewThreadSelector:@selector(update_)
8446 title:UCLocalize("UPDATING_SOURCES")
8450 - (void) reloadData {
8451 @synchronized (self) {
8457 pkgProblemResolver *resolver = [database_ resolver];
8459 resolver->InstallProtect();
8460 if (!resolver->Resolve(true))
8465 if (![database_ prepare])
8468 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8469 [page setDelegate:self];
8470 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8471 [confirm_ setDelegate:self];
8474 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8475 [tabbar_ presentModalViewController:confirm_ animated:YES];
8481 @synchronized (self) {
8486 - (void) clearPackage:(Package *)package {
8487 @synchronized (self) {
8494 - (void) installPackages:(NSArray *)packages {
8495 @synchronized (self) {
8496 for (Package *package in packages)
8503 - (void) installPackage:(Package *)package {
8504 @synchronized (self) {
8511 - (void) removePackage:(Package *)package {
8512 @synchronized (self) {
8519 - (void) distUpgrade {
8520 @synchronized (self) {
8521 if (![database_ upgrade])
8528 @synchronized (self) {
8533 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8536 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8538 if (navigation != nil) {
8539 [navigation pushViewController:progress animated:YES];
8541 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8543 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8544 [tabbar_ presentModalViewController:navigation animated:YES];
8548 detachNewThreadSelector:@selector(perform)
8551 title:UCLocalize("RUNNING")
8557 - (void) progressControllerIsComplete:(ProgressController *)progress {
8562 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8563 CYNavigationController *controller = (CYNavigationController *) viewController;
8565 if ([[controller viewControllers] count] == 0) {
8566 int index = [[tabbar_ viewControllers] indexOfObjectIdenticalTo:controller];
8567 CYViewController *root = nil;
8570 root = [[[HomeController alloc] init] autorelease];
8571 else if (index == 1)
8572 root = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
8573 else if (index == 2)
8574 root = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
8578 root = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8579 else if (index == 4)
8580 root = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8581 else if (index == 5)
8582 root = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8585 root = [[[ManageController alloc] init] autorelease];
8586 else if (index == 4)
8587 root = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8590 [root setDelegate:self];
8593 [controller setViewControllers:[NSArray arrayWithObject:root]];
8597 - (void) showSettings {
8598 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
8599 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8601 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8602 [tabbar_ presentModalViewController:nav animated:YES];
8605 - (void) retainNetworkActivityIndicator {
8606 if (activity_++ == 0)
8607 [self setNetworkActivityIndicatorVisible:YES];
8610 - (void) releaseNetworkActivityIndicator {
8611 if (--activity_ == 0)
8612 [self setNetworkActivityIndicatorVisible:NO];
8615 - (void) setPackageController:(CYPackageController *)view {
8617 [view setPackage:nil];
8621 - (void) cancelAndClear:(bool)clear {
8622 @synchronized (self) {
8634 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8635 NSString *context([alert context]);
8637 if ([context isEqualToString:@"fixhalf"]) {
8638 if (button == [alert firstOtherButtonIndex]) {
8639 @synchronized (self) {
8640 for (Package *broken in broken_) {
8643 NSString *id = [broken id];
8644 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8645 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8646 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8647 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8653 } else if (button == [alert cancelButtonIndex]) {
8654 [broken_ removeAllObjects];
8658 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8659 } else if ([context isEqualToString:@"upgrade"]) {
8660 if (button == [alert firstOtherButtonIndex]) {
8661 @synchronized (self) {
8662 for (Package *essential in essential_)
8663 [essential install];
8668 } else if (button == [alert firstOtherButtonIndex] + 1) {
8670 } else if (button == [alert cancelButtonIndex]) {
8674 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8678 - (void) system:(NSString *)command { _pooled
8680 system([command UTF8String]);
8684 - (void) applicationWillSuspend {
8686 [super applicationWillSuspend];
8689 - (BOOL) isSafeToSuspend {
8690 // Use external process status API internally.
8691 // This is probably a really bad idea.
8692 // XXX: what is the point of this? does this solve anything at all?
8693 uint64_t status = 0;
8695 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8696 notify_get_state(notify_token, &status);
8697 notify_cancel(notify_token);
8700 return locked_ == 0 && status == 0;
8703 - (void) applicationSuspend:(__GSEvent *)event {
8704 if ([self isSafeToSuspend])
8705 [super applicationSuspend:event];
8708 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8709 if ([self isSafeToSuspend])
8710 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8713 - (void) _setSuspended:(BOOL)value {
8714 if ([self isSafeToSuspend])
8715 [super _setSuspended:value];
8718 - (UIProgressHUD *) addProgressHUD {
8719 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8720 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8722 [window_ setUserInteractionEnabled:NO];
8725 UIViewController *target = tabbar_;
8726 while ([target modalViewController] != nil) target = [target modalViewController];
8727 [[target view] addSubview:hud];
8733 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8735 [hud removeFromSuperview];
8736 [window_ setUserInteractionEnabled:YES];
8740 - (CYViewController *) pageForPackage:(NSString *)name {
8741 if (Package *package = [database_ packageWithName:name]) {
8742 CYPackageController *view = [[[CYPackageController alloc] initWithDatabase:database_] autorelease];
8743 [view setPackage:package];
8746 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8747 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8748 CYBrowserController *browser = [[[CYBrowserController alloc] init] autorelease];
8749 [browser loadURL:url];
8754 - (CYViewController *) pageForURL:(NSURL *)url {
8755 NSString *scheme([[url scheme] lowercaseString]);
8756 if ([[url absoluteString] length] <= [scheme length] + 3)
8758 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
8759 NSArray *components([path pathComponents]);
8761 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
8762 return [self pageForPackage:[components objectAtIndex:1]];
8764 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
8767 NSString *base([components objectAtIndex:0]);
8769 CYViewController *controller = nil;
8771 if ([base isEqualToString:@"url"]) {
8772 // This kind of URL can contain slashes in the argument, so we can't parse them below.
8773 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
8774 controller = [[[CYBrowserController alloc] init] autorelease];
8775 [(CYBrowserController *)controller loadURL:[NSURL URLWithString:destination]];
8776 } else if ([components count] == 1) {
8777 if ([base isEqualToString:@"storage"]) {
8778 controller = [[[CYBrowserController alloc] init] autorelease];
8779 [(CYBrowserController *)controller loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]]];
8782 if ([base isEqualToString:@"sources"]) {
8783 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8786 if ([base isEqualToString:@"home"]) {
8787 controller = [[[HomeController alloc] init] autorelease];
8790 if ([base isEqualToString:@"sections"]) {
8791 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
8794 if ([base isEqualToString:@"search"]) {
8795 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8798 if ([base isEqualToString:@"changes"]) {
8799 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
8802 if ([base isEqualToString:@"installed"]) {
8803 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8805 } else if ([components count] == 2) {
8806 NSString *argument = [components objectAtIndex:1];
8808 if ([base isEqualToString:@"package"]) {
8809 controller = [self pageForPackage:argument];
8812 if ([base isEqualToString:@"search"]) {
8813 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8814 [(SearchController *)controller setSearchTerm:argument];
8817 if ([base isEqualToString:@"sections"]) {
8818 if ([argument isEqualToString:@"all"])
8820 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
8823 if ([base isEqualToString:@"sources"]) {
8824 if ([argument isEqualToString:@"add"]) {
8825 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8826 [(SourcesController *)controller showAddSourcePrompt];
8828 NSArray *sources = [database_ sources];
8829 for (Source *source in sources) {
8830 if ([[source name] caseInsensitiveCompare:argument] == NSOrderedSame) {
8831 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
8838 if ([base isEqualToString:@"launch"]) {
8839 [self launchApplicationWithIdentifier:argument suspended:NO];
8842 } else if ([components count] == 3) {
8843 NSString *arg1 = [components objectAtIndex:1];
8844 NSString *arg2 = [components objectAtIndex:2];
8846 if ([base isEqualToString:@"package"]) {
8847 if ([arg2 isEqualToString:@"settings"]) {
8848 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
8849 } else if ([arg2 isEqualToString:@"signature"]) {
8850 controller = [[[SignatureController alloc] initWithDatabase:database_ package:arg1] autorelease];
8851 } else if ([arg2 isEqualToString:@"files"]) {
8852 if (Package *package = [database_ packageWithName:arg1]) {
8853 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8854 [(FileTable *)controller setPackage:package];
8860 [controller setDelegate:self];
8864 - (BOOL) openCydiaURL:(NSURL *)url {
8865 CYViewController *page([self pageForURL:url]);
8868 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
8869 [nav setViewControllers:[NSArray arrayWithObject:page]];
8870 [tabbar_ setTransientViewController:nav];
8876 - (void) applicationOpenURL:(NSURL *)url {
8877 [super applicationOpenURL:url];
8879 if (!loaded_) starturl_ = [url retain];
8880 else [self openCydiaURL:url];
8883 - (void) applicationWillResignActive:(UIApplication *)application {
8884 // Stop refreshing if you get a phone call or lock the device.
8885 if ([tabbar_ updating])
8886 [tabbar_ cancelUpdate];
8888 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8889 [super applicationWillResignActive:application];
8892 - (void) addStashController {
8894 stash_ = [[StashController alloc] init];
8895 [window_ addSubview:[stash_ view]];
8898 - (void) removeStashController {
8899 [[stash_ view] removeFromSuperview];
8905 [self setIdleTimerDisabled:YES];
8907 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8908 [self setStatusBarShowsProgress:YES];
8909 UpdateExternalStatus(1);
8911 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8913 UpdateExternalStatus(0);
8914 [self setStatusBarShowsProgress:NO];
8916 [self removeStashController];
8918 if (ExecFork() == 0) {
8919 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8920 perror("launchctl stop");
8924 - (void) setupViewControllers {
8925 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8926 [tabbar_ setDelegate:self];
8928 NSMutableArray *items([NSMutableArray arrayWithObjects:
8929 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
8930 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
8931 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
8932 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
8936 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
8937 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
8939 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
8942 NSMutableArray *controllers([NSMutableArray array]);
8943 for (UITabBarItem *item in items) {
8944 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8945 [controller setTabBarItem:item];
8946 [controllers addObject:controller];
8948 [tabbar_ setViewControllers:controllers];
8950 [tabbar_ setUpdateDelegate:self];
8953 - (CYEmulatedLoadingController *)showEmulatedLoadingControllerInView:(UIView *)view {
8954 static CYEmulatedLoadingController *fake = [[CYEmulatedLoadingController alloc] init];
8956 [view addSubview:[fake view]];
8958 [[fake view] removeFromSuperview];
8964 - (void) applicationDidFinishLaunching:(id)unused {
8968 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
8969 [self setApplicationSupportsShakeToEdit:NO];
8971 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
8972 initWithMemoryCapacity:524288
8973 diskCapacity:10485760
8974 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
8977 [CYBrowserController _initialize];
8979 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8981 Font12_ = [[UIFont systemFontOfSize:12] retain];
8982 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8983 Font14_ = [[UIFont systemFontOfSize:14] retain];
8984 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8985 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8987 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8988 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8990 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
8991 [window_ orderFront:self];
8992 [window_ makeKey:self];
8993 [window_ setHidden:NO];
8996 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8997 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8998 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8999 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9000 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9001 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9002 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9003 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9004 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9007 [self addStashController];
9008 // XXX: this would be much cleaner as a yieldToSelector:
9009 // that way the removeStashController could happen right here inline
9010 // we also could no longer require the useless stash_ field anymore
9011 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9015 database_ = [Database sharedInstance];
9017 [window_ setUserInteractionEnabled:NO];
9018 [self setupViewControllers];
9019 [self showEmulatedLoadingControllerInView:window_];
9021 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9028 [window_ setUserInteractionEnabled:YES];
9030 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9031 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9033 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9034 [[self showEmulatedLoadingControllerInView:window_] presentModalViewController:nav animated:YES];
9038 if ([[self showEmulatedLoadingControllerInView:window_] modalViewController] != nil)
9039 [[self showEmulatedLoadingControllerInView:window_] dismissModalViewControllerAnimated:YES];
9040 [window_ setUserInteractionEnabled:NO];
9046 [window_ addSubview:[tabbar_ view]];
9047 [self showEmulatedLoadingControllerInView:nil];
9048 [window_ setUserInteractionEnabled:YES];
9050 // Show the home page.
9051 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:0];
9052 [navigation setViewControllers:[NSArray arrayWithObject:[self pageForURL:[NSURL URLWithString:@"cydia://home"]]]];
9054 // (Try to) show the startup URL.
9055 if (starturl_ != nil) {
9056 [self openCydiaURL:starturl_];
9057 [starturl_ release];
9062 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9063 if (item != nil && IsWildcat_) {
9064 [sheet showFromBarButtonItem:item animated:YES];
9066 [sheet showInView:window_];
9073 id Alloc_(id self, SEL selector) {
9074 id object = alloc_(self, selector);
9075 lprintf("[%s]A-%p\n", self->isa->name, object);
9080 id Dealloc_(id self, SEL selector) {
9081 id object = dealloc_(self, selector);
9082 lprintf("[%s]D-%p\n", self->isa->name, object);
9086 Class $WebDefaultUIKitDelegate;
9088 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9089 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9090 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9091 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9094 static NSNumber *shouldPlayKeyboardSounds;
9098 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9100 case 1104: // Keyboard Button Clicked
9101 case 1105: // Keyboard Delete Repeated
9102 if (shouldPlayKeyboardSounds == nil) {
9103 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9104 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9107 if (![shouldPlayKeyboardSounds boolValue])
9111 _UIHardware$_playSystemSound$(self, _cmd, sound);
9115 Class $UIApplication;
9117 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9118 static BOOL initialized = NO;
9119 static BOOL started = NO;
9121 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9122 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9124 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9125 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9126 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9127 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9129 if (initialized && !enabled) {
9131 [bundle performSelector:@selector(_accessibilityStopServer)];
9132 } else if (enabled) {
9136 [bundle performSelector:@selector(_accessibilityStartServer)];
9142 int main(int argc, char *argv[]) { _pooled
9145 if (Class $UIDevice = objc_getClass("UIDevice")) {
9146 UIDevice *device([$UIDevice currentDevice]);
9147 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9151 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9153 /* Library Hacks {{{ */
9154 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9156 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9157 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9158 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9159 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9160 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9163 $UIHardware = objc_getClass("UIHardware");
9164 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9165 if (UIHardware$_playSystemSound$ != NULL) {
9166 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9167 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9170 $UIApplication = objc_getClass("UIApplication");
9171 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9172 if (UIApplication$_updateApplicationAccessibility != NULL) {
9173 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9174 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9177 /* Set Locale {{{ */
9178 Locale_ = CFLocaleCopyCurrent();
9179 Languages_ = [NSLocale preferredLanguages];
9180 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9181 //NSLog(@"%@", [Languages_ description]);
9184 if (Languages_ == nil || [Languages_ count] == 0)
9185 // XXX: consider just setting to C and then falling through?
9188 lang = [[Languages_ objectAtIndex:0] UTF8String];
9189 setenv("LANG", lang, true);
9192 //std::setlocale(LC_ALL, lang);
9193 NSLog(@"Setting Language: %s", lang);
9196 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9198 /* Parse Arguments {{{ */
9199 bool substrate(false);
9205 for (int argi(1); argi != argc; ++argi)
9206 if (strcmp(argv[argi], "--") == 0) {
9208 argv[argi] = argv[0];
9214 for (int argi(1); argi != arge; ++argi)
9215 if (strcmp(args[argi], "--substrate") == 0)
9218 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9222 App_ = [[NSBundle mainBundle] bundlePath];
9223 Home_ = NSHomeDirectory();
9229 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9230 alloc_ = alloc->method_imp;
9231 alloc->method_imp = (IMP) &Alloc_;*/
9233 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9234 dealloc_ = dealloc->method_imp;
9235 dealloc->method_imp = (IMP) &Dealloc_;*/
9237 /* System Information {{{ */
9241 size = sizeof(maxproc);
9242 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9243 perror("sysctlbyname(\"kern.maxproc\", ?)");
9244 else if (maxproc < 64) {
9246 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9247 perror("sysctlbyname(\"kern.maxproc\", #)");
9250 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9251 char *osversion = new char[size];
9252 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9253 perror("sysctlbyname(\"kern.osversion\", ?)");
9255 System_ = [NSString stringWithUTF8String:osversion];
9257 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9258 char *machine = new char[size];
9259 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9260 perror("sysctlbyname(\"hw.machine\", ?)");
9264 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9265 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9266 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9267 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9271 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9272 NSData *data((NSData *) ecid);
9273 size_t length([data length]);
9274 uint8_t bytes[length];
9275 [data getBytes:bytes];
9276 char string[length * 2 + 1];
9277 for (size_t i(0); i != length; ++i)
9278 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9279 ChipID_ = [NSString stringWithUTF8String:string];
9283 IOObjectRelease(service);
9287 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9289 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9290 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9291 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9293 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9294 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9295 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9297 if (mcc != NULL && mnc != NULL)
9298 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9305 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9306 Build_ = [system objectForKey:@"ProductBuildVersion"];
9307 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9308 Product_ = [info objectForKey:@"SafariProductVersion"];
9309 Safari_ = [info objectForKey:@"CFBundleVersion"];
9312 /* Load Database {{{ */
9314 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9316 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9318 if (Metadata_ == NULL)
9319 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9321 Settings_ = [Metadata_ objectForKey:@"Settings"];
9323 Packages_ = [Metadata_ objectForKey:@"Packages"];
9324 Sections_ = [Metadata_ objectForKey:@"Sections"];
9325 Sources_ = [Metadata_ objectForKey:@"Sources"];
9327 Token_ = [Metadata_ objectForKey:@"Token"];
9330 if (Settings_ != nil)
9331 Role_ = [Settings_ objectForKey:@"Role"];
9333 if (Sections_ == nil) {
9334 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9335 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9338 if (Sources_ == nil) {
9339 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9340 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9345 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9348 if (Packages_ != nil) {
9349 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
9351 [Metadata_ removeObjectForKey:@"Packages"];
9356 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9358 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9359 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9360 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9361 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9362 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9363 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9365 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9367 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9368 unlink("/tmp/.cydia.fw");
9370 } else if (access("/User", F_OK) != 0 || version < 2) {
9373 system("/usr/libexec/cydia/firmware.sh");
9377 _assert([[NSFileManager defaultManager]
9378 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9379 withIntermediateDirectories:YES
9384 if (access("/tmp/cydia.chk", F_OK) == 0) {
9385 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9386 _assert(errno == ENOENT);
9387 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9388 _assert(errno == ENOENT);
9391 /* APT Initialization {{{ */
9392 _assert(pkgInitConfig(*_config));
9393 _assert(pkgInitSystem(*_config, _system));
9396 _config->Set("APT::Acquire::Translation", lang);
9398 // XXX: this timeout might be important :(
9399 //_config->Set("Acquire::http::Timeout", 15);
9401 _config->Set("Acquire::http::MaxParallel", 3);
9403 /* Color Choices {{{ */
9404 space_ = CGColorSpaceCreateDeviceRGB();
9406 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9407 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9408 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9409 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9410 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9411 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9412 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9413 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9414 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9416 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9417 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9419 /* UIKit Configuration {{{ */
9420 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9421 if ($GSFontSetUseLegacyFontMetrics != NULL)
9422 $GSFontSetUseLegacyFontMetrics(YES);
9424 // XXX: I have a feeling this was important
9425 //UIKeyboardDisableAutomaticAppearance();
9428 Colon_ = UCLocalize("COLON_DELIMITED");
9429 Elision_ = UCLocalize("ELISION");
9430 Error_ = UCLocalize("ERROR");
9431 Warning_ = UCLocalize("WARNING");
9434 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9436 CGColorSpaceRelease(space_);