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>
111 #include <mach-o/nlist.h>
121 #include "UICaboodle/BrowserView.h"
123 #include "substrate.h"
130 #define _timestamp ({ \
132 gettimeofday(&tv, NULL); \
133 tv.tv_sec * 1000000 + tv.tv_usec; \
136 typedef std::vector<class ProfileTime *> TimeList;
146 ProfileTime(const char *name) :
150 times_.push_back(this);
153 void AddTime(uint64_t time) {
160 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
172 ProfileTimer(ProfileTime &time) :
179 time_.AddTime(_timestamp - start_);
184 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
186 std::cerr << "========" << std::endl;
189 #define _profile(name) { \
190 static ProfileTime name(#name); \
191 ProfileTimer _ ## name(name);
196 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
198 #define CYPoolStart() \
199 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
201 #define CYPoolEnd() \
205 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
207 void NSLogPoint(const char *fix, const CGPoint &point) {
208 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
211 void NSLogRect(const char *fix, const CGRect &rect) {
212 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
215 static _finline NSString *CydiaURL(NSString *path) {
217 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
218 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
219 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
220 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
221 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
222 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
225 static _finline void UpdateExternalStatus(uint64_t newStatus) {
227 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
228 notify_set_state(notify_token, newStatus);
229 notify_cancel(notify_token);
231 notify_post("com.saurik.Cydia.status");
234 /* [NSObject yieldToSelector:(withObject:)] {{{*/
235 @interface NSObject (Cydia)
236 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
237 - (id) yieldToSelector:(SEL)selector;
240 @implementation NSObject (Cydia)
245 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
246 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
247 id object([[context objectAtIndex:1] nonretainedObjectValue]);
248 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
250 /* XXX: deal with exceptions */
251 id value([self performSelector:selector withObject:object]);
253 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
254 [context removeAllObjects];
255 if ([signature methodReturnLength] != 0 && value != nil)
256 [context addObject:value];
261 performSelectorOnMainThread:@selector(doNothing)
267 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
268 /*return [self performSelector:selector withObject:object];*/
270 volatile bool stopped(false);
272 NSMutableArray *context([NSMutableArray arrayWithObjects:
273 [NSValue valueWithPointer:selector],
274 [NSValue valueWithNonretainedObject:object],
275 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
278 NSThread *thread([[[NSThread alloc]
280 selector:@selector(_yieldToContext:)
286 NSRunLoop *loop([NSRunLoop currentRunLoop]);
287 NSDate *future([NSDate distantFuture]);
289 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
291 return [context count] == 0 ? nil : [context objectAtIndex:0];
294 - (id) yieldToSelector:(SEL)selector {
295 return [self yieldToSelector:selector withObject:nil];
301 /* Cydia Action Sheet {{{ */
302 @interface CYActionSheet : UIAlertView {
306 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
309 @implementation CYActionSheet
311 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
312 if ((self = [super init])) {
313 [self setTitle:title];
314 [self setDelegate:self];
315 for (NSString *button in buttons) [self addButtonWithTitle:button];
316 [self setCancelButtonIndex:index];
320 - (void) _updateFrameForDisplay {
321 [super _updateFrameForDisplay];
322 if ([self cancelButtonIndex] == -1) {
323 NSArray *buttons = [self buttons];
324 if ([buttons count]) {
325 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
326 for (UIThreePartButton *button in buttons)
327 [button setBackground:background forState:0];
332 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
333 button_ = buttonIndex + 1;
337 [self dismissWithClickedButtonIndex:-1 animated:YES];
340 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
341 [self setRunsModal:YES];
350 /* NSForcedOrderingSearch doesn't work on the iPhone */
351 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
352 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
353 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
355 /* Information Dictionaries {{{ */
356 @interface NSMutableArray (Cydia)
357 - (void) addInfoDictionary:(NSDictionary *)info;
360 @implementation NSMutableArray (Cydia)
362 - (void) addInfoDictionary:(NSDictionary *)info {
363 [self addObject:info];
368 @interface NSMutableDictionary (Cydia)
369 - (void) addInfoDictionary:(NSDictionary *)info;
372 @implementation NSMutableDictionary (Cydia)
374 - (void) addInfoDictionary:(NSDictionary *)info {
375 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
381 #define lprintf(args...) fprintf(stderr, args)
384 #define TraceLogging (1 && !ForRelease)
385 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
386 #define ProfileTimes (0 && !ForRelease)
387 #define ForSaurik (0 && !ForRelease)
388 #define LogBrowser (0 && !ForRelease)
389 #define TrackResize (0 && !ForRelease)
390 #define ManualRefresh (1 && !ForRelease)
391 #define ShowInternals (0 && !ForRelease)
392 #define IgnoreInstall (0 && !ForRelease)
393 #define AlwaysReload (0 && !ForRelease)
397 #define _trace(args...)
402 #define _profile(name) {
405 #define PrintTimes() do {} while (false)
409 typedef uint32_t (*SKRadixFunction)(id, void *);
411 @interface NSMutableArray (Radix)
412 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
420 @implementation NSMutableArray (Radix)
422 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
423 size_t count([self count]);
424 struct RadixItem_ *swap(new RadixItem_[count * 2]);
426 for (size_t i(0); i != count; ++i) {
427 RadixItem_ &item(swap[i]);
430 id object([self objectAtIndex:i]);
431 item.key = function(object, argument);
434 struct RadixItem_ *lhs(swap), *rhs(swap + count);
436 static const size_t width = 32;
437 static const size_t bits = 11;
438 static const size_t slots = 1 << bits;
439 static const size_t passes = (width + (bits - 1)) / bits;
441 size_t *hist(new size_t[slots]);
443 for (size_t pass(0); pass != passes; ++pass) {
444 memset(hist, 0, sizeof(size_t) * slots);
446 for (size_t i(0); i != count; ++i) {
447 uint32_t key(lhs[i].key);
449 key &= _not(uint32_t) >> width - bits;
454 for (size_t i(0); i != slots; ++i) {
455 size_t local(offset);
460 for (size_t i(0); i != count; ++i) {
461 uint32_t key(lhs[i].key);
463 key &= _not(uint32_t) >> width - bits;
464 rhs[hist[key]++] = lhs[i];
467 RadixItem_ *tmp(lhs);
474 const void **values(new const void *[count]);
475 for (size_t i(0); i != count; ++i)
476 values[i] = [self objectAtIndex:lhs[i].index];
477 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
485 /* Insertion Sort {{{ */
487 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
488 const char *ptr = (const char *)list;
490 CFIndex half = count / 2;
491 const char *probe = ptr + elementSize * half;
492 CFComparisonResult cr = comparator(element, probe, context);
493 if (0 == cr) return (probe - (const char *)list) / elementSize;
494 ptr = (cr < 0) ? ptr : probe + elementSize;
495 count = (cr < 0) ? half : (half + (count & 1) - 1);
497 return (ptr - (const char *)list) / elementSize;
500 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
501 const char *ptr = (const char *)list;
503 CFIndex half = count / 2;
504 const char *probe = ptr + elementSize * half;
505 CFComparisonResult cr = comparator(element, probe, context);
506 if (0 == cr) return (probe - (const char *)list) / elementSize;
507 ptr = (cr < 0) ? ptr : probe + elementSize;
508 count = (cr < 0) ? half : (half + (count & 1) - 1);
510 return (ptr - (const char *)list) / elementSize;
513 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
514 if (range.length == 0)
516 const void **values(new const void *[range.length]);
517 CFArrayGetValues(array, range, values);
519 #if HistogramInsertionSort > 0
520 uint32_t total(0), *offsets(new uint32_t[range.length]);
523 for (CFIndex index(1); index != range.length; ++index) {
524 const void *value(values[index]);
525 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
526 CFIndex correct(index);
527 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
528 #if HistogramInsertionSort > 1
529 NSLog(@"%@ < %@", value, values[correct - 1]);
534 if (correct != index) {
535 size_t offset(index - correct);
536 #if HistogramInsertionSort
540 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
542 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
543 values[correct] = value;
547 CFArrayReplaceValues(array, range, values, range.length);
550 #if HistogramInsertionSort > 0
551 for (CFIndex index(0); index != range.length; ++index)
552 if (offsets[index] != 0)
553 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
554 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
561 /* Apple Bug Fixes {{{ */
562 @implementation UIWebDocumentView (Cydia)
564 - (void) _setScrollerOffset:(CGPoint)offset {
565 UIScroller *scroller([self _scroller]);
567 CGSize size([scroller contentSize]);
568 CGSize bounds([scroller bounds].size);
571 max.x = size.width - bounds.width;
572 max.y = size.height - bounds.height;
580 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
581 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
583 [scroller setOffset:offset];
589 @implementation WebScriptObject (NSFastEnumeration)
591 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
592 size_t length([self count] - state->state);
595 else if (length > count)
597 for (size_t i(0); i != length; ++i)
598 objects[i] = [self objectAtIndex:state->state++];
599 state->itemsPtr = objects;
600 state->mutationsPtr = (unsigned long *) self;
606 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
607 size_t length([self length] - state->state);
610 else if (length > count)
612 for (size_t i(0); i != length; ++i)
613 objects[i] = [self item:state->state++];
614 state->itemsPtr = objects;
615 state->mutationsPtr = (unsigned long *) self;
619 /* Cydia NSString Additions {{{ */
620 @interface NSString (Cydia)
621 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
622 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
623 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
624 - (NSComparisonResult) compareByPath:(NSString *)other;
625 - (NSString *) stringByCachingURLWithCurrentCDN;
626 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
629 @implementation NSString (Cydia)
631 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
632 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
635 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
636 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
637 memcpy(data, bytes, length);
638 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
641 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
642 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
645 - (NSComparisonResult) compareByPath:(NSString *)other {
646 NSString *prefix = [self commonPrefixWithString:other options:0];
647 size_t length = [prefix length];
649 NSRange lrange = NSMakeRange(length, [self length] - length);
650 NSRange rrange = NSMakeRange(length, [other length] - length);
652 lrange = [self rangeOfString:@"/" options:0 range:lrange];
653 rrange = [other rangeOfString:@"/" options:0 range:rrange];
655 NSComparisonResult value;
657 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
658 value = NSOrderedSame;
659 else if (lrange.location == NSNotFound)
660 value = NSOrderedAscending;
661 else if (rrange.location == NSNotFound)
662 value = NSOrderedDescending;
664 value = NSOrderedSame;
666 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
667 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
668 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
669 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
671 NSComparisonResult result = [lpath compare:rpath];
672 return result == NSOrderedSame ? value : result;
675 - (NSString *) stringByCachingURLWithCurrentCDN {
677 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
678 withString:@"://cache.cydia.saurik.com/"
682 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
683 return [(id)CFURLCreateStringByAddingPercentEscapes(
688 kCFStringEncodingUTF8
695 /* C++ NSString Wrapper Cache {{{ */
696 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
697 return size == 0 ? NULL :
698 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
699 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
702 static _finline CFStringRef CYStringCreate(const char *data) {
703 return CYStringCreate(data, strlen(data));
712 _finline void clear_() {
713 if (cache_ != NULL) {
720 _finline bool empty() const {
724 _finline size_t size() const {
728 _finline char *data() const {
732 _finline void clear() {
737 _finline CYString() :
744 _finline ~CYString() {
748 void operator =(const CYString &rhs) {
752 if (rhs.cache_ == nil)
755 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
758 void set(apr_pool_t *pool, const char *data, size_t size) {
764 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
765 memcpy(temp, data, size);
772 _finline void set(apr_pool_t *pool, const char *data) {
773 set(pool, data, data == NULL ? 0 : strlen(data));
776 _finline void set(apr_pool_t *pool, const std::string &rhs) {
777 set(pool, rhs.data(), rhs.size());
780 bool operator ==(const CYString &rhs) const {
781 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
784 _finline operator CFStringRef() {
786 cache_ = CYStringCreate(data_, size_);
790 _finline operator id() {
791 return (NSString *) static_cast<CFStringRef>(*this);
795 /* C++ NSString Algorithm Adapters {{{ */
797 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
800 struct NSStringMapHash :
801 std::unary_function<NSString *, size_t>
803 _finline size_t operator ()(NSString *value) const {
804 return CFStringHashNSString((CFStringRef) value);
808 struct NSStringMapLess :
809 std::binary_function<NSString *, NSString *, bool>
811 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
812 return [lhs compare:rhs] == NSOrderedAscending;
816 struct NSStringMapEqual :
817 std::binary_function<NSString *, NSString *, bool>
819 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
820 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
821 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
822 //[lhs isEqualToString:rhs];
827 /* Perl-Compatible RegEx {{{ */
837 Pcre(const char *regex) :
842 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
845 lprintf("%d:%s\n", offset, error);
849 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
850 matches_ = new int[(capture_ + 1) * 3];
858 NSString *operator [](size_t match) {
859 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
862 bool operator ()(NSString *data) {
863 // XXX: length is for characters, not for bytes
864 return operator ()([data UTF8String], [data length]);
867 bool operator ()(const char *data, size_t size) {
869 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
873 /* Mime Addresses {{{ */
874 @interface Address : NSObject {
880 - (NSString *) address;
882 - (void) setAddress:(NSString *)address;
884 + (Address *) addressWithString:(NSString *)string;
885 - (Address *) initWithString:(NSString *)string;
888 @implementation Address
897 - (NSString *) name {
901 - (NSString *) address {
905 - (void) setAddress:(NSString *)address {
907 [address_ autorelease];
911 address_ = [address retain];
914 + (Address *) addressWithString:(NSString *)string {
915 return [[[Address alloc] initWithString:string] autorelease];
918 + (NSArray *) _attributeKeys {
919 return [NSArray arrayWithObjects:@"address", @"name", nil];
922 - (NSArray *) attributeKeys {
923 return [[self class] _attributeKeys];
926 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
927 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
930 - (Address *) initWithString:(NSString *)string {
931 if ((self = [super init]) != nil) {
932 const char *data = [string UTF8String];
933 size_t size = [string length];
935 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
937 if (address_r(data, size)) {
938 name_ = [address_r[1] retain];
939 address_ = [address_r[2] retain];
941 name_ = [string retain];
949 /* CoreGraphics Primitives {{{ */
954 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
955 CGFloat color[] = {red, green, blue, alpha};
956 return CGColorCreate(space, color);
965 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
966 color_(Create_(space, red, green, blue, alpha))
968 Set(space, red, green, blue, alpha);
973 CGColorRelease(color_);
980 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
982 color_ = Create_(space, red, green, blue, alpha);
985 operator CGColorRef() {
991 /* Random Global Variables {{{ */
992 static const int PulseInterval_ = 50000;
993 static const int ButtonBarWidth_ = 60;
994 static const int ButtonBarHeight_ = 48;
995 static const float KeyboardTime_ = 0.3f;
998 static NSArray *Finishes_;
1000 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1001 #define NotifyConfig_ "/etc/notify.conf"
1003 static bool Queuing_;
1005 static CYColor Blue_;
1006 static CYColor Blueish_;
1007 static CYColor Black_;
1008 static CYColor Off_;
1009 static CYColor White_;
1010 static CYColor Gray_;
1011 static CYColor Green_;
1012 static CYColor Purple_;
1013 static CYColor Purplish_;
1015 static UIColor *InstallingColor_;
1016 static UIColor *RemovingColor_;
1018 static NSString *App_;
1019 static NSString *Home_;
1021 static BOOL Advanced_;
1022 static BOOL Ignored_;
1024 static UIFont *Font12_;
1025 static UIFont *Font12Bold_;
1026 static UIFont *Font14_;
1027 static UIFont *Font18Bold_;
1028 static UIFont *Font22Bold_;
1030 static const char *Machine_ = NULL;
1031 static NSString *System_ = nil;
1032 static NSString *SerialNumber_ = nil;
1033 static NSString *ChipID_ = nil;
1034 static NSString *Token_ = nil;
1035 static NSString *UniqueID_ = nil;
1036 static NSString *PLMN_ = nil;
1037 static NSString *Build_ = nil;
1038 static NSString *Product_ = nil;
1039 static NSString *Safari_ = nil;
1041 static CFLocaleRef Locale_;
1042 static NSArray *Languages_;
1043 static CGColorSpaceRef space_;
1045 static NSDictionary *SectionMap_;
1046 static NSMutableDictionary *Metadata_;
1047 static _transient NSMutableDictionary *Settings_;
1048 static _transient NSString *Role_;
1049 static _transient NSMutableDictionary *Packages_;
1050 static _transient NSMutableDictionary *Sections_;
1051 static _transient NSMutableDictionary *Sources_;
1052 static bool Changed_;
1053 static NSDate *now_;
1055 static bool IsWildcat_;
1058 /* Display Helpers {{{ */
1059 inline float Interpolate(float begin, float end, float fraction) {
1060 return (end - begin) * fraction + begin;
1063 /* XXX: localize this! */
1064 NSString *SizeString(double size) {
1065 bool negative = size < 0;
1070 while (size > 1024) {
1075 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1077 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1080 static _finline const char *StripVersion_(const char *version) {
1081 const char *colon(strchr(version, ':'));
1083 version = colon + 1;
1087 NSString *LocalizeSection(NSString *section) {
1088 static Pcre title_r("^(.*?) \\((.*)\\)$");
1089 if (title_r(section)) {
1090 NSString *parent(title_r[1]);
1091 NSString *child(title_r[2]);
1093 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1094 LocalizeSection(parent),
1095 LocalizeSection(child)
1099 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1102 NSString *Simplify(NSString *title) {
1103 const char *data = [title UTF8String];
1104 size_t size = [title length];
1106 static Pcre square_r("^\\[(.*)\\]$");
1107 if (square_r(data, size))
1108 return Simplify(square_r[1]);
1110 static Pcre paren_r("^\\((.*)\\)$");
1111 if (paren_r(data, size))
1112 return Simplify(paren_r[1]);
1114 static Pcre title_r("^(.*?) \\((.*)\\)$");
1115 if (title_r(data, size))
1116 return Simplify(title_r[1]);
1122 NSString *GetLastUpdate() {
1123 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1126 return UCLocalize("NEVER_OR_UNKNOWN");
1128 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1129 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1131 CFRelease(formatter);
1133 return [(NSString *) formatted autorelease];
1136 bool isSectionVisible(NSString *section) {
1137 NSDictionary *metadata([Sections_ objectForKey:section]);
1138 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1139 return hidden == nil || ![hidden boolValue];
1144 /* Delegate Prototypes {{{ */
1148 @interface NSObject (ProgressDelegate)
1151 @protocol ProgressDelegate
1152 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1153 - (void) setProgressTitle:(NSString *)title;
1154 - (void) setProgressPercent:(float)percent;
1155 - (void) startProgress;
1156 - (void) addProgressOutput:(NSString *)output;
1157 - (bool) isCancelling:(size_t)received;
1160 @protocol ConfigurationDelegate
1161 - (void) repairWithSelector:(SEL)selector;
1162 - (void) setConfigurationData:(NSString *)data;
1165 @class PackageController;
1167 @protocol CydiaDelegate
1168 - (void) setPackageController:(PackageController *)view;
1169 - (void) clearPackage:(Package *)package;
1170 - (void) installPackage:(Package *)package;
1171 - (void) installPackages:(NSArray *)packages;
1172 - (void) removePackage:(Package *)package;
1173 - (void) beginUpdate;
1175 - (void) distUpgrade;
1177 - (void) updateData;
1179 - (void) showSettings;
1180 - (UIProgressHUD *) addProgressHUD;
1181 - (BOOL) hudIsShowing;
1182 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1183 - (CYViewController *) pageForPackage:(NSString *)name;
1184 - (PackageController *) packageController;
1185 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1189 /* Status Delegation {{{ */
1191 public pkgAcquireStatus
1194 _transient NSObject<ProgressDelegate> *delegate_;
1202 void setDelegate(id delegate) {
1203 delegate_ = delegate;
1206 NSObject<ProgressDelegate> *getDelegate() const {
1210 virtual bool MediaChange(std::string media, std::string drive) {
1214 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1217 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1218 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1219 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1222 virtual void Done(pkgAcquire::ItemDesc &item) {
1225 virtual void Fail(pkgAcquire::ItemDesc &item) {
1227 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1228 item.Owner->Status == pkgAcquire::Item::StatDone
1232 std::string &error(item.Owner->ErrorText);
1236 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1237 NSArray *fields([description componentsSeparatedByString:@" "]);
1238 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1240 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1241 withObject:[NSArray arrayWithObjects:
1242 [NSString stringWithUTF8String:error.c_str()],
1249 virtual bool Pulse(pkgAcquire *Owner) {
1250 bool value = pkgAcquireStatus::Pulse(Owner);
1253 double(CurrentBytes + CurrentItems) /
1254 double(TotalBytes + TotalItems)
1257 [delegate_ setProgressPercent:percent];
1258 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1261 virtual void Start() {
1262 [delegate_ startProgress];
1265 virtual void Stop() {
1269 /* Progress Delegation {{{ */
1274 _transient id<ProgressDelegate> delegate_;
1278 virtual void Update() {
1279 /*if (abs(Percent - percent_) > 2)
1280 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1284 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1285 [delegate_ setProgressPercent:(Percent / 100)];*/
1295 void setDelegate(id delegate) {
1296 delegate_ = delegate;
1299 id getDelegate() const {
1303 virtual void Done() {
1305 //[delegate_ setProgressPercent:1];
1310 /* Database Interface {{{ */
1311 typedef std::map< unsigned long, _H<Source> > SourceMap;
1313 @interface Database : NSObject {
1319 pkgCacheFile cache_;
1320 pkgDepCache::Policy *policy_;
1321 pkgRecords *records_;
1322 pkgProblemResolver *resolver_;
1323 pkgAcquire *fetcher_;
1325 SPtr<pkgPackageManager> manager_;
1326 pkgSourceList *list_;
1329 CFMutableArrayRef packages_;
1331 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1340 + (Database *) sharedInstance;
1343 - (void) _readCydia:(NSNumber *)fd;
1344 - (void) _readStatus:(NSNumber *)fd;
1345 - (void) _readOutput:(NSNumber *)fd;
1349 - (Package *) packageWithName:(NSString *)name;
1351 - (pkgCacheFile &) cache;
1352 - (pkgDepCache::Policy *) policy;
1353 - (pkgRecords *) records;
1354 - (pkgProblemResolver *) resolver;
1355 - (pkgAcquire &) fetcher;
1356 - (pkgSourceList &) list;
1357 - (NSArray *) packages;
1358 - (NSArray *) sources;
1359 - (void) reloadData;
1367 - (void) updateWithStatus:(Status &)status;
1369 - (void) setDelegate:(id)delegate;
1370 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1373 /* Delegate Helpers {{{ */
1374 @implementation NSObject (ProgressDelegate)
1376 - (void) _setProgressErrorPackage:(NSArray *)args {
1377 [self performSelector:@selector(setProgressError:forPackage:)
1378 withObject:[args objectAtIndex:0]
1379 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1383 - (void) _setProgressErrorTitle:(NSArray *)args {
1384 [self performSelector:@selector(setProgressError:withTitle:)
1385 withObject:[args objectAtIndex:0]
1386 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1390 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1391 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1392 withObject:[NSArray arrayWithObjects:error, title, nil]
1397 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1398 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1400 [self performSelector:@selector(setProgressError:withTitle:)
1402 withObject:(package == nil ? id : [package name])
1409 /* Source Class {{{ */
1410 @interface Source : NSObject {
1411 CYString depiction_;
1412 CYString description_;
1418 CYString distribution_;
1423 NSString *authority_;
1425 CYString defaultIcon_;
1427 NSDictionary *record_;
1431 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1433 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1435 - (NSString *) depictionForPackage:(NSString *)package;
1436 - (NSString *) supportForPackage:(NSString *)package;
1438 - (NSDictionary *) record;
1442 - (NSString *) distribution;
1443 - (NSString *) type;
1445 - (NSString *) host;
1447 - (NSString *) name;
1448 - (NSString *) description;
1449 - (NSString *) label;
1450 - (NSString *) origin;
1451 - (NSString *) version;
1453 - (NSString *) defaultIcon;
1457 @implementation Source
1461 distribution_.clear();
1464 description_.clear();
1470 defaultIcon_.clear();
1472 if (record_ != nil) {
1482 if (authority_ != nil) {
1483 [authority_ release];
1489 // XXX: this is a very inefficient way to call these deconstructors
1494 + (NSArray *) _attributeKeys {
1495 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1498 - (NSArray *) attributeKeys {
1499 return [[self class] _attributeKeys];
1502 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1503 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1506 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1509 trusted_ = index->IsTrusted();
1511 uri_.set(pool, index->GetURI());
1512 distribution_.set(pool, index->GetDist());
1513 type_.set(pool, index->GetType());
1515 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1516 if (dindex != NULL) {
1518 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1521 pkgTagFile tags(&fd);
1523 pkgTagSection section;
1530 {"default-icon", &defaultIcon_},
1531 {"depiction", &depiction_},
1532 {"description", &description_},
1534 {"origin", &origin_},
1535 {"support", &support_},
1536 {"version", &version_},
1539 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1540 const char *start, *end;
1542 if (section.Find(names[i].name_, start, end)) {
1543 CYString &value(*names[i].value_);
1544 value.set(pool, start, end - start);
1550 record_ = [Sources_ objectForKey:[self key]];
1552 record_ = [record_ retain];
1554 NSURL *url([NSURL URLWithString:uri_]);
1558 host_ = [[host_ lowercaseString] retain];
1563 authority_ = [url path];
1565 if (authority_ != nil)
1566 authority_ = [authority_ retain];
1569 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1570 if ((self = [super init]) != nil) {
1571 [self setMetaIndex:index inPool:pool];
1575 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1576 NSDictionary *lhr = [self record];
1577 NSDictionary *rhr = [source record];
1580 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1582 NSString *lhs = [self name];
1583 NSString *rhs = [source name];
1585 if ([lhs length] != 0 && [rhs length] != 0) {
1586 unichar lhc = [lhs characterAtIndex:0];
1587 unichar rhc = [rhs characterAtIndex:0];
1589 if (isalpha(lhc) && !isalpha(rhc))
1590 return NSOrderedAscending;
1591 else if (!isalpha(lhc) && isalpha(rhc))
1592 return NSOrderedDescending;
1595 return [lhs compare:rhs options:LaxCompareOptions_];
1598 - (NSString *) depictionForPackage:(NSString *)package {
1599 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1602 - (NSString *) supportForPackage:(NSString *)package {
1603 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1606 - (NSDictionary *) record {
1614 - (NSString *) uri {
1618 - (NSString *) distribution {
1619 return distribution_;
1622 - (NSString *) type {
1626 - (NSString *) key {
1627 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1630 - (NSString *) host {
1634 - (NSString *) name {
1635 return origin_.empty() ? authority_ : origin_;
1638 - (NSString *) description {
1639 return description_;
1642 - (NSString *) label {
1643 return label_.empty() ? authority_ : label_;
1646 - (NSString *) origin {
1650 - (NSString *) version {
1654 - (NSString *) defaultIcon {
1655 return defaultIcon_;
1660 /* Relationship Class {{{ */
1661 @interface Relationship : NSObject {
1666 - (NSString *) type;
1668 - (NSString *) name;
1672 @implementation Relationship
1680 - (NSString *) type {
1688 - (NSString *) name {
1695 /* Package Class {{{ */
1696 @interface Package : NSObject {
1700 pkgCache::VerIterator version_;
1701 pkgCache::PkgIterator iterator_;
1702 _transient Database *database_;
1703 pkgCache::VerFileIterator file_;
1709 _transient NSString *section$_;
1714 CYString installed_;
1720 CYString depiction_;
1731 NSMutableArray *tags_;
1734 NSMutableDictionary *metadata_;
1735 _transient NSDate *firstSeen_;
1736 _transient NSDate *lastSeen_;
1741 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1742 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1744 - (pkgCache::PkgIterator) iterator;
1747 - (NSString *) section;
1748 - (NSString *) simpleSection;
1750 - (NSString *) longSection;
1751 - (NSString *) shortSection;
1755 - (Address *) maintainer;
1757 - (NSString *) longDescription;
1758 - (NSString *) shortDescription;
1761 - (NSMutableDictionary *) metadata;
1763 - (BOOL) subscribed;
1766 - (NSString *) latest;
1767 - (NSString *) installed;
1768 - (BOOL) uninstalled;
1771 - (BOOL) upgradableAndEssential:(BOOL)essential;
1774 - (BOOL) unfiltered;
1778 - (BOOL) halfConfigured;
1779 - (BOOL) halfInstalled;
1781 - (NSString *) mode;
1784 - (NSString *) name;
1786 - (NSString *) homepage;
1787 - (NSString *) depiction;
1788 - (Address *) author;
1790 - (NSString *) support;
1792 - (NSArray *) files;
1793 - (NSArray *) warnings;
1794 - (NSArray *) applications;
1796 - (Source *) source;
1797 - (NSString *) role;
1799 - (BOOL) matches:(NSString *)text;
1801 - (bool) hasSupportingRole;
1802 - (BOOL) hasTag:(NSString *)tag;
1803 - (NSString *) primaryPurpose;
1804 - (NSArray *) purposes;
1805 - (bool) isCommercial;
1807 - (CYString &) cyname;
1809 - (uint32_t) compareBySection:(NSArray *)sections;
1814 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1815 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1816 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1817 - (bool) isVisibleInSection:(NSString *)section;
1818 - (bool) isVisibleInSource:(Source *)source;
1822 uint32_t PackageChangesRadix(Package *self, void *) {
1827 uint32_t timestamp : 30;
1828 uint32_t ignored : 1;
1829 uint32_t upgradable : 1;
1833 bool upgradable([self upgradableAndEssential:YES]);
1834 value.bits.upgradable = upgradable ? 1 : 0;
1837 value.bits.timestamp = 0;
1838 value.bits.ignored = [self ignored] ? 0 : 1;
1839 value.bits.upgradable = 1;
1841 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1842 value.bits.ignored = 0;
1843 value.bits.upgradable = 0;
1846 return _not(uint32_t) - value.key;
1849 _finline static void Stifle(uint8_t &value) {
1852 uint32_t PackagePrefixRadix(Package *self, void *context) {
1853 size_t offset(reinterpret_cast<size_t>(context));
1854 CYString &name([self cyname]);
1856 size_t size(name.size());
1859 char *text(name.data());
1862 if (!isdigit(text[0]))
1866 while (size != digits && isdigit(text[digits]))
1876 if (offset == 0 && zeros != 0) {
1877 memset(data, '0', zeros);
1878 memcpy(data + zeros, text, 4 - zeros);
1880 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1881 if (size <= offset - zeros)
1884 text += offset - zeros;
1885 size -= offset - zeros;
1888 memcpy(data, text, 4);
1890 memcpy(data, text, size);
1891 memset(data + size, 0, 4 - size);
1894 for (size_t i(0); i != 4; ++i)
1895 if (isalpha(data[i]))
1903 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1905 /* XXX: ntohl may be more honest */
1906 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1909 CYString &(*PackageName)(Package *self, SEL sel);
1911 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1912 _profile(PackageNameCompare)
1913 CYString &lhi(PackageName(lhs, @selector(cyname)));
1914 CYString &rhi(PackageName(rhs, @selector(cyname)));
1915 CFStringRef lhn(lhi), rhn(rhi);
1918 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1919 else if (rhn == NULL)
1920 return NSOrderedDescending;
1922 _profile(PackageNameCompare$NumbersLast)
1923 if (!lhi.empty() && !rhi.empty()) {
1924 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1925 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1926 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1927 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1928 return lha ? NSOrderedAscending : NSOrderedDescending;
1932 CFIndex length = CFStringGetLength(lhn);
1934 _profile(PackageNameCompare$Compare)
1935 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1940 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1941 return PackageNameCompare(*lhs, *rhs, context);
1944 struct PackageNameOrdering :
1945 std::binary_function<Package *, Package *, bool>
1947 _finline bool operator ()(Package *lhs, Package *rhs) const {
1948 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1952 @implementation Package
1954 - (NSString *) description {
1955 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1965 if (sponsor$_ != nil)
1966 [sponsor$_ release];
1967 if (author$_ != nil)
1974 if (metadata_ != nil)
1975 [metadata_ release];
1980 + (NSString *) webScriptNameForSelector:(SEL)selector {
1981 if (selector == @selector(hasTag:))
1987 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1988 return [self webScriptNameForSelector:selector] == nil;
1991 + (NSArray *) _attributeKeys {
1992 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];
1995 - (NSArray *) attributeKeys {
1996 return [[self class] _attributeKeys];
1999 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2000 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2010 _profile(Package$parse)
2011 pkgRecords::Parser *parser;
2013 _profile(Package$parse$Lookup)
2014 parser = &[database_ records]->Lookup(file_);
2019 _profile(Package$parse$Find)
2025 {"depiction", &depiction_},
2026 {"homepage", &homepage_},
2027 {"website", &website},
2029 {"support", &support_},
2030 {"sponsor", &sponsor_},
2031 {"author", &author_},
2034 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2035 const char *start, *end;
2037 if (parser->Find(names[i].name_, start, end)) {
2038 CYString &value(*names[i].value_);
2039 _profile(Package$parse$Value)
2040 value.set(pool_, start, end - start);
2046 _profile(Package$parse$Tagline)
2047 const char *start, *end;
2048 if (parser->ShortDesc(start, end)) {
2049 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2052 while (stop != start && stop[-1] == '\r')
2054 tagline_.set(pool_, start, stop - start);
2058 _profile(Package$parse$Retain)
2059 if (homepage_.empty())
2060 homepage_ = website;
2061 if (homepage_ == depiction_)
2067 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2068 if ((self = [super init]) != nil) {
2069 _profile(Package$initWithVersion)
2070 era_ = [database era];
2075 _profile(Package$initWithVersion$ParentPkg)
2076 iterator_ = version.ParentPkg();
2079 database_ = database;
2081 _profile(Package$initWithVersion$Latest)
2082 const char *latest(StripVersion_(version_.VerStr()));
2083 latest_ = (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(latest), strlen(latest), kCFStringEncodingASCII, NO);
2086 pkgCache::VerIterator current;
2087 _profile(Package$initWithVersion$Versions)
2088 current = iterator_.CurrentVer();
2090 installed_.set(pool_, StripVersion_(current.VerStr()));
2092 if (!version_.end())
2093 file_ = version_.FileList();
2095 pkgCache &cache([database_ cache]);
2096 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2100 _profile(Package$initWithVersion$Name)
2101 id_.set(pool_, iterator_.Name());
2102 name_.set(pool, iterator_.Display());
2105 _profile(Package$initWithVersion$lowercaseString)
2106 char *data(id_.data());
2107 for (size_t i(0), e(id_.size()); i != e; ++i)
2108 // XXX: do not use tolower() as this is not locale-specific? :(
2112 _profile(Package$initWithVersion$Tags)
2113 pkgCache::TagIterator tag(iterator_.TagList());
2115 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2117 const char *name(tag.Name());
2118 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2119 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2120 role_ = (NSString *) CYStringCreate(name + 6);
2122 } while (!tag.end());
2126 bool changed(false);
2128 _profile(Package$initWithVersion$Metadata)
2129 metadata_ = [Packages_ objectForKey:id_];
2131 if (metadata_ == nil) {
2134 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2135 firstSeen_, @"FirstSeen",
2136 latest_, @"LastVersion",
2141 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2142 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2144 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2145 subscribed_ = [subscribed boolValue];
2147 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2149 if (firstSeen_ == nil) {
2150 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2151 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2155 if (version == nil) {
2156 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2158 } else if (![version isEqualToString:latest_]) {
2159 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2161 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2166 metadata_ = [metadata_ retain];
2169 [Packages_ setObject:metadata_ forKey:id_];
2174 _profile(Package$initWithVersion$Section)
2175 section_.set(pool_, iterator_.Section());
2178 _profile(Package$initWithVersion$hasTag)
2179 obsolete_ = [self hasTag:@"cydia::obsolete"];
2180 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2183 ignored_ = iterator_->SelectedState == pkgCache::State::Hold;
2187 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2188 pkgCache::VerIterator version;
2190 _profile(Package$packageWithIterator$GetCandidateVer)
2191 version = [database policy]->GetCandidateVer(iterator);
2197 return [[[Package alloc]
2198 initWithVersion:version
2205 - (pkgCache::PkgIterator) iterator {
2209 - (NSString *) section {
2210 if (section$_ == nil) {
2211 if (section_.empty())
2214 _profile(Package$section)
2215 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2216 NSString *name(section_);
2217 section$_ = [SectionMap_ objectForKey:name] ?: name;
2222 - (NSString *) simpleSection {
2223 if (NSString *section = [self section])
2224 return Simplify(section);
2229 - (NSString *) longSection {
2230 return LocalizeSection([self section]);
2233 - (NSString *) shortSection {
2234 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2237 - (NSString *) uri {
2240 pkgIndexFile *index;
2241 pkgCache::PkgFileIterator file(file_.File());
2242 if (![database_ list].FindIndex(file, index))
2244 return [NSString stringWithUTF8String:iterator_->Path];
2245 //return [NSString stringWithUTF8String:file.Site()];
2246 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2250 - (Address *) maintainer {
2251 @synchronized (database_) {
2252 if ([database_ era] != era_ || file_.end())
2255 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2256 const std::string &maintainer(parser->Maintainer());
2257 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2261 @synchronized (database_) {
2262 if ([database_ era] != era_ || version_.end())
2265 return version_->InstalledSize;
2268 - (NSString *) longDescription {
2269 @synchronized (database_) {
2270 if ([database_ era] != era_ || file_.end())
2273 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2274 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2276 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2277 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2278 if ([lines count] < 2)
2281 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2282 for (size_t i(1), e([lines count]); i != e; ++i) {
2283 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2284 [trimmed addObject:trim];
2287 return [trimmed componentsJoinedByString:@"\n"];
2290 - (NSString *) shortDescription {
2295 _profile(Package$index)
2296 CFStringRef name((CFStringRef) [self name]);
2297 if (CFStringGetLength(name) == 0)
2299 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2300 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2302 return toupper(character);
2306 - (NSMutableDictionary *) metadata {
2311 if (subscribed_ && lastSeen_ != nil)
2316 - (BOOL) subscribed {
2324 - (NSString *) latest {
2328 - (NSString *) installed {
2332 - (BOOL) uninstalled {
2333 return installed_.empty();
2337 return !version_.end();
2340 - (BOOL) upgradableAndEssential:(BOOL)essential {
2341 _profile(Package$upgradableAndEssential)
2342 pkgCache::VerIterator current(iterator_.CurrentVer());
2344 return essential && essential_;
2346 return !version_.end() && version_ != current;
2350 - (BOOL) essential {
2355 return [database_ cache][iterator_].InstBroken();
2358 - (BOOL) unfiltered {
2359 _profile(Package$unfiltered$obsolete)
2364 _profile(Package$unfiltered$hasSupportingRole)
2365 if (![self hasSupportingRole])
2373 if (![self unfiltered])
2376 NSString *section([self section]);
2378 _profile(Package$visible$isSectionVisible)
2379 if (section != nil && !isSectionVisible(section))
2387 unsigned char current(iterator_->CurrentState);
2388 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2391 - (BOOL) halfConfigured {
2392 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2395 - (BOOL) halfInstalled {
2396 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2400 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2401 return state.Mode != pkgDepCache::ModeKeep;
2404 - (NSString *) mode {
2405 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2407 switch (state.Mode) {
2408 case pkgDepCache::ModeDelete:
2409 if ((state.iFlags & pkgDepCache::Purge) != 0)
2413 case pkgDepCache::ModeKeep:
2414 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2415 return @"REINSTALL";
2416 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2420 case pkgDepCache::ModeInstall:
2421 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2422 return @"REINSTALL";
2423 else*/ switch (state.Status) {
2425 return @"DOWNGRADE";
2431 return @"NEW_INSTALL";
2442 - (NSString *) name {
2443 return name_.empty() ? id_ : name_;
2446 - (UIImage *) icon {
2447 NSString *section = [self simpleSection];
2451 if ([static_cast<id>(icon_) hasPrefix:@"file:///"])
2452 // XXX: correct escaping
2453 icon = [UIImage imageAtPath:[static_cast<id>(icon_) substringFromIndex:7]];
2454 if (icon == nil) if (section != nil)
2455 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2456 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2457 if ([dicon hasPrefix:@"file:///"])
2458 // XXX: correct escaping
2459 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2461 icon = [UIImage applicationImageNamed:@"unknown.png"];
2465 - (NSString *) homepage {
2469 - (NSString *) depiction {
2470 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2473 - (Address *) sponsor {
2474 if (sponsor$_ == nil) {
2475 if (sponsor_.empty())
2477 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2481 - (Address *) author {
2482 if (author$_ == nil) {
2483 if (author_.empty())
2485 author$_ = [[Address addressWithString:author_] retain];
2489 - (NSString *) support {
2490 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2493 - (NSArray *) files {
2494 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2495 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2498 fin.open([path UTF8String]);
2503 while (std::getline(fin, line))
2504 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2509 - (NSArray *) warnings {
2510 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2511 const char *name(iterator_.Name());
2513 size_t length(strlen(name));
2514 if (length < 2) invalid:
2515 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2516 else for (size_t i(0); i != length; ++i)
2518 /* XXX: technically this is not allowed */
2519 (name[i] < 'A' || name[i] > 'Z') &&
2520 (name[i] < 'a' || name[i] > 'z') &&
2521 (name[i] < '0' || name[i] > '9') &&
2522 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2525 if (strcmp(name, "cydia") != 0) {
2528 bool _private = false;
2531 bool repository = [[self section] isEqualToString:@"Repositories"];
2533 if (NSArray *files = [self files])
2534 for (NSString *file in files)
2535 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2537 else if (!user && [file isEqualToString:@"/User"])
2539 else if (!_private && [file isEqualToString:@"/private"])
2541 else if (!stash && [file isEqualToString:@"/var/stash"])
2544 /* XXX: this is not sensitive enough. only some folders are valid. */
2545 if (cydia && !repository)
2546 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2548 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2550 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2552 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2555 return [warnings count] == 0 ? nil : warnings;
2558 - (NSArray *) applications {
2559 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2561 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2563 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2564 if (NSArray *files = [self files])
2565 for (NSString *file in files)
2566 if (application_r(file)) {
2567 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2568 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2569 if ([id isEqualToString:me])
2572 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2574 display = application_r[1];
2576 NSString *bundle([file stringByDeletingLastPathComponent]);
2577 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2578 if (icon == nil || [icon length] == 0)
2580 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2582 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2583 [applications addObject:application];
2585 [application addObject:id];
2586 [application addObject:display];
2587 [application addObject:url];
2590 return [applications count] == 0 ? nil : applications;
2593 - (Source *) source {
2594 if (source_ == nil) {
2595 @synchronized (database_) {
2596 if ([database_ era] != era_ || file_.end())
2597 source_ = (Source *) [NSNull null];
2599 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2603 return source_ == (Source *) [NSNull null] ? nil : source_;
2606 - (NSString *) role {
2610 - (BOOL) matches:(NSString *)text {
2616 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2617 if (range.location != NSNotFound)
2620 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2621 if (range.location != NSNotFound)
2624 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2625 if (range.location != NSNotFound)
2631 - (bool) hasSupportingRole {
2634 if ([role_ isEqualToString:@"enduser"])
2636 if ([Role_ isEqualToString:@"User"])
2638 if ([role_ isEqualToString:@"hacker"])
2640 if ([Role_ isEqualToString:@"Hacker"])
2642 if ([role_ isEqualToString:@"developer"])
2644 if ([Role_ isEqualToString:@"Developer"])
2649 - (BOOL) hasTag:(NSString *)tag {
2650 return tags_ == nil ? NO : [tags_ containsObject:tag];
2653 - (NSString *) primaryPurpose {
2654 for (NSString *tag in tags_)
2655 if ([tag hasPrefix:@"purpose::"])
2656 return [tag substringFromIndex:9];
2660 - (NSArray *) purposes {
2661 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2662 for (NSString *tag in tags_)
2663 if ([tag hasPrefix:@"purpose::"])
2664 [purposes addObject:[tag substringFromIndex:9]];
2665 return [purposes count] == 0 ? nil : purposes;
2668 - (bool) isCommercial {
2669 return [self hasTag:@"cydia::commercial"];
2672 - (CYString &) cyname {
2673 return name_.empty() ? id_ : name_;
2676 - (uint32_t) compareBySection:(NSArray *)sections {
2677 NSString *section([self section]);
2678 for (size_t i(0), e([sections count]); i != e; ++i) {
2679 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2683 return _not(uint32_t);
2687 @synchronized (database_) {
2688 pkgProblemResolver *resolver = [database_ resolver];
2689 resolver->Clear(iterator_);
2691 pkgCacheFile &cache([database_ cache]);
2692 cache->SetReInstall(iterator_, false);
2693 cache->MarkKeep(iterator_, false);
2697 @synchronized (database_) {
2698 pkgProblemResolver *resolver = [database_ resolver];
2699 resolver->Clear(iterator_);
2700 resolver->Protect(iterator_);
2702 pkgCacheFile &cache([database_ cache]);
2703 cache->SetReInstall(iterator_, false);
2704 cache->MarkInstall(iterator_, false);
2706 pkgDepCache::StateCache &state((*cache)[iterator_]);
2707 if (!state.Install())
2708 cache->SetReInstall(iterator_, true);
2712 @synchronized (database_) {
2713 pkgProblemResolver *resolver = [database_ resolver];
2714 resolver->Clear(iterator_);
2715 resolver->Remove(iterator_);
2716 resolver->Protect(iterator_);
2718 pkgCacheFile &cache([database_ cache]);
2719 cache->SetReInstall(iterator_, false);
2720 cache->MarkDelete(iterator_, true);
2723 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2724 _profile(Package$isUnfilteredAndSearchedForBy)
2727 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2728 value &= [self unfiltered];
2731 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2732 value &= [self matches:search];
2739 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2740 if ([search length] == 0)
2743 _profile(Package$isUnfilteredAndSelectedForBy)
2746 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2747 value &= [self unfiltered];
2750 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2751 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2758 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2759 return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]);
2762 - (bool) isVisibleInSection:(NSString *)name {
2763 NSString *section([self section]);
2767 section == nil && [name length] == 0 ||
2768 [name isEqualToString:section]
2769 ) && [self visible];
2772 - (bool) isVisibleInSource:(Source *)source {
2773 return [self source] == source && [self visible];
2778 /* Section Class {{{ */
2779 @interface Section : NSObject {
2784 NSString *localized_;
2787 - (NSComparisonResult) compareByLocalized:(Section *)section;
2788 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2789 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2790 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2791 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2792 - (NSString *) name;
2799 - (void) addToCount;
2801 - (void) setCount:(size_t)count;
2802 - (NSString *) localized;
2806 @implementation Section
2810 if (localized_ != nil)
2811 [localized_ release];
2815 - (NSComparisonResult) compareByLocalized:(Section *)section {
2816 NSString *lhs(localized_);
2817 NSString *rhs([section localized]);
2819 /*if ([lhs length] != 0 && [rhs length] != 0) {
2820 unichar lhc = [lhs characterAtIndex:0];
2821 unichar rhc = [rhs characterAtIndex:0];
2823 if (isalpha(lhc) && !isalpha(rhc))
2824 return NSOrderedAscending;
2825 else if (!isalpha(lhc) && isalpha(rhc))
2826 return NSOrderedDescending;
2829 return [lhs compare:rhs options:LaxCompareOptions_];
2832 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2833 if ((self = [self initWithName:name localize:NO]) != nil) {
2834 if (localized != nil)
2835 localized_ = [localized retain];
2839 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2840 return [self initWithName:name row:0 localize:localize];
2843 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2844 if ((self = [super init]) != nil) {
2845 name_ = [name retain];
2849 localized_ = [LocalizeSection(name_) retain];
2853 /* XXX: localize the index thingees */
2854 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2855 if ((self = [super init]) != nil) {
2856 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2862 - (NSString *) name {
2882 - (void) addToCount {
2886 - (void) setCount:(size_t)count {
2890 - (NSString *) localized {
2897 static NSString *Colon_;
2898 static NSString *Elision_;
2899 static NSString *Error_;
2900 static NSString *Warning_;
2902 /* Database Implementation {{{ */
2903 @implementation Database
2905 + (Database *) sharedInstance {
2906 static Database *instance;
2907 if (instance == nil)
2908 instance = [[Database alloc] init];
2916 - (void) releasePackages {
2917 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
2918 CFArrayRemoveAllValues(packages_);
2922 // XXX: actually implement this thing
2924 [self releasePackages];
2925 apr_pool_destroy(pool_);
2926 NSRecycleZone(zone_);
2930 - (void) _readCydia:(NSNumber *)fd { _pooled
2931 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2932 std::istream is(&ib);
2935 static Pcre finish_r("^finish:([^:]*)$");
2937 while (std::getline(is, line)) {
2938 const char *data(line.c_str());
2939 size_t size = line.size();
2940 lprintf("C:%s\n", data);
2942 if (finish_r(data, size)) {
2943 NSString *finish = finish_r[1];
2944 int index = [Finishes_ indexOfObject:finish];
2945 if (index != INT_MAX && index > Finish_)
2953 - (void) _readStatus:(NSNumber *)fd { _pooled
2954 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2955 std::istream is(&ib);
2958 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2959 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2961 while (std::getline(is, line)) {
2962 const char *data(line.c_str());
2963 size_t size(line.size());
2964 lprintf("S:%s\n", data);
2966 if (conffile_r(data, size)) {
2967 [delegate_ setConfigurationData:conffile_r[1]];
2968 } else if (strncmp(data, "status: ", 8) == 0) {
2969 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2970 [delegate_ setProgressTitle:string];
2971 } else if (pmstatus_r(data, size)) {
2972 std::string type([pmstatus_r[1] UTF8String]);
2973 NSString *id = pmstatus_r[2];
2975 float percent([pmstatus_r[3] floatValue]);
2976 [delegate_ setProgressPercent:(percent / 100)];
2978 NSString *string = pmstatus_r[4];
2980 if (type == "pmerror")
2981 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
2982 withObject:[NSArray arrayWithObjects:string, id, nil]
2985 else if (type == "pmstatus") {
2986 [delegate_ setProgressTitle:string];
2987 } else if (type == "pmconffile")
2988 [delegate_ setConfigurationData:string];
2990 lprintf("E:unknown pmstatus\n");
2992 lprintf("E:unknown status\n");
2998 - (void) _readOutput:(NSNumber *)fd { _pooled
2999 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3000 std::istream is(&ib);
3003 while (std::getline(is, line)) {
3004 lprintf("O:%s\n", line.c_str());
3005 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3015 - (Package *) packageWithName:(NSString *)name {
3016 @synchronized (self) {
3017 if (static_cast<pkgDepCache *>(cache_) == NULL)
3019 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3020 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3024 if ((self = [super init]) != nil) {
3031 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3032 apr_pool_create(&pool_, NULL);
3034 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
3038 _assert(pipe(fds) != -1);
3041 _config->Set("APT::Keep-Fds::", cydiafd_);
3042 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3045 detachNewThreadSelector:@selector(_readCydia:)
3047 withObject:[NSNumber numberWithInt:fds[0]]
3050 _assert(pipe(fds) != -1);
3054 detachNewThreadSelector:@selector(_readStatus:)
3056 withObject:[NSNumber numberWithInt:fds[0]]
3059 _assert(pipe(fds) != -1);
3060 _assert(dup2(fds[0], 0) != -1);
3061 _assert(close(fds[0]) != -1);
3063 input_ = fdopen(fds[1], "a");
3065 _assert(pipe(fds) != -1);
3066 _assert(dup2(fds[1], 1) != -1);
3067 _assert(close(fds[1]) != -1);
3070 detachNewThreadSelector:@selector(_readOutput:)
3072 withObject:[NSNumber numberWithInt:fds[0]]
3077 - (pkgCacheFile &) cache {
3081 - (pkgDepCache::Policy *) policy {
3085 - (pkgRecords *) records {
3089 - (pkgProblemResolver *) resolver {
3093 - (pkgAcquire &) fetcher {
3097 - (pkgSourceList &) list {
3101 - (NSArray *) packages {
3102 return (NSArray *) packages_;
3105 - (NSArray *) sources {
3106 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3107 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3108 [sources addObject:i->second];
3112 - (NSArray *) issues {
3113 if (cache_->BrokenCount() == 0)
3116 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3118 for (Package *package in [self packages]) {
3119 if (![package broken])
3121 pkgCache::PkgIterator pkg([package iterator]);
3123 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3124 [entry addObject:[package name]];
3125 [issues addObject:entry];
3127 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3131 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3132 pkgCache::DepIterator start;
3133 pkgCache::DepIterator end;
3134 dep.GlobOr(start, end); // ++dep
3136 if (!cache_->IsImportantDep(end))
3138 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3141 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3142 [entry addObject:failure];
3143 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3145 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3146 if (Package *package = [self packageWithName:name])
3147 name = [package name];
3148 [failure addObject:name];
3150 pkgCache::PkgIterator target(start.TargetPkg());
3151 if (target->ProvidesList != 0)
3152 [failure addObject:@"?"];
3154 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3156 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3157 else if (!cache_[target].CandidateVerIter(cache_).end())
3158 [failure addObject:@"-"];
3159 else if (target->ProvidesList == 0)
3160 [failure addObject:@"!"];
3162 [failure addObject:@"%"];
3166 if (start.TargetVer() != 0)
3167 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3178 - (bool) popErrorWithTitle:(NSString *)title {
3180 std::string message;
3182 while (!_error->empty()) {
3184 bool warning(!_error->PopMessage(error));
3188 size_t size(error.size());
3189 if (size == 0 || error[size - 1] != '\n')
3191 error.resize(size - 1);
3193 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3195 if (!message.empty())
3200 if (fatal && !message.empty())
3201 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3206 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3207 return [self popErrorWithTitle:title] || !success;
3210 - (void) reloadData { CYPoolStart() {
3211 @synchronized (self) {
3214 [self releasePackages];
3240 apr_pool_clear(pool_);
3241 NSRecycleZone(zone_);
3243 int chk(creat("/tmp/cydia.chk", 0644));
3247 NSString *title(UCLocalize("DATABASE"));
3250 if (!cache_.Open(progress_, true)) { pop:
3252 bool warning(!_error->PopMessage(error));
3253 lprintf("cache_.Open():[%s]\n", error.c_str());
3255 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3256 [delegate_ repairWithSelector:@selector(configure)];
3257 else if (error == "The package lists or status file could not be parsed or opened.")
3258 [delegate_ repairWithSelector:@selector(update)];
3259 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3260 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3261 // else if (error == "The list of sources could not be read.")
3263 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3272 unlink("/tmp/cydia.chk");
3274 now_ = [[NSDate date] retain];
3276 policy_ = new pkgDepCache::Policy();
3277 records_ = new pkgRecords(cache_);
3278 resolver_ = new pkgProblemResolver(cache_);
3279 fetcher_ = new pkgAcquire(&status_);
3282 list_ = new pkgSourceList();
3283 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3286 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3287 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3291 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3294 if (cache_->BrokenCount() != 0) {
3295 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3298 if (cache_->BrokenCount() != 0) {
3299 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3303 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3307 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3308 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3309 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3310 // XXX: this could be more intelligent
3311 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3312 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3314 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3319 /*std::vector<Package *> packages;
3320 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3321 [packages_ release];
3326 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3327 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3328 //packages.push_back(package);
3329 CFArrayAppendValue(packages_, [package retain]);
3333 /*if (packages.empty())
3334 packages_ = [[NSArray alloc] init];
3336 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3339 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3340 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3341 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3349 /*if (!packages.empty())
3350 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3351 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3353 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3355 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3357 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3361 } } CYPoolEnd() _trace(); }
3364 @synchronized (self) {
3366 resolver_ = new pkgProblemResolver(cache_);
3368 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3369 if (!cache_[iterator].Keep()) {
3370 cache_->MarkKeep(iterator, false);
3371 cache_->SetReInstall(iterator, false);
3376 - (void) configure {
3377 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3378 system([dpkg UTF8String]);
3382 // XXX: I don't remember this condition
3387 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3389 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3391 if ([self popErrorWithTitle:title])
3395 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3398 public pkgArchiveCleaner
3401 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3406 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3413 fetcher_->Shutdown();
3415 pkgRecords records(cache_);
3417 lock_ = new FileFd();
3418 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3420 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3422 if ([self popErrorWithTitle:title])
3426 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3429 manager_ = (_system->CreatePM(cache_));
3430 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3437 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3439 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3441 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3443 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3444 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3447 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3452 bool failed = false;
3453 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3454 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3456 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3459 std::string uri = (*item)->DescURI();
3460 std::string error = (*item)->ErrorText;
3462 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3465 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3466 withObject:[NSArray arrayWithObjects:
3467 [NSString stringWithUTF8String:error.c_str()],
3479 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3481 if (_error->PendingError()) {
3486 if (result == pkgPackageManager::Failed) {
3491 if (result != pkgPackageManager::Completed) {
3496 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3498 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3500 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3501 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3504 if (![before isEqualToArray:after])
3509 NSString *title(UCLocalize("UPGRADE"));
3510 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3516 [self updateWithStatus:status_];
3519 - (void) updateWithStatus:(Status &)status {
3520 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3521 NSString *title(UCLocalize("REFRESHING_DATA"));
3524 if (!list.ReadMainList())
3525 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3528 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3529 if ([self popErrorWithTitle:title])
3532 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3533 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3534 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3536 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3540 - (void) setDelegate:(id)delegate {
3541 delegate_ = delegate;
3542 status_.setDelegate(delegate);
3543 progress_.setDelegate(delegate);
3546 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3547 SourceMap::const_iterator i(sources_.find(file->ID));
3548 return i == sources_.end() ? nil : i->second;
3554 /* Confirmation Controller {{{ */
3555 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3556 if (!iterator.end())
3557 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3558 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3560 pkgCache::PkgIterator package(dep.TargetPkg());
3563 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3571 /* Web Scripting {{{ */
3572 @interface CydiaObject : NSObject {
3574 _transient id delegate_;
3577 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3580 @implementation CydiaObject
3583 [indirect_ release];
3587 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3588 if ((self = [super init]) != nil) {
3589 indirect_ = [indirect retain];
3593 - (void) setDelegate:(id)delegate {
3594 delegate_ = delegate;
3597 + (NSArray *) _attributeKeys {
3598 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3601 - (NSArray *) attributeKeys {
3602 return [[self class] _attributeKeys];
3605 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3606 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3609 - (NSString *) device {
3610 return [[UIDevice currentDevice] uniqueIdentifier];
3613 #if 0 // XXX: implement!
3614 - (NSString *) mac {
3615 if (![indirect_ promptForSensitive:@"Mac Address"])
3619 - (NSString *) serial {
3620 if (![indirect_ promptForSensitive:@"Serial #"])
3624 - (NSString *) firewire {
3625 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3629 - (NSString *) imei {
3630 if (![indirect_ promptForSensitive:@"IMEI"])
3635 + (NSString *) webScriptNameForSelector:(SEL)selector {
3636 if (selector == @selector(close))
3638 else if (selector == @selector(getInstalledPackages))
3639 return @"getInstalledPackages";
3640 else if (selector == @selector(getPackageById:))
3641 return @"getPackageById";
3642 else if (selector == @selector(installPackages:))
3643 return @"installPackages";
3644 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3645 return @"setButtonImage";
3646 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3647 return @"setButtonTitle";
3648 else if (selector == @selector(setPopupHook:))
3649 return @"setPopupHook";
3650 else if (selector == @selector(setSpecial:))
3651 return @"setSpecial";
3652 else if (selector == @selector(setToken:))
3654 else if (selector == @selector(setViewportWidth:))
3655 return @"setViewportWidth";
3656 else if (selector == @selector(supports:))
3658 else if (selector == @selector(stringWithFormat:arguments:))
3660 else if (selector == @selector(localizedStringForKey:value:table:))
3662 else if (selector == @selector(du:))
3664 else if (selector == @selector(statfs:))
3670 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3671 return [self webScriptNameForSelector:selector] == nil;
3674 - (BOOL) supports:(NSString *)feature {
3675 return [feature isEqualToString:@"window.open"];
3678 - (NSArray *) getInstalledPackages {
3679 NSArray *packages([[Database sharedInstance] packages]);
3680 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3681 for (Package *package in packages)
3682 if ([package installed] != nil)
3683 [installed addObject:package];
3687 - (Package *) getPackageById:(NSString *)id {
3688 Package *package([[Database sharedInstance] packageWithName:id]);
3693 - (NSArray *) statfs:(NSString *)path {
3696 if (path == nil || statfs([path UTF8String], &stat) == -1)
3699 return [NSArray arrayWithObjects:
3700 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3701 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3702 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3706 - (NSNumber *) du:(NSString *)path {
3707 NSNumber *value(nil);
3710 _assert(pipe(fds) != -1);
3712 pid_t pid(ExecFork());
3714 _assert(dup2(fds[1], 1) != -1);
3715 _assert(close(fds[0]) != -1);
3716 _assert(close(fds[1]) != -1);
3717 /* XXX: this should probably not use du */
3718 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3723 _assert(close(fds[1]) != -1);
3725 if (FILE *du = fdopen(fds[0], "r")) {
3727 while (fgets(line, sizeof(line), du) != NULL) {
3728 size_t length(strlen(line));
3729 while (length != 0 && line[length - 1] == '\n')
3730 line[--length] = '\0';
3731 if (char *tab = strchr(line, '\t')) {
3733 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3738 } else _assert(close(fds[0]));
3742 if (waitpid(pid, &status, 0) == -1)
3745 else _assert(false);
3754 - (void) installPackages:(NSArray *)packages {
3755 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3758 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3759 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3762 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3763 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3766 - (void) setSpecial:(id)function {
3767 [indirect_ setSpecial:function];
3770 - (void) setToken:(NSString *)token {
3773 Token_ = [token retain];
3775 [Metadata_ setObject:Token_ forKey:@"Token"];
3779 - (void) setPopupHook:(id)function {
3780 [indirect_ setPopupHook:function];
3783 - (void) setViewportWidth:(float)width {
3784 [indirect_ setViewportWidth:width];
3787 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3788 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3789 unsigned count([arguments count]);
3791 for (unsigned i(0); i != count; ++i)
3792 values[i] = [arguments objectAtIndex:i];
3793 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3796 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3797 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3799 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3801 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3807 /* Cydia Browser Controller {{{ */
3808 @interface CYBrowserController : BrowserController {
3809 CydiaObject *cydia_;
3814 @implementation CYBrowserController
3821 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3824 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3825 [super webView:view didClearWindowObject:window forFrame:frame];
3827 WebDataSource *source([frame dataSource]);
3828 NSURLResponse *response([source response]);
3829 NSURL *url([response URL]);
3830 NSString *scheme([url scheme]);
3832 NSHTTPURLResponse *http;
3833 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3834 http = (NSHTTPURLResponse *) response;
3838 NSDictionary *headers([http allHeaderFields]);
3839 NSString *host([url host]);
3840 [self setHeaders:headers forHost:host];
3843 [host isEqualToString:@"cydia.saurik.com"] ||
3844 [host hasSuffix:@".cydia.saurik.com"] ||
3845 [scheme isEqualToString:@"file"]
3847 [window setValue:cydia_ forKey:@"cydia"];
3850 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3851 if (System_ != NULL)
3852 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3853 if (Machine_ != NULL)
3854 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3856 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3858 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3861 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3862 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3863 [self _setMoreHeaders:copy];
3867 - (void) setDelegate:(id)delegate {
3868 [super setDelegate:delegate];
3869 [cydia_ setDelegate:delegate];
3873 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3874 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3876 WebView *webview([[webview_ _documentView] webView]);
3878 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3880 NSString *application = package == nil ? @"Cydia" : [NSString
3881 stringWithFormat:@"Cydia/%@",
3886 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3888 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3889 if (Product_ != nil)
3890 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3892 [webview setApplicationNameForUserAgent:application];
3899 /* Confirmation {{{ */
3900 @protocol ConfirmationControllerDelegate
3901 - (void) cancelAndClear:(bool)clear;
3902 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3906 @interface ConfirmationController : CYBrowserController {
3907 _transient Database *database_;
3908 UIAlertView *essential_;
3915 - (id) initWithDatabase:(Database *)database;
3919 @implementation ConfirmationController
3926 if (essential_ != nil)
3927 [essential_ release];
3931 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3932 NSString *context([alert context]);
3934 if ([context isEqualToString:@"remove"]) {
3935 if (button == [alert cancelButtonIndex]) {
3936 [self dismissModalViewControllerAnimated:YES];
3937 } else if (button == [alert firstOtherButtonIndex]) {
3940 [delegate_ confirmWithNavigationController:[self navigationController]];
3943 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3944 } else if ([context isEqualToString:@"unable"]) {
3945 [self dismissModalViewControllerAnimated:YES];
3946 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3948 [super alertView:alert clickedButtonAtIndex:button];
3952 - (void) _doContinue {
3953 [self dismissModalViewControllerAnimated:YES];
3954 [delegate_ cancelAndClear:NO];
3957 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
3958 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
3962 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3963 [super webView:view didClearWindowObject:window forFrame:frame];
3964 [window setValue:changes_ forKey:@"changes"];
3965 [window setValue:issues_ forKey:@"issues"];
3966 [window setValue:sizes_ forKey:@"sizes"];
3967 [window setValue:self forKey:@"queue"];
3970 - (id) initWithDatabase:(Database *)database {
3971 if ((self = [super init]) != nil) {
3972 database_ = database;
3974 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
3976 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3977 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3978 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3979 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3980 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3984 pkgDepCache::Policy *policy([database_ policy]);
3986 pkgCacheFile &cache([database_ cache]);
3987 NSArray *packages = [database_ packages];
3988 for (Package *package in packages) {
3989 pkgCache::PkgIterator iterator = [package iterator];
3990 pkgDepCache::StateCache &state(cache[iterator]);
3992 NSString *name([package name]);
3994 if (state.NewInstall())
3995 [installing addObject:name];
3996 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3997 [reinstalling addObject:name];
3998 else if (state.Upgrade())
3999 [upgrading addObject:name];
4000 else if (state.Downgrade())
4001 [downgrading addObject:name];
4002 else if (state.Delete()) {
4003 if ([package essential])
4005 [removing addObject:name];
4008 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4009 substrate_ |= DepSubstrate(iterator.CurrentVer());
4014 else if (Advanced_) {
4015 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4017 essential_ = [[UIAlertView alloc]
4018 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4019 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4021 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4022 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4025 [essential_ setContext:@"remove"];
4027 essential_ = [[UIAlertView alloc]
4028 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4029 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4031 cancelButtonTitle:UCLocalize("OKAY")
4032 otherButtonTitles:nil
4035 [essential_ setContext:@"unable"];
4038 changes_ = [[NSArray alloc] initWithObjects:
4046 issues_ = [database_ issues];
4048 issues_ = [issues_ retain];
4050 sizes_ = [[NSArray alloc] initWithObjects:
4051 SizeString([database_ fetcher].FetchNeeded()),
4052 SizeString([database_ fetcher].PartialPresent()),
4055 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4057 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4058 initWithTitle:UCLocalize("CANCEL")
4059 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4060 style:UIBarButtonItemStylePlain
4062 action:@selector(cancelButtonClicked)
4067 - (void) applyRightButton {
4068 #if !AlwaysReload && !IgnoreInstall
4069 if (issues_ == nil && ![self isLoading])
4070 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4071 initWithTitle:UCLocalize("CONFIRM")
4072 style:UIBarButtonItemStylePlain
4074 action:@selector(confirmButtonClicked)
4077 [super applyRightButton];
4079 [[self navigationItem] setRightBarButtonItem:nil];
4083 - (void) cancelButtonClicked {
4084 [self dismissModalViewControllerAnimated:YES];
4085 [delegate_ cancelAndClear:YES];
4089 - (void) confirmButtonClicked {
4093 if (essential_ != nil)
4098 [delegate_ confirmWithNavigationController:[self navigationController]];
4106 /* Progress Data {{{ */
4107 @interface ProgressData : NSObject {
4109 // XXX: should these really both be _transient?
4110 _transient id target_;
4111 _transient id object_;
4114 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4121 @implementation ProgressData
4123 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4124 if ((self = [super init]) != nil) {
4125 selector_ = selector;
4145 /* Progress Controller {{{ */
4146 @interface ProgressController : CYViewController <
4147 ConfigurationDelegate,
4150 _transient Database *database_;
4151 UIProgressBar *progress_;
4152 UITextView *output_;
4153 UITextLabel *status_;
4154 UIPushButton *close_;
4156 SHA1SumValue springlist_;
4157 SHA1SumValue notifyconf_;
4161 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4163 - (void) _retachThread;
4164 - (void) _detachNewThreadData:(ProgressData *)data;
4165 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4171 @protocol ProgressControllerDelegate
4172 - (void) progressControllerIsComplete:(ProgressController *)sender;
4175 @implementation ProgressController
4178 [database_ setDelegate:nil];
4179 [progress_ release];
4188 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4189 if ((self = [super init]) != nil) {
4190 database_ = database;
4191 [database_ setDelegate:self];
4192 delegate_ = delegate;
4194 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4196 progress_ = [[UIProgressBar alloc] init];
4197 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4198 [progress_ setStyle:0];
4200 status_ = [[UITextLabel alloc] init];
4201 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4202 [status_ setColor:[UIColor whiteColor]];
4203 [status_ setBackgroundColor:[UIColor clearColor]];
4204 [status_ setCentersHorizontally:YES];
4205 //[status_ setFont:font];
4207 output_ = [[UITextView alloc] init];
4209 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4210 //[output_ setTextFont:@"Courier New"];
4211 [output_ setFont:[[output_ font] fontWithSize:12]];
4212 [output_ setTextColor:[UIColor whiteColor]];
4213 [output_ setBackgroundColor:[UIColor clearColor]];
4214 [output_ setMarginTop:0];
4215 [output_ setAllowsRubberBanding:YES];
4216 [output_ setEditable:NO];
4217 [[self view] addSubview:output_];
4219 close_ = [[UIPushButton alloc] init];
4220 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4221 [close_ setAutosizesToFit:NO];
4222 [close_ setDrawsShadow:YES];
4223 [close_ setStretchBackground:YES];
4224 [close_ setEnabled:YES];
4225 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4226 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4227 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4228 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4232 - (void) positionViews {
4233 CGRect bounds = [[self view] bounds];
4234 CGSize prgsize = [UIProgressBar defaultSize];
4237 (bounds.size.width - prgsize.width) / 2,
4238 bounds.size.height - prgsize.height - 20
4241 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4243 [progress_ setFrame:prgrect];
4244 [status_ setFrame:CGRectMake(
4246 bounds.size.height - prgsize.height - 50,
4247 bounds.size.width - 20,
4250 [output_ setFrame:CGRectMake(
4253 bounds.size.width - 20,
4254 bounds.size.height - 62
4256 [close_ setFrame:CGRectMake(
4257 (bounds.size.width - closewidth) / 2,
4258 bounds.size.height - prgsize.height - 50,
4264 - (void) viewWillAppear:(BOOL)animated {
4265 [super viewDidAppear:animated];
4266 [[self navigationItem] setHidesBackButton:YES];
4267 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4269 [self positionViews];
4272 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4273 [self positionViews];
4276 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4277 NSString *context([alert context]);
4279 if ([context isEqualToString:@"conffile"]) {
4280 FILE *input = [database_ input];
4281 if (button == [alert cancelButtonIndex])
4282 fprintf(input, "N\n");
4283 else if (button == [alert firstOtherButtonIndex])
4284 fprintf(input, "Y\n");
4289 - (void) closeButtonPushed {
4292 UpdateExternalStatus(0);
4296 [self dismissModalViewControllerAnimated:YES];
4300 [delegate_ terminateWithSuccess];
4301 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4302 [delegate_ suspendWithAnimation:YES];
4304 [delegate_ suspend];*/
4308 system("launchctl stop com.apple.SpringBoard");
4312 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4321 - (void) _retachThread {
4322 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4324 [[self view] addSubview:close_];
4325 [progress_ removeFromSuperview];
4326 [status_ removeFromSuperview];
4328 [database_ popErrorWithTitle:title_];
4329 [delegate_ progressControllerIsComplete:self];
4333 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4336 MMap mmap(file, MMap::ReadOnly);
4338 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4339 if (!(notifyconf_ == sha1.Result()))
4346 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4349 MMap mmap(file, MMap::ReadOnly);
4351 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4352 if (!(springlist_ == sha1.Result()))
4358 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4359 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4360 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4361 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4362 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4365 system("su -c /usr/bin/uicache mobile");
4367 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4369 [delegate_ setStatusBarShowsProgress:NO];
4372 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4373 [[data target] performSelector:[data selector] withObject:[data object]];
4374 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4377 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4378 UpdateExternalStatus(1);
4385 title_ = [title retain];
4387 [[self navigationItem] setTitle:title_];
4389 [status_ setText:nil];
4390 [output_ setText:@""];
4391 [progress_ setProgress:0];
4393 [close_ removeFromSuperview];
4394 [[self view] addSubview:progress_];
4395 [[self view] addSubview:status_];
4397 [delegate_ setStatusBarShowsProgress:YES];
4402 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4405 MMap mmap(file, MMap::ReadOnly);
4407 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4408 notifyconf_ = sha1.Result();
4414 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4417 MMap mmap(file, MMap::ReadOnly);
4419 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4420 springlist_ = sha1.Result();
4425 detachNewThreadSelector:@selector(_detachNewThreadData:)
4427 withObject:[[[ProgressData alloc]
4428 initWithSelector:selector
4435 - (void) repairWithSelector:(SEL)selector {
4437 detachNewThreadSelector:selector
4440 title:UCLocalize("REPAIRING")
4444 - (void) setConfigurationData:(NSString *)data {
4446 performSelectorOnMainThread:@selector(_setConfigurationData:)
4452 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4453 CYActionSheet *sheet([[[CYActionSheet alloc]
4455 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4456 defaultButtonIndex:0
4459 [sheet setMessage:error];
4460 [sheet yieldToPopupAlertAnimated:YES];
4464 - (void) setProgressTitle:(NSString *)title {
4466 performSelectorOnMainThread:@selector(_setProgressTitle:)
4472 - (void) setProgressPercent:(float)percent {
4474 performSelectorOnMainThread:@selector(_setProgressPercent:)
4475 withObject:[NSNumber numberWithFloat:percent]
4480 - (void) startProgress {
4483 - (void) addProgressOutput:(NSString *)output {
4485 performSelectorOnMainThread:@selector(_addProgressOutput:)
4491 - (bool) isCancelling:(size_t)received {
4495 - (void) _setConfigurationData:(NSString *)data {
4496 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4498 if (!conffile_r(data)) {
4499 lprintf("E:invalid conffile\n");
4503 NSString *ofile = conffile_r[1];
4504 //NSString *nfile = conffile_r[2];
4506 UIAlertView *alert = [[[UIAlertView alloc]
4507 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4508 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4510 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4511 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4512 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4516 [alert setContext:@"conffile"];
4520 - (void) _setProgressTitle:(NSString *)title {
4521 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4522 for (size_t i(0), e([words count]); i != e; ++i) {
4523 NSString *word([words objectAtIndex:i]);
4524 if (Package *package = [database_ packageWithName:word])
4525 [words replaceObjectAtIndex:i withObject:[package name]];
4528 [status_ setText:[words componentsJoinedByString:@" "]];
4531 - (void) _setProgressPercent:(NSNumber *)percent {
4532 [progress_ setProgress:[percent floatValue]];
4535 - (void) _addProgressOutput:(NSString *)output {
4536 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4537 CGSize size = [output_ contentSize];
4538 CGRect rect = {{0, size.height}, {size.width, 0}};
4539 [output_ scrollRectToVisible:rect animated:YES];
4542 - (BOOL) isRunning {
4549 /* Cell Content View {{{ */
4550 @protocol ContentDelegate
4551 - (void) drawContentRect:(CGRect)rect;
4554 @interface ContentView : UIView {
4555 _transient id<ContentDelegate> delegate_;
4560 @implementation ContentView
4562 - (id) initWithFrame:(CGRect)frame {
4563 if ((self = [super initWithFrame:frame]) != nil) {
4564 [self setNeedsDisplayOnBoundsChange:YES];
4568 - (void) setDelegate:(id<ContentDelegate>)delegate {
4569 delegate_ = delegate;
4572 - (void) drawRect:(CGRect)rect {
4573 [super drawRect:rect];
4574 [delegate_ drawContentRect:rect];
4579 /* Cydia TableView Cell {{{ */
4580 @interface CYTableViewCell : UITableViewCell {
4581 ContentView *content_;
4587 @implementation CYTableViewCell
4594 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4595 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4597 if (view == content_) {
4598 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4599 highlighted_ = highlighted;
4602 [super _updateHighlightColorsForView:view highlighted:highlighted];
4605 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4606 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4607 highlighted_ = selected;
4609 [super setSelected:selected animated:animated];
4610 [content_ setNeedsDisplay];
4615 /* Package Cell {{{ */
4616 @interface PackageCell : CYTableViewCell <
4621 NSString *description_;
4629 - (PackageCell *) init;
4630 - (void) setPackage:(Package *)package;
4632 + (int) heightForPackage:(Package *)package;
4633 - (void) drawContentRect:(CGRect)rect;
4637 @implementation PackageCell
4639 - (void) clearPackage {
4650 if (description_ != nil) {
4651 [description_ release];
4655 if (source_ != nil) {
4660 if (badge_ != nil) {
4665 if (placard_ != nil) {
4675 [self clearPackage];
4679 - (PackageCell *) init {
4680 CGRect frame(CGRectMake(0, 0, 320, 74));
4681 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4682 UIView *content([self contentView]);
4683 CGRect bounds([content bounds]);
4685 content_ = [[ContentView alloc] initWithFrame:bounds];
4686 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4687 [content addSubview:content_];
4689 [content_ setDelegate:self];
4690 [content_ setOpaque:YES];
4694 - (void) _setBackgroundColor {
4696 if (NSString *mode = [package_ mode]) {
4697 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4698 color = remove ? RemovingColor_ : InstallingColor_;
4700 color = [UIColor whiteColor];
4702 [content_ setBackgroundColor:color];
4703 [self setNeedsDisplay];
4706 - (void) setPackage:(Package *)package {
4707 [self clearPackage];
4710 Source *source = [package source];
4712 icon_ = [[package icon] retain];
4713 name_ = [[package name] retain];
4716 description_ = [package longDescription];
4717 if (description_ == nil)
4718 description_ = [package shortDescription];
4719 if (description_ != nil)
4720 description_ = [description_ retain];
4722 commercial_ = [package isCommercial];
4724 package_ = [package retain];
4726 NSString *label = nil;
4727 bool trusted = false;
4729 if (source != nil) {
4730 label = [source label];
4731 trusted = [source trusted];
4732 } else if ([[package id] isEqualToString:@"firmware"])
4733 label = UCLocalize("APPLE");
4735 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4737 NSString *from(label);
4739 NSString *section = [package simpleSection];
4740 if (section != nil && ![section isEqualToString:label]) {
4741 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4742 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4745 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4746 source_ = [from retain];
4748 if (NSString *purpose = [package primaryPurpose])
4749 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4750 badge_ = [badge_ retain];
4752 if ([package installed] != nil)
4753 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4754 placard_ = [placard_ retain];
4756 [self _setBackgroundColor];
4757 [content_ setNeedsDisplay];
4760 - (void) drawContentRect:(CGRect)rect {
4761 bool highlighted(highlighted_);
4762 float width([self bounds].size.width);
4765 CGContextRef context(UIGraphicsGetCurrentContext());
4766 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4767 CGContextFillRect(context, rect);
4772 rect.size = [icon_ size];
4774 rect.size.width /= 2;
4775 rect.size.height /= 2;
4777 rect.origin.x = 25 - rect.size.width / 2;
4778 rect.origin.y = 25 - rect.size.height / 2;
4780 [icon_ drawInRect:rect];
4783 if (badge_ != nil) {
4784 CGSize size = [badge_ size];
4786 [badge_ drawAtPoint:CGPointMake(
4787 36 - size.width / 2,
4788 36 - size.height / 2
4796 UISetColor(commercial_ ? Purple_ : Black_);
4797 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4798 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4801 UISetColor(commercial_ ? Purplish_ : Gray_);
4802 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4804 if (placard_ != nil)
4805 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4808 + (int) heightForPackage:(Package *)package {
4814 /* Section Cell {{{ */
4815 @interface SectionCell : CYTableViewCell <
4827 - (void) setSection:(Section *)section editing:(BOOL)editing;
4831 @implementation SectionCell
4833 - (void) clearSection {
4834 if (basic_ != nil) {
4839 if (section_ != nil) {
4849 if (count_ != nil) {
4856 [self clearSection];
4862 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4863 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4864 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4865 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4866 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4868 UIView *content([self contentView]);
4869 CGRect bounds([content bounds]);
4871 content_ = [[ContentView alloc] initWithFrame:bounds];
4872 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4873 [content addSubview:content_];
4874 [content_ setBackgroundColor:[UIColor whiteColor]];
4876 [content_ setDelegate:self];
4880 - (void) onSwitch:(id)sender {
4881 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4882 if (metadata == nil) {
4883 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4884 [Sections_ setObject:metadata forKey:basic_];
4888 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4891 - (void) setSection:(Section *)section editing:(BOOL)editing {
4892 if (editing != editing_) {
4894 [switch_ removeFromSuperview];
4896 [self addSubview:switch_];
4900 [self clearSection];
4902 if (section == nil) {
4903 name_ = [UCLocalize("ALL_PACKAGES") retain];
4906 basic_ = [section name];
4908 basic_ = [basic_ retain];
4910 section_ = [section localized];
4911 if (section_ != nil)
4912 section_ = [section_ retain];
4914 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4915 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4918 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4921 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4922 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
4924 [content_ setNeedsDisplay];
4927 - (void) setFrame:(CGRect)frame {
4928 [super setFrame:frame];
4930 CGRect rect([switch_ frame]);
4931 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4934 - (void) drawContentRect:(CGRect)rect {
4935 bool highlighted(highlighted_);
4937 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4942 float width(rect.size.width);
4948 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4950 CGSize size = [count_ sizeWithFont:Font14_];
4954 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4960 /* File Table {{{ */
4961 @interface FileTable : CYViewController <
4962 UITableViewDataSource,
4965 _transient Database *database_;
4968 NSMutableArray *files_;
4972 - (id) initWithDatabase:(Database *)database;
4973 - (void) setPackage:(Package *)package;
4977 @implementation FileTable
4980 if (package_ != nil)
4989 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
4990 return files_ == nil ? 0 : [files_ count];
4993 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
4997 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
4998 static NSString *reuseIdentifier = @"Cell";
5000 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5002 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5003 [cell setFont:[UIFont systemFontOfSize:16]];
5005 [cell setText:[files_ objectAtIndex:indexPath.row]];
5006 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5011 - (id) initWithDatabase:(Database *)database {
5012 if ((self = [super init]) != nil) {
5013 database_ = database;
5015 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5017 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5019 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5020 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5021 [list_ setRowHeight:24.0f];
5022 [[self view] addSubview:list_];
5024 [list_ setDataSource:self];
5025 [list_ setDelegate:self];
5029 - (void) setPackage:(Package *)package {
5030 if (package_ != nil) {
5031 [package_ autorelease];
5040 [files_ removeAllObjects];
5042 if (package != nil) {
5043 package_ = [package retain];
5044 name_ = [[package id] retain];
5046 if (NSArray *files = [package files])
5047 [files_ addObjectsFromArray:files];
5049 if ([files_ count] != 0) {
5050 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5051 [files_ removeObjectAtIndex:0];
5052 [files_ sortUsingSelector:@selector(compareByPath:)];
5054 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5055 [stack addObject:@"/"];
5057 for (int i(0), e([files_ count]); i != e; ++i) {
5058 NSString *file = [files_ objectAtIndex:i];
5059 while (![file hasPrefix:[stack lastObject]])
5060 [stack removeLastObject];
5061 NSString *directory = [stack lastObject];
5062 [stack addObject:[file stringByAppendingString:@"/"]];
5063 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5064 ([stack count] - 2) * 3, "",
5065 [file substringFromIndex:[directory length]]
5074 - (void) reloadData {
5075 [self setPackage:[database_ packageWithName:name_]];
5080 /* Package Controller {{{ */
5081 @interface PackageController : CYBrowserController <
5082 UIActionSheetDelegate
5084 _transient Database *database_;
5088 NSMutableArray *buttons_;
5089 UIBarButtonItem *button_;
5092 - (id) initWithDatabase:(Database *)database;
5093 - (void) setPackage:(Package *)package;
5097 @implementation PackageController
5100 if (package_ != nil)
5114 if ([self retainCount] == 1)
5115 [delegate_ setPackageController:self];
5119 /* XXX: this is not safe at all... localization of /fail/ */
5120 - (void) _clickButtonWithName:(NSString *)name {
5121 if ([name isEqualToString:UCLocalize("CLEAR")])
5122 [delegate_ clearPackage:package_];
5123 else if ([name isEqualToString:UCLocalize("INSTALL")])
5124 [delegate_ installPackage:package_];
5125 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5126 [delegate_ installPackage:package_];
5127 else if ([name isEqualToString:UCLocalize("REMOVE")])
5128 [delegate_ removePackage:package_];
5129 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5130 [delegate_ installPackage:package_];
5131 else _assert(false);
5134 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5135 NSString *context([sheet context]);
5137 if ([context isEqualToString:@"modify"]) {
5138 if (button != [sheet cancelButtonIndex]) {
5139 NSString *buttonName = [buttons_ objectAtIndex:button];
5140 [self _clickButtonWithName:buttonName];
5143 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5147 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5148 [super webView:view didClearWindowObject:window forFrame:frame];
5149 [window setValue:package_ forKey:@"package"];
5152 - (bool) _allowJavaScriptPanel {
5157 - (void) _customButtonClicked {
5158 int count([buttons_ count]);
5163 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5165 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5166 [buttons addObjectsFromArray:buttons_];
5168 UIActionSheet *sheet = [[[UIActionSheet alloc]
5171 cancelButtonTitle:nil
5172 destructiveButtonTitle:nil
5173 otherButtonTitles:nil
5176 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5178 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5179 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5181 [sheet setContext:@"modify"];
5183 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5187 // We don't want to allow non-commercial packages to do custom things to the install button,
5188 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5189 - (void) customButtonClicked {
5191 [super customButtonClicked];
5193 [self _customButtonClicked];
5196 - (void) reloadButtonClicked {
5197 // Don't reload a package view by clicking the button.
5200 - (void) applyLoadingTitle {
5201 // Don't show "Loading" as the title. Ever.
5204 - (UIBarButtonItem *) rightButton {
5209 - (id) initWithDatabase:(Database *)database {
5210 if ((self = [super init]) != nil) {
5211 database_ = database;
5212 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5213 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5217 - (void) setPackage:(Package *)package {
5218 if (package_ != nil) {
5219 [package_ autorelease];
5228 [buttons_ removeAllObjects];
5230 if (package != nil) {
5233 package_ = [package retain];
5234 name_ = [[package id] retain];
5235 commercial_ = [package isCommercial];
5237 if ([package_ mode] != nil)
5238 [buttons_ addObject:UCLocalize("CLEAR")];
5239 if ([package_ source] == nil);
5240 else if ([package_ upgradableAndEssential:NO])
5241 [buttons_ addObject:UCLocalize("UPGRADE")];
5242 else if ([package_ uninstalled])
5243 [buttons_ addObject:UCLocalize("INSTALL")];
5245 [buttons_ addObject:UCLocalize("REINSTALL")];
5246 if (![package_ uninstalled])
5247 [buttons_ addObject:UCLocalize("REMOVE")];
5254 switch ([buttons_ count]) {
5255 case 0: title = nil; break;
5256 case 1: title = [buttons_ objectAtIndex:0]; break;
5257 default: title = UCLocalize("MODIFY"); break;
5260 button_ = [[UIBarButtonItem alloc]
5262 style:UIBarButtonItemStylePlain
5264 action:@selector(customButtonClicked)
5270 - (bool) isLoading {
5271 return commercial_ ? [super isLoading] : false;
5274 - (void) reloadData {
5275 [self setPackage:[database_ packageWithName:name_]];
5280 /* Package Table {{{ */
5281 @interface PackageTable : UIView <
5282 UITableViewDataSource,
5285 _transient Database *database_;
5286 NSMutableArray *packages_;
5287 NSMutableArray *sections_;
5289 NSMutableArray *index_;
5290 NSMutableDictionary *indices_;
5291 // XXX: this target_ seems to be delegate_. :(
5292 _transient id target_;
5294 // XXX: why do we even have this delegate_?
5295 _transient id delegate_;
5298 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5300 - (void) setDelegate:(id)delegate;
5302 - (void) reloadData;
5303 - (void) resetCursor;
5305 - (UITableView *) list;
5307 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5309 - (void) deselectWithAnimation:(BOOL)animated;
5313 @implementation PackageTable
5316 [packages_ release];
5317 [sections_ release];
5325 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5326 NSInteger count([sections_ count]);
5327 return count == 0 ? 1 : count;
5330 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5331 if ([sections_ count] == 0)
5333 return [[sections_ objectAtIndex:section] name];
5336 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5337 if ([sections_ count] == 0)
5339 return [[sections_ objectAtIndex:section] count];
5342 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5343 Section *section([sections_ objectAtIndex:[path section]]);
5344 NSInteger row([path row]);
5345 Package *package([packages_ objectAtIndex:([section row] + row)]);
5349 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5350 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5352 cell = [[[PackageCell alloc] init] autorelease];
5353 [cell setPackage:[self packageAtIndexPath:path]];
5357 - (void) deselectWithAnimation:(BOOL)animated {
5358 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5361 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5362 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5365 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5366 Package *package([self packageAtIndexPath:path]);
5367 package = [database_ packageWithName:[package id]];
5368 [target_ performSelector:action_ withObject:package];
5372 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5373 return [packages_ count] > 20 ? index_ : nil;
5376 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5380 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5381 if ((self = [super initWithFrame:frame]) != nil) {
5382 database_ = database;
5387 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5388 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5390 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5391 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5393 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5394 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5395 [list_ setRowHeight:73.0f];
5396 [self addSubview:list_];
5398 [list_ setDataSource:self];
5399 [list_ setDelegate:self];
5403 - (void) setDelegate:(id)delegate {
5404 delegate_ = delegate;
5407 - (bool) hasPackage:(Package *)package {
5411 - (void) reloadData {
5412 NSArray *packages = [database_ packages];
5414 [packages_ removeAllObjects];
5415 [sections_ removeAllObjects];
5417 _profile(PackageTable$reloadData$Filter)
5418 for (Package *package in packages)
5419 if ([self hasPackage:package])
5420 [packages_ addObject:package];
5423 [index_ removeAllObjects];
5424 [indices_ removeAllObjects];
5426 Section *section = nil;
5428 _profile(PackageTable$reloadData$Section)
5429 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5433 _profile(PackageTable$reloadData$Section$Package)
5434 package = [packages_ objectAtIndex:offset];
5435 index = [package index];
5438 if (section == nil || [section index] != index) {
5439 _profile(PackageTable$reloadData$Section$Allocate)
5440 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5443 [index_ addObject:[section name]];
5444 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5446 _profile(PackageTable$reloadData$Section$Add)
5447 [sections_ addObject:section];
5451 [section addToCount];
5455 _profile(PackageTable$reloadData$List)
5460 - (void) resetCursor {
5461 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5464 - (UITableView *) list {
5468 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5469 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5474 /* Filtered Package Table {{{ */
5475 @interface FilteredPackageTable : PackageTable {
5481 - (void) setObject:(id)object;
5482 - (void) setObject:(id)object forFilter:(SEL)filter;
5484 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5488 @implementation FilteredPackageTable
5496 - (void) setFilter:(SEL)filter {
5499 /* XXX: this is an unsafe optimization of doomy hell */
5500 Method method(class_getInstanceMethod([Package class], filter));
5501 _assert(method != NULL);
5502 imp_ = method_getImplementation(method);
5503 _assert(imp_ != NULL);
5506 - (void) setObject:(id)object {
5512 object_ = [object retain];
5515 - (void) setObject:(id)object forFilter:(SEL)filter {
5516 [self setFilter:filter];
5517 [self setObject:object];
5520 - (bool) hasPackage:(Package *)package {
5521 _profile(FilteredPackageTable$hasPackage)
5522 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5526 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5527 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5528 [self setFilter:filter];
5529 object_ = [object retain];
5537 /* Filtered Package Controller {{{ */
5538 @interface FilteredPackageController : CYViewController {
5539 _transient Database *database_;
5540 FilteredPackageTable *packages_;
5544 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5548 @implementation FilteredPackageController
5551 [packages_ release];
5557 - (void) viewDidAppear:(BOOL)animated {
5558 [super viewDidAppear:animated];
5559 [packages_ deselectWithAnimation:animated];
5562 - (void) didSelectPackage:(Package *)package {
5563 PackageController *view([delegate_ packageController]);
5564 [view setPackage:package];
5565 [view setDelegate:delegate_];
5566 [[self navigationController] pushViewController:view animated:YES];
5569 - (NSString *) title { return title_; }
5571 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5572 if ((self = [super init]) != nil) {
5573 database_ = database;
5574 title_ = [title copy];
5575 [[self navigationItem] setTitle:title_];
5577 packages_ = [[FilteredPackageTable alloc]
5578 initWithFrame:[[self view] bounds]
5581 action:@selector(didSelectPackage:)
5586 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5587 [[self view] addSubview:packages_];
5591 - (void) reloadData {
5592 [packages_ reloadData];
5595 - (void) setDelegate:(id)delegate {
5596 [super setDelegate:delegate];
5597 [packages_ setDelegate:delegate];
5604 /* Add Source Controller {{{ */
5605 @interface AddSourceController : CYViewController {
5606 _transient Database *database_;
5609 - (id) initWithDatabase:(Database *)database;
5613 @implementation AddSourceController
5615 - (id) initWithDatabase:(Database *)database {
5616 if ((self = [super init]) != nil) {
5617 database_ = database;
5623 /* Source Cell {{{ */
5624 @interface SourceCell : CYTableViewCell <
5629 NSString *description_;
5633 - (void) setSource:(Source *)source;
5637 @implementation SourceCell
5639 - (void) clearSource {
5642 [description_ release];
5651 - (void) setSource:(Source *)source {
5655 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5657 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5658 icon_ = [icon_ retain];
5660 origin_ = [[source name] retain];
5661 label_ = [[source uri] retain];
5662 description_ = [[source description] retain];
5664 [content_ setNeedsDisplay];
5672 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5673 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5674 UIView *content([self contentView]);
5675 CGRect bounds([content bounds]);
5677 content_ = [[ContentView alloc] initWithFrame:bounds];
5678 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5679 [content_ setBackgroundColor:[UIColor whiteColor]];
5680 [content addSubview:content_];
5682 [content_ setDelegate:self];
5683 [content_ setOpaque:YES];
5687 - (void) drawContentRect:(CGRect)rect {
5688 bool highlighted(highlighted_);
5689 float width(rect.size.width);
5692 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5699 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5703 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5707 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5712 /* Source Table {{{ */
5713 @interface SourceTable : CYViewController <
5714 UITableViewDataSource,
5717 _transient Database *database_;
5719 NSMutableArray *sources_;
5723 UIProgressHUD *hud_;
5726 //NSURLConnection *installer_;
5727 NSURLConnection *trivial_;
5728 NSURLConnection *trivial_bz2_;
5729 NSURLConnection *trivial_gz_;
5730 //NSURLConnection *automatic_;
5735 - (id) initWithDatabase:(Database *)database;
5737 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5741 @implementation SourceTable
5743 - (void) _releaseConnection:(NSURLConnection *)connection {
5744 if (connection != nil) {
5745 [connection cancel];
5746 //[connection setDelegate:nil];
5747 [connection release];
5759 //[self _releaseConnection:installer_];
5760 [self _releaseConnection:trivial_];
5761 [self _releaseConnection:trivial_gz_];
5762 [self _releaseConnection:trivial_bz2_];
5763 //[self _releaseConnection:automatic_];
5770 - (void) viewDidAppear:(BOOL)animated {
5771 [super viewDidAppear:animated];
5772 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5775 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5776 return offset_ == 0 ? 1 : 2;
5779 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5780 switch (section + (offset_ == 0 ? 1 : 0)) {
5781 case 0: return UCLocalize("ENTERED_BY_USER");
5782 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5788 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5789 int count = [sources_ count];
5791 case 0: return (offset_ == 0 ? count : offset_);
5792 case 1: return count - offset_;
5798 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5800 switch (indexPath.section) {
5801 case 0: idx = indexPath.row; break;
5802 case 1: idx = indexPath.row + offset_; break;
5806 return [sources_ objectAtIndex:idx];
5809 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5810 Source *source = [self sourceAtIndexPath:indexPath];
5811 return [source description] == nil ? 56 : 73;
5814 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5815 static NSString *cellIdentifier = @"SourceCell";
5817 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5818 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5819 [cell setSource:[self sourceAtIndexPath:indexPath]];
5824 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5825 return UITableViewCellAccessoryDisclosureIndicator;
5828 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5829 Source *source = [self sourceAtIndexPath:indexPath];
5831 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5832 initWithDatabase:database_
5833 title:[source label]
5834 filter:@selector(isVisibleInSource:)
5838 [packages setDelegate:delegate_];
5840 [[self navigationController] pushViewController:packages animated:YES];
5843 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5844 Source *source = [self sourceAtIndexPath:indexPath];
5845 return [source record] != nil;
5848 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5849 Source *source = [self sourceAtIndexPath:indexPath];
5850 [Sources_ removeObjectForKey:[source key]];
5851 [delegate_ syncData];
5855 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5858 @"./", @"Distribution",
5859 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5861 [delegate_ syncData];
5864 - (NSString *) getWarning {
5865 NSString *href(href_);
5866 NSRange colon([href rangeOfString:@"://"]);
5867 if (colon.location != NSNotFound)
5868 href = [href substringFromIndex:(colon.location + 3)];
5869 href = [href stringByAddingPercentEscapes];
5870 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5871 href = [href stringByCachingURLWithCurrentCDN];
5873 NSURL *url([NSURL URLWithString:href]);
5875 NSStringEncoding encoding;
5876 NSError *error(nil);
5878 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5879 return [warning length] == 0 ? nil : warning;
5883 - (void) _endConnection:(NSURLConnection *)connection {
5884 // XXX: the memory management in this method is horribly awkward
5886 NSURLConnection **field = NULL;
5887 if (connection == trivial_)
5889 else if (connection == trivial_bz2_)
5890 field = &trivial_bz2_;
5891 else if (connection == trivial_gz_)
5892 field = &trivial_gz_;
5893 _assert(field != NULL);
5894 [connection release];
5899 trivial_bz2_ == nil &&
5905 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5908 UIAlertView *alert = [[[UIAlertView alloc]
5909 initWithTitle:UCLocalize("SOURCE_WARNING")
5912 cancelButtonTitle:UCLocalize("CANCEL")
5913 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5916 [alert setContext:@"warning"];
5917 [alert setNumberOfRows:1];
5921 } else if (error_ != nil) {
5922 UIAlertView *alert = [[[UIAlertView alloc]
5923 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5924 message:[error_ localizedDescription]
5926 cancelButtonTitle:UCLocalize("OK")
5927 otherButtonTitles:nil
5930 [alert setContext:@"urlerror"];
5933 UIAlertView *alert = [[[UIAlertView alloc]
5934 initWithTitle:UCLocalize("NOT_REPOSITORY")
5935 message:UCLocalize("NOT_REPOSITORY_EX")
5937 cancelButtonTitle:UCLocalize("OK")
5938 otherButtonTitles:nil
5941 [alert setContext:@"trivial"];
5945 [delegate_ setStatusBarShowsProgress:NO];
5946 [delegate_ removeProgressHUD:hud_];
5956 if (error_ != nil) {
5963 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5964 switch ([response statusCode]) {
5970 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5971 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5973 error_ = [error retain];
5974 [self _endConnection:connection];
5977 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5978 [self _endConnection:connection];
5981 - (NSString *) title { return UCLocalize("SOURCES"); }
5983 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5984 NSMutableURLRequest *request = [NSMutableURLRequest
5985 requestWithURL:[NSURL URLWithString:href]
5986 cachePolicy:NSURLRequestUseProtocolCachePolicy
5987 timeoutInterval:120.0
5990 [request setHTTPMethod:method];
5992 if (Machine_ != NULL)
5993 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5994 if (UniqueID_ != nil)
5995 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5997 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5999 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6002 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6003 NSString *context([alert context]);
6005 if ([context isEqualToString:@"source"]) {
6008 NSString *href = [[alert textField] text];
6010 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6012 if (![href hasSuffix:@"/"])
6013 href_ = [href stringByAppendingString:@"/"];
6016 href_ = [href_ retain];
6018 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6019 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6020 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6021 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6025 // XXX: this is stupid
6026 hud_ = [[delegate_ addProgressHUD] retain];
6027 [hud_ setText:UCLocalize("VERIFYING_URL")];
6036 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6037 } else if ([context isEqualToString:@"trivial"])
6038 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6039 else if ([context isEqualToString:@"urlerror"])
6040 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6041 else if ([context isEqualToString:@"warning"]) {
6056 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6060 - (id) initWithDatabase:(Database *)database {
6061 if ((self = [super init]) != nil) {
6062 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6063 [self updateButtonsForEditingStatus:NO animated:NO];
6065 database_ = database;
6066 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6068 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6069 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6070 [[self view] addSubview:list_];
6072 [list_ setDataSource:self];
6073 [list_ setDelegate:self];
6079 - (void) reloadData {
6081 if (!list.ReadMainList())
6084 [sources_ removeAllObjects];
6085 [sources_ addObjectsFromArray:[database_ sources]];
6087 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6090 int count([sources_ count]);
6092 for (int i = 0; i != count; i++) {
6093 if ([[sources_ objectAtIndex:i] record] == nil)
6098 [list_ setEditing:NO];
6099 [self updateButtonsForEditingStatus:NO animated:NO];
6103 - (void) addButtonClicked {
6104 /*[book_ pushPage:[[[AddSourceController alloc]
6109 UIAlertView *alert = [[[UIAlertView alloc]
6110 initWithTitle:UCLocalize("ENTER_APT_URL")
6113 cancelButtonTitle:UCLocalize("CANCEL")
6114 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6117 [alert setContext:@"source"];
6118 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6120 [alert setNumberOfRows:1];
6121 [alert addTextFieldWithValue:@"http://" label:@""];
6123 UITextInputTraits *traits = [[alert textField] textInputTraits];
6124 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6125 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6126 [traits setKeyboardType:UIKeyboardTypeURL];
6127 // XXX: UIReturnKeyDone
6128 [traits setReturnKeyType:UIReturnKeyNext];
6133 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6134 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6135 initWithTitle:UCLocalize("ADD")
6136 style:UIBarButtonItemStylePlain
6138 action:@selector(addButtonClicked)
6139 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6141 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6142 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6143 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6145 action:@selector(editButtonClicked)
6146 ] autorelease] animated:animated];
6148 if (IsWildcat_ && !editing)
6149 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6150 initWithTitle:UCLocalize("SETTINGS")
6151 style:UIBarButtonItemStylePlain
6153 action:@selector(settingsButtonClicked)
6157 - (void) settingsButtonClicked {
6158 [delegate_ showSettings];
6161 - (void) editButtonClicked {
6162 [list_ setEditing:![list_ isEditing] animated:YES];
6164 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6170 /* Installed Controller {{{ */
6171 @interface InstalledController : FilteredPackageController {
6175 - (id) initWithDatabase:(Database *)database;
6177 - (void) updateRoleButton;
6178 - (void) queueStatusDidChange;
6182 @implementation InstalledController
6188 - (NSString *) title { return UCLocalize("INSTALLED"); }
6190 - (id) initWithDatabase:(Database *)database {
6191 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
6192 [self updateRoleButton];
6193 [self queueStatusDidChange];
6198 - (void) queueButtonClicked {
6203 - (void) queueStatusDidChange {
6207 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6208 initWithTitle:UCLocalize("QUEUE")
6209 style:UIBarButtonItemStyleDone
6211 action:@selector(queueButtonClicked)
6214 [[self navigationItem] setLeftBarButtonItem:nil];
6220 - (void) reloadData {
6221 [packages_ reloadData];
6224 - (void) updateRoleButton {
6225 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6226 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6227 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6228 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6230 action:@selector(roleButtonClicked)
6234 - (void) roleButtonClicked {
6235 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6236 [packages_ reloadData];
6239 [self updateRoleButton];
6242 - (void) setDelegate:(id)delegate {
6243 [super setDelegate:delegate];
6244 [packages_ setDelegate:delegate];
6250 /* Home Controller {{{ */
6251 @interface HomeController : CYBrowserController {
6256 @implementation HomeController
6258 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6259 [super _setMoreHeaders:request];
6262 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6263 if (UniqueID_ != nil)
6264 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6266 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6269 - (void) aboutButtonClicked {
6270 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6272 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6273 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6274 [alert setCancelButtonIndex:0];
6277 @"Copyright (C) 2008-2010\n"
6278 "Jay Freeman (saurik)\n"
6279 "saurik@saurik.com\n"
6280 "http://www.saurik.com/"
6286 - (void) viewWillAppear:(BOOL)animated {
6287 [super viewWillAppear:animated];
6288 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6291 - (void) viewWillDisappear:(BOOL)animated {
6292 [super viewWillDisappear:animated];
6293 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6297 if ((self = [super init]) != nil) {
6298 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6299 initWithTitle:UCLocalize("ABOUT")
6300 style:UIBarButtonItemStylePlain
6302 action:@selector(aboutButtonClicked)
6309 /* Manage Controller {{{ */
6310 @interface ManageController : CYBrowserController {
6313 - (void) queueStatusDidChange;
6316 @implementation ManageController
6319 if ((self = [super init]) != nil) {
6320 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6322 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6323 initWithTitle:UCLocalize("SETTINGS")
6324 style:UIBarButtonItemStylePlain
6326 action:@selector(settingsButtonClicked)
6329 [self queueStatusDidChange];
6333 - (void) settingsButtonClicked {
6334 [delegate_ showSettings];
6338 - (void) queueButtonClicked {
6342 - (void) applyLoadingTitle {
6343 // No "Loading" title.
6346 - (void) applyRightButton {
6351 - (void) queueStatusDidChange {
6353 if (!IsWildcat_ && Queuing_) {
6354 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6355 initWithTitle:UCLocalize("QUEUE")
6356 style:UIBarButtonItemStyleDone
6358 action:@selector(queueButtonClicked)
6361 [[self navigationItem] setRightBarButtonItem:nil];
6366 - (bool) isLoading {
6373 /* Refresh Bar {{{ */
6374 @interface RefreshBar : UINavigationBar {
6375 UIProgressIndicator *indicator_;
6376 UITextLabel *prompt_;
6377 UIProgressBar *progress_;
6378 UINavigationButton *cancel_;
6383 @implementation RefreshBar
6386 [indicator_ release];
6388 [progress_ release];
6393 - (void) positionViews {
6394 CGRect frame = [cancel_ frame];
6395 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6396 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6397 [cancel_ setFrame:frame];
6399 CGSize prgsize = {75, 100};
6401 [self frame].size.width - prgsize.width - 10,
6402 ([self frame].size.height - prgsize.height) / 2
6404 [progress_ setFrame:prgrect];
6406 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6407 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6408 CGRect indrect = {{indoffset, indoffset}, indsize};
6409 [indicator_ setFrame:indrect];
6411 CGSize prmsize = {215, indsize.height + 4};
6413 indoffset * 2 + indsize.width,
6414 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6416 [prompt_ setFrame:prmrect];
6419 - (void)setFrame:(CGRect)frame {
6420 [super setFrame:frame];
6422 [self positionViews];
6425 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6426 if ((self = [super initWithFrame:frame])) {
6427 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6429 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6430 [self setBarStyle:UIBarStyleBlack];
6432 UIBarStyle barstyle([self _barStyle:NO]);
6433 bool ugly(barstyle == UIBarStyleDefault);
6435 UIProgressIndicatorStyle style = ugly ?
6436 UIProgressIndicatorStyleMediumBrown :
6437 UIProgressIndicatorStyleMediumWhite;
6439 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6440 [indicator_ setStyle:style];
6441 [indicator_ startAnimation];
6442 [self addSubview:indicator_];
6444 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6445 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6446 [prompt_ setBackgroundColor:[UIColor clearColor]];
6447 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6448 [self addSubview:prompt_];
6450 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6451 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6452 [progress_ setStyle:0];
6453 [self addSubview:progress_];
6455 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6456 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6457 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6458 [cancel_ setBarStyle:barstyle];
6460 [self positionViews];
6465 [cancel_ removeFromSuperview];
6469 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6470 [progress_ setProgress:0];
6471 [self addSubview:cancel_];
6475 [cancel_ removeFromSuperview];
6478 - (void) setPrompt:(NSString *)prompt {
6479 [prompt_ setText:prompt];
6482 - (void) setProgress:(float)progress {
6483 [progress_ setProgress:progress];
6489 @class CYNavigationController;
6491 /* Cydia Tab Bar Controller {{{ */
6492 @interface CYTabBarController : UITabBarController {
6493 _transient Database *database_;
6498 @implementation CYTabBarController
6500 /* XXX: some logic should probably go here related to
6501 freeing the view controllers on tab change */
6503 - (void) reloadData {
6504 size_t count([[self viewControllers] count]);
6505 for (size_t i(0); i != count; ++i) {
6506 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6511 - (id) initWithDatabase:(Database *)database {
6512 if ((self = [super init]) != nil) {
6513 database_ = database;
6520 /* Cydia Navigation Controller {{{ */
6521 @interface CYNavigationController : UINavigationController {
6522 _transient Database *database_;
6523 _transient id<UINavigationControllerDelegate> delegate_;
6526 - (id) initWithDatabase:(Database *)database;
6527 - (void) reloadData;
6532 @implementation CYNavigationController
6534 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6535 // Inherit autorotation settings for modal parents.
6536 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6537 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6539 return [super shouldAutorotateToInterfaceOrientation:orientation];
6547 - (void) reloadData {
6548 size_t count([[self viewControllers] count]);
6549 for (size_t i(0); i != count; ++i) {
6550 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6555 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6556 delegate_ = delegate;
6559 - (id) initWithDatabase:(Database *)database {
6560 if ((self = [super init]) != nil) {
6561 database_ = database;
6567 /* Cydia:// Protocol {{{ */
6568 @interface CydiaURLProtocol : NSURLProtocol {
6573 @implementation CydiaURLProtocol
6575 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6576 NSURL *url([request URL]);
6579 NSString *scheme([[url scheme] lowercaseString]);
6580 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6585 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6589 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6590 id<NSURLProtocolClient> client([self client]);
6592 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6594 NSData *data(UIImagePNGRepresentation(icon));
6596 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6597 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6598 [client URLProtocol:self didLoadData:data];
6599 [client URLProtocolDidFinishLoading:self];
6603 - (void) startLoading {
6604 id<NSURLProtocolClient> client([self client]);
6605 NSURLRequest *request([self request]);
6607 NSURL *url([request URL]);
6608 NSString *href([url absoluteString]);
6610 NSString *path([href substringFromIndex:8]);
6611 NSRange slash([path rangeOfString:@"/"]);
6614 if (slash.location == NSNotFound) {
6618 command = [path substringToIndex:slash.location];
6619 path = [path substringFromIndex:(slash.location + 1)];
6622 Database *database([Database sharedInstance]);
6624 if ([command isEqualToString:@"package-icon"]) {
6627 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6628 Package *package([database packageWithName:path]);
6631 UIImage *icon([package icon]);
6632 [self _returnPNGWithImage:icon forRequest:request];
6633 } else if ([command isEqualToString:@"source-icon"]) {
6636 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6637 NSString *source(Simplify(path));
6638 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6640 icon = [UIImage applicationImageNamed:@"unknown.png"];
6641 [self _returnPNGWithImage:icon forRequest:request];
6642 } else if ([command isEqualToString:@"uikit-image"]) {
6645 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6646 UIImage *icon(_UIImageWithName(path));
6647 [self _returnPNGWithImage:icon forRequest:request];
6648 } else if ([command isEqualToString:@"section-icon"]) {
6651 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6652 NSString *section(Simplify(path));
6653 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6655 icon = [UIImage applicationImageNamed:@"unknown.png"];
6656 [self _returnPNGWithImage:icon forRequest:request];
6658 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6662 - (void) stopLoading {
6668 /* Sections Controller {{{ */
6669 @interface SectionsController : CYViewController <
6670 UITableViewDataSource,
6673 _transient Database *database_;
6674 NSMutableArray *sections_;
6675 NSMutableArray *filtered_;
6681 - (id) initWithDatabase:(Database *)database;
6682 - (void) reloadData;
6685 - (void) editButtonClicked;
6689 @implementation SectionsController
6692 [list_ setDataSource:nil];
6693 [list_ setDelegate:nil];
6695 [sections_ release];
6696 [filtered_ release];
6698 [accessory_ release];
6702 - (void) viewDidAppear:(BOOL)animated {
6703 [super viewDidAppear:animated];
6704 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6707 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6708 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6712 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6713 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6716 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6720 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6721 static NSString *reuseIdentifier = @"SectionCell";
6723 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6725 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6727 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6732 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6736 Section *section = [self sectionAtIndexPath:indexPath];
6737 NSString *name = [section name];
6740 if ([indexPath row] == 0) {
6743 title = UCLocalize("ALL_PACKAGES");
6746 name = [NSString stringWithString:name];
6747 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6750 title = UCLocalize("NO_SECTION");
6754 FilteredPackageController *table = [[[FilteredPackageController alloc]
6755 initWithDatabase:database_
6757 filter:@selector(isVisibleInSection:)
6761 [table setDelegate:delegate_];
6763 [[self navigationController] pushViewController:table animated:YES];
6766 - (NSString *) title { return UCLocalize("SECTIONS"); }
6768 - (id) initWithDatabase:(Database *)database {
6769 if ((self = [super init]) != nil) {
6770 database_ = database;
6772 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6774 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6775 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6777 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6778 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6779 [list_ setRowHeight:45.0f];
6780 [[self view] addSubview:list_];
6782 [list_ setDataSource:self];
6783 [list_ setDelegate:self];
6789 - (void) reloadData {
6790 NSArray *packages = [database_ packages];
6792 [sections_ removeAllObjects];
6793 [filtered_ removeAllObjects];
6795 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6798 for (Package *package in packages) {
6799 NSString *name([package section]);
6800 NSString *key(name == nil ? @"" : name);
6804 _profile(SectionsView$reloadData$Section)
6805 section = [sections objectForKey:key];
6806 if (section == nil) {
6807 _profile(SectionsView$reloadData$Section$Allocate)
6808 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6809 [sections setObject:section forKey:key];
6814 [section addToCount];
6816 _profile(SectionsView$reloadData$Filter)
6817 if (![package valid] || ![package visible])
6825 [sections_ addObjectsFromArray:[sections allValues]];
6827 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6829 for (Section *section in sections_) {
6830 size_t count([section row]);
6834 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6835 [section setCount:count];
6836 [filtered_ addObject:section];
6839 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6840 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
6841 style:UIBarButtonItemStylePlain
6843 action:@selector(editButtonClicked)
6844 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6850 - (void) resetView {
6852 [self editButtonClicked];
6855 - (void) editButtonClicked {
6856 if ((editing_ = !editing_))
6859 [delegate_ updateData];
6861 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6862 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6863 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6866 - (UIView *) accessoryView {
6872 /* Changes Controller {{{ */
6873 @interface ChangesController : CYViewController <
6874 UITableViewDataSource,
6877 _transient Database *database_;
6878 CFMutableArrayRef packages_;
6879 NSMutableArray *sections_;
6882 BOOL hasSentFirstLoad_;
6885 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6886 - (void) reloadData;
6890 @implementation ChangesController
6893 [list_ setDelegate:nil];
6894 [list_ setDataSource:nil];
6896 CFRelease(packages_);
6898 [sections_ release];
6903 - (void) viewDidAppear:(BOOL)animated {
6904 [super viewDidAppear:animated];
6905 if (!hasSentFirstLoad_) {
6906 hasSentFirstLoad_ = YES;
6907 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6909 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6913 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6914 NSInteger count([sections_ count]);
6915 return count == 0 ? 1 : count;
6918 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6919 if ([sections_ count] == 0)
6921 return [[sections_ objectAtIndex:section] name];
6924 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6925 if ([sections_ count] == 0)
6927 return [[sections_ objectAtIndex:section] count];
6930 - (Package *) packageAtIndex:(NSUInteger)index {
6931 return (Package *) CFArrayGetValueAtIndex(packages_, index);
6934 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6935 Section *section([sections_ objectAtIndex:[path section]]);
6936 NSInteger row([path row]);
6937 return [self packageAtIndex:([section row] + row)];
6940 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6941 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6943 cell = [[[PackageCell alloc] init] autorelease];
6944 [cell setPackage:[self packageAtIndexPath:path]];
6948 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
6949 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
6952 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6953 Package *package([self packageAtIndexPath:path]);
6954 PackageController *view([delegate_ packageController]);
6955 [view setDelegate:delegate_];
6956 [view setPackage:package];
6957 [[self navigationController] pushViewController:view animated:YES];
6961 - (void) refreshButtonClicked {
6962 [delegate_ beginUpdate];
6963 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
6966 - (void) upgradeButtonClicked {
6967 [delegate_ distUpgrade];
6970 - (NSString *) title { return UCLocalize("CHANGES"); }
6972 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
6973 if ((self = [super init]) != nil) {
6974 database_ = database;
6975 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
6977 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
6979 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6981 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6982 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6983 [list_ setRowHeight:73.0f];
6984 [[self view] addSubview:list_];
6986 [list_ setDataSource:self];
6987 [list_ setDelegate:self];
6989 delegate_ = delegate;
6993 - (void) _reloadPackages:(NSArray *)packages {
6995 for (Package *package in packages)
6996 if ([package upgradableAndEssential:YES] || [package visible])
6997 CFArrayAppendValue(packages_, package);
7000 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7004 - (void) reloadData {
7005 NSArray *packages = [database_ packages];
7007 CFArrayRemoveAllValues(packages_);
7009 [sections_ removeAllObjects];
7012 UIProgressHUD *hud([delegate_ addProgressHUD]);
7013 [hud setText:UCLocalize("LOADING")];
7014 //NSLog(@"HUD:%@::%@", delegate_, hud);
7015 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7016 [delegate_ removeProgressHUD:hud];
7018 [self _reloadPackages:packages];
7021 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7022 Section *ignored = nil;
7023 Section *section = nil;
7027 bool unseens = false;
7029 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7031 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7032 Package *package = [self packageAtIndex:offset];
7034 BOOL uae = [package upgradableAndEssential:YES];
7040 _profile(ChangesController$reloadData$Remember)
7041 seen = [package seen];
7044 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7049 name = UCLocalize("UNKNOWN");
7051 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7055 _profile(ChangesController$reloadData$Allocate)
7056 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7057 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7058 [sections_ addObject:section];
7062 [section addToCount];
7063 } else if ([package ignored]) {
7064 if (ignored == nil) {
7065 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7067 [ignored addToCount];
7070 [upgradable addToCount];
7075 CFRelease(formatter);
7078 Section *last = [sections_ lastObject];
7079 size_t count = [last count];
7080 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7081 [sections_ removeLastObject];
7084 if ([ignored count] != 0)
7085 [sections_ insertObject:ignored atIndex:0];
7087 [sections_ insertObject:upgradable atIndex:0];
7092 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7093 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7094 style:UIBarButtonItemStylePlain
7096 action:@selector(upgradeButtonClicked)
7099 if (![delegate_ updating])
7100 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7101 initWithTitle:UCLocalize("REFRESH")
7102 style:UIBarButtonItemStylePlain
7104 action:@selector(refreshButtonClicked)
7110 /* Search Controller {{{ */
7111 @interface SearchController : FilteredPackageController <
7114 UISearchBar *search_;
7117 - (id) initWithDatabase:(Database *)database;
7118 - (void) reloadData;
7122 @implementation SearchController
7129 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7130 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7131 [search_ resignFirstResponder];
7135 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7136 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7140 - (NSString *) title { return nil; }
7142 - (id) initWithDatabase:(Database *)database {
7143 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7146 - (void)viewDidAppear:(BOOL)animated {
7147 [super viewDidAppear:animated];
7149 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7150 [search_ layoutSubviews];
7151 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7152 UITextField *textField = [search_ searchField];
7153 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7154 [search_ setDelegate:self];
7155 [textField setEnablesReturnKeyAutomatically:NO];
7156 [[self navigationItem] setTitleView:textField];
7160 - (void) _reloadData {
7163 - (void) reloadData {
7164 _profile(SearchController$reloadData)
7165 [packages_ reloadData];
7168 [packages_ resetCursor];
7171 - (void) didSelectPackage:(Package *)package {
7172 [search_ resignFirstResponder];
7173 [super didSelectPackage:package];
7178 /* Settings Controller {{{ */
7179 @interface SettingsController : CYViewController <
7180 UITableViewDataSource,
7183 _transient Database *database_;
7186 UITableView *table_;
7187 UISwitch *subscribedSwitch_;
7188 UISwitch *ignoredSwitch_;
7189 UITableViewCell *subscribedCell_;
7190 UITableViewCell *ignoredCell_;
7193 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7197 @implementation SettingsController
7201 if (package_ != nil)
7204 [subscribedSwitch_ release];
7205 [ignoredSwitch_ release];
7206 [subscribedCell_ release];
7207 [ignoredCell_ release];
7212 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7213 if (package_ == nil)
7219 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7220 if (package_ == nil)
7226 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7227 return UCLocalize("SHOW_ALL_CHANGES_EX");
7230 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7231 if (package_ == nil)
7234 NSMutableDictionary *metadata([package_ metadata]);
7237 if (NSNumber *number = [metadata objectForKey:key])
7238 before = [number boolValue];
7242 if (value != before) {
7243 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7245 [delegate_ updateData];
7249 - (void) onSubscribed:(id)control {
7250 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7253 - (void) onIgnored:(id)control {
7254 // TODO: set Held state - possibly call out to dpkg, etc.
7257 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7258 if (package_ == nil)
7261 switch ([indexPath row]) {
7262 case 0: return subscribedCell_;
7263 case 1: return ignoredCell_;
7271 - (NSString *) title { return UCLocalize("SETTINGS"); }
7273 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7274 if ((self = [super init])) {
7275 database_ = database;
7276 name_ = [package retain];
7278 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7280 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7281 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7282 [[self view] addSubview:table_];
7284 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7285 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7286 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7288 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7289 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7290 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7292 subscribedCell_ = [[UITableViewCell alloc] init];
7293 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7294 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7295 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7297 ignoredCell_ = [[UITableViewCell alloc] init];
7298 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7299 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7300 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7302 [table_ setDataSource:self];
7303 [table_ setDelegate:self];
7308 - (void) reloadData {
7309 if (package_ != nil)
7310 [package_ autorelease];
7311 package_ = [database_ packageWithName:name_];
7312 if (package_ != nil) {
7314 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7315 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7318 [table_ reloadData];
7323 /* Signature Controller {{{ */
7324 @interface SignatureController : CYBrowserController {
7325 _transient Database *database_;
7329 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7333 @implementation SignatureController
7340 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7342 [super webView:view didClearWindowObject:window forFrame:frame];
7345 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7346 if ((self = [super init]) != nil) {
7347 database_ = database;
7348 package_ = [package retain];
7353 - (void) reloadData {
7354 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7360 /* Role Controller {{{ */
7361 @interface RoleController : CYViewController <
7362 UITableViewDataSource,
7365 _transient Database *database_;
7366 // XXX: ok, "roledelegate_"?...
7367 _transient id roledelegate_;
7368 UITableView *table_;
7369 UISegmentedControl *segment_;
7373 - (void) showDoneButton;
7374 - (void) resizeSegmentedControl;
7378 @implementation RoleController
7382 [container_ release];
7387 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7388 if ((self = [super init])) {
7389 database_ = database;
7390 roledelegate_ = delegate;
7392 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7394 NSArray *items = [NSArray arrayWithObjects:
7396 UCLocalize("HACKER"),
7397 UCLocalize("DEVELOPER"),
7399 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7400 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7401 [container_ addSubview:segment_];
7404 if ([Role_ isEqualToString:@"User"]) index = 0;
7405 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7406 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7408 [segment_ setSelectedSegmentIndex:index];
7409 [self showDoneButton];
7412 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7413 [self resizeSegmentedControl];
7415 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7416 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7417 [table_ setDelegate:self];
7418 [table_ setDataSource:self];
7419 [[self view] addSubview:table_];
7420 [table_ reloadData];
7424 - (void) resizeSegmentedControl {
7425 CGFloat width = [[self view] frame].size.width;
7426 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7429 - (void) viewWillAppear:(BOOL)animated {
7430 [super viewWillAppear:animated];
7432 [self resizeSegmentedControl];
7435 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7436 [self resizeSegmentedControl];
7439 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7440 [self resizeSegmentedControl];
7444 NSString *role(nil);
7446 switch ([segment_ selectedSegmentIndex]) {
7447 case 0: role = @"User"; break;
7448 case 1: role = @"Hacker"; break;
7449 case 2: role = @"Developer"; break;
7454 if (![role isEqualToString:Role_]) {
7455 bool rolling(Role_ == nil);
7458 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7462 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7467 [roledelegate_ loadData];
7469 [roledelegate_ updateData];
7473 - (void) segmentChanged:(UISegmentedControl *)control {
7474 [self showDoneButton];
7477 - (void) saveAndClose {
7480 [[self navigationItem] setRightBarButtonItem:nil];
7481 [[self navigationController] dismissModalViewControllerAnimated:YES];
7484 - (void) doneButtonClicked {
7485 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7486 [spinner startAnimating];
7487 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7488 [[self navigationItem] setRightBarButtonItem:spinItem];
7490 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7493 - (void) showDoneButton {
7494 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7495 initWithTitle:UCLocalize("DONE")
7496 style:UIBarButtonItemStyleDone
7498 action:@selector(doneButtonClicked)
7499 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
7502 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7503 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7507 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7511 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7512 return nil; // This method is required by the protocol.
7515 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7517 return UCLocalize("ROLE_EX");
7519 return [NSString stringWithFormat:
7520 @"%@: %@\n%@: %@\n%@: %@",
7521 UCLocalize("USER"), UCLocalize("USER_EX"),
7522 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7523 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7528 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7529 return section == 3 ? 44.0f : 0;
7532 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7533 return section == 3 ? container_ : nil;
7538 /* Stash Controller {{{ */
7539 @interface CYStashController : CYViewController {
7540 // XXX: just delete these things
7541 _transient UIActivityIndicatorView *spinner_;
7542 _transient UILabel *status_;
7543 _transient UILabel *caption_;
7547 @implementation CYStashController
7549 if ((self = [super init])) {
7550 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7552 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
7553 CGRect spinrect = [spinner_ frame];
7554 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7555 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7556 [spinner_ setFrame:spinrect];
7557 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7558 [[self view] addSubview:spinner_];
7559 [spinner_ startAnimating];
7562 captrect.size.width = [[self view] frame].size.width;
7563 captrect.size.height = 40.0f;
7564 captrect.origin.x = 0;
7565 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7566 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
7567 [caption_ setText:@"Initializing Filesystem"];
7568 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7569 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7570 [caption_ setTextColor:[UIColor whiteColor]];
7571 [caption_ setBackgroundColor:[UIColor clearColor]];
7572 [caption_ setShadowColor:[UIColor blackColor]];
7573 [caption_ setTextAlignment:UITextAlignmentCenter];
7574 [[self view] addSubview:caption_];
7577 statusrect.size.width = [[self view] frame].size.width;
7578 statusrect.size.height = 30.0f;
7579 statusrect.origin.x = 0;
7580 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7581 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
7582 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7583 [status_ setText:@"(Cydia will exit when complete.)"];
7584 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7585 [status_ setTextColor:[UIColor whiteColor]];
7586 [status_ setBackgroundColor:[UIColor clearColor]];
7587 [status_ setShadowColor:[UIColor blackColor]];
7588 [status_ setTextAlignment:UITextAlignmentCenter];
7589 [[self view] addSubview:status_];
7593 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7594 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7599 /* Cydia Container {{{ */
7600 @interface CYContainer : UIViewController <ProgressDelegate> {
7601 _transient Database *database_;
7602 RefreshBar *refreshbar_;
7606 // XXX: ok, "updatedelegate_"?...
7607 _transient NSObject<CydiaDelegate> *updatedelegate_;
7608 // XXX: can't we query for this variable when we need it?
7609 _transient UITabBarController *root_;
7612 - (void) setTabBarController:(UITabBarController *)controller;
7614 - (void) dropBar:(BOOL)animated;
7615 - (void) beginUpdate;
7616 - (void) raiseBar:(BOOL)animated;
7621 @implementation CYContainer
7623 - (BOOL) _reallyWantsFullScreenLayout {
7627 // NOTE: UIWindow only sends the top controller these messages,
7628 // So we have to forward them on.
7630 - (void) viewDidAppear:(BOOL)animated {
7631 [super viewDidAppear:animated];
7632 [root_ viewDidAppear:animated];
7635 - (void) viewWillAppear:(BOOL)animated {
7636 [super viewWillAppear:animated];
7637 [root_ viewWillAppear:animated];
7640 - (void) viewDidDisappear:(BOOL)animated {
7641 [super viewDidDisappear:animated];
7642 [root_ viewDidDisappear:animated];
7645 - (void) viewWillDisappear:(BOOL)animated {
7646 [super viewWillDisappear:animated];
7647 [root_ viewWillDisappear:animated];
7650 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7651 return ![updatedelegate_ hudIsShowing] && (IsWildcat_ || orientation == UIInterfaceOrientationPortrait);
7654 - (void) setTabBarController:(UITabBarController *)controller {
7656 [[self view] addSubview:[root_ view]];
7659 - (void) setUpdate:(NSDate *)date {
7663 - (void) beginUpdate {
7665 [refreshbar_ start];
7670 detachNewThreadSelector:@selector(performUpdate)
7676 - (void) performUpdate { _pooled
7678 status.setDelegate(self);
7679 [database_ updateWithStatus:status];
7682 performSelectorOnMainThread:@selector(completeUpdate)
7688 - (void) completeUpdate {
7693 [self raiseBar:YES];
7695 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7698 - (void) cancelUpdate {
7700 [self raiseBar:YES];
7702 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7705 - (void) cancelPressed {
7706 [self cancelUpdate];
7713 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7714 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7717 - (void) startProgress {
7720 - (void) setProgressTitle:(NSString *)title {
7722 performSelectorOnMainThread:@selector(_setProgressTitle:)
7728 - (bool) isCancelling:(size_t)received {
7732 - (void) setProgressPercent:(float)percent {
7734 performSelectorOnMainThread:@selector(_setProgressPercent:)
7735 withObject:[NSNumber numberWithFloat:percent]
7740 - (void) addProgressOutput:(NSString *)output {
7742 performSelectorOnMainThread:@selector(_addProgressOutput:)
7748 - (void) _setProgressTitle:(NSString *)title {
7749 [refreshbar_ setPrompt:title];
7752 - (void) _setProgressPercent:(NSNumber *)percent {
7753 [refreshbar_ setProgress:[percent floatValue]];
7756 - (void) _addProgressOutput:(NSString *)output {
7759 - (void) setUpdateDelegate:(id)delegate {
7760 updatedelegate_ = delegate;
7763 - (CGFloat) statusBarHeight {
7764 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7765 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7767 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7771 - (void) dropBar:(BOOL)animated {
7776 [[self view] addSubview:refreshbar_];
7778 CGFloat sboffset = [self statusBarHeight];
7780 CGRect barframe = [refreshbar_ frame];
7781 barframe.origin.y = sboffset;
7782 [refreshbar_ setFrame:barframe];
7785 [UIView beginAnimations:nil context:NULL];
7786 CGRect viewframe = [[root_ view] frame];
7787 viewframe.origin.y += barframe.size.height + sboffset;
7788 viewframe.size.height -= barframe.size.height + sboffset;
7789 [[root_ view] setFrame:viewframe];
7791 [UIView commitAnimations];
7793 // Ensure bar has the proper width for our view, it might have changed
7794 barframe.size.width = viewframe.size.width;
7795 [refreshbar_ setFrame:barframe];
7797 // XXX: fix Apple's layout bug
7798 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7801 - (void) raiseBar:(BOOL)animated {
7806 [refreshbar_ removeFromSuperview];
7808 CGFloat sboffset = [self statusBarHeight];
7811 [UIView beginAnimations:nil context:NULL];
7812 CGRect barframe = [refreshbar_ frame];
7813 CGRect viewframe = [[root_ view] frame];
7814 viewframe.origin.y -= barframe.size.height + sboffset;
7815 viewframe.size.height += barframe.size.height + sboffset;
7816 [[root_ view] setFrame:viewframe];
7818 [UIView commitAnimations];
7820 // XXX: fix Apple's layout bug
7821 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7824 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7825 // XXX: fix Apple's layout bug
7826 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7829 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7835 // XXX: fix Apple's layout bug
7836 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7839 - (void) statusBarFrameChanged:(NSNotification *)notification {
7847 [refreshbar_ release];
7848 [[NSNotificationCenter defaultCenter] removeObserver:self];
7852 - (id) initWithDatabase:(Database *)database {
7853 if ((self = [super init]) != nil) {
7854 database_ = database;
7856 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7857 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7859 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7876 @interface Cydia : UIApplication <
7877 ConfirmationControllerDelegate,
7878 ProgressControllerDelegate,
7880 UINavigationControllerDelegate,
7881 UITabBarControllerDelegate
7883 // XXX: evaluate all fields for _transient
7886 CYContainer *container_;
7887 CYTabBarController *tabbar_;
7889 NSMutableArray *essential_;
7890 NSMutableArray *broken_;
7892 Database *database_;
7898 SectionsController *sections_;
7899 ChangesController *changes_;
7900 ManageController *manage_;
7901 SearchController *search_;
7902 SourceTable *sources_;
7903 InstalledController *installed_;
7906 CYStashController *stash_;
7911 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7912 - (void) setPage:(CYViewController *)page;
7917 static _finline void _setHomePage(Cydia *self) {
7918 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7921 @implementation Cydia
7923 - (void) beginUpdate {
7924 [container_ beginUpdate];
7928 return [container_ updating];
7931 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7936 if ([broken_ count] != 0) {
7937 int count = [broken_ count];
7939 UIAlertView *alert = [[[UIAlertView alloc]
7940 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7941 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7943 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7944 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
7947 [alert setContext:@"fixhalf"];
7949 } else if (!Ignored_ && [essential_ count] != 0) {
7950 int count = [essential_ count];
7952 UIAlertView *alert = [[[UIAlertView alloc]
7953 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7954 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
7956 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
7957 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
7960 [alert setContext:@"upgrade"];
7965 - (void) _saveConfig {
7968 NSString *error(nil);
7969 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7971 NSError *error(nil);
7972 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7973 NSLog(@"failure to save metadata data: %@", error);
7976 NSLog(@"failure to serialize metadata: %@", error);
7984 - (void) _updateData {
7987 /* XXX: this is just stupid */
7988 if (tag_ != 1 && sections_ != nil)
7989 [sections_ reloadData];
7990 if (tag_ != 2 && changes_ != nil)
7991 [changes_ reloadData];
7992 if (tag_ != 4 && search_ != nil)
7993 [search_ reloadData];
7995 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
7998 - (int)indexOfTabWithTag:(int)tag {
8000 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8001 if ([[controller tabBarItem] tag] == tag)
8009 - (void) _refreshIfPossible {
8010 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8012 bool recently = false;
8013 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8014 if (update != nil) {
8015 NSTimeInterval interval([update timeIntervalSinceNow]);
8016 if (interval <= 0 && interval > -(15*60))
8020 // Don't automatic refresh if:
8021 // - We already refreshed recently.
8022 // - We already auto-refreshed this launch.
8023 // - Auto-refresh is disabled.
8024 if (recently || loaded_ || ManualRefresh) {
8025 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8027 // If we are cancelling due to ManualRefresh or a recent refresh
8028 // we need to make sure it knows it's already loaded.
8032 // We are going to load, so remember that.
8036 SCNetworkReachabilityFlags flags; {
8037 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8038 SCNetworkReachabilityGetFlags(reachability, &flags);
8039 CFRelease(reachability);
8042 // XXX: this elaborate mess is what Apple is using to determine this? :(
8043 // XXX: do we care if the user has to intervene? maybe that's ok?
8045 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8046 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8047 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8048 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8049 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8050 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8054 // If we can reach the server, auto-refresh!
8056 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8061 - (void) refreshIfPossible {
8062 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8065 - (void) _reloadData {
8066 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8067 [hud setText:UCLocalize("RELOADING_DATA")];
8069 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8072 [self removeProgressHUD:hud];
8076 [essential_ removeAllObjects];
8077 [broken_ removeAllObjects];
8079 NSArray *packages([database_ packages]);
8080 for (Package *package in packages) {
8082 [broken_ addObject:package];
8083 if ([package upgradableAndEssential:NO]) {
8084 if ([package essential])
8085 [essential_ addObject:package];
8090 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8092 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8093 [changesItem setBadgeValue:badge];
8094 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8096 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8097 [self setApplicationBadge:badge];
8099 [self setApplicationBadgeString:badge];
8101 [changesItem setBadgeValue:nil];
8102 [changesItem setAnimatedBadge:NO];
8104 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8105 [self removeApplicationBadge];
8106 else // XXX: maybe use setApplicationBadgeString also?
8107 [self setApplicationIconBadgeNumber:0];
8112 [self refreshIfPossible];
8115 - (void) updateData {
8124 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8125 _assert(file != NULL);
8127 for (NSString *key in [Sources_ allKeys]) {
8128 NSDictionary *source([Sources_ objectForKey:key]);
8130 fprintf(file, "%s %s %s\n",
8131 [[source objectForKey:@"Type"] UTF8String],
8132 [[source objectForKey:@"URI"] UTF8String],
8133 [[source objectForKey:@"Distribution"] UTF8String]
8141 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8142 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8144 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8145 [container_ presentModalViewController:navigation animated:YES];
8148 detachNewThreadSelector:@selector(update_)
8151 title:UCLocalize("UPDATING_SOURCES")
8155 - (void) reloadData {
8156 @synchronized (self) {
8162 pkgProblemResolver *resolver = [database_ resolver];
8164 resolver->InstallProtect();
8165 if (!resolver->Resolve(true))
8169 - (CGRect) popUpBounds {
8170 return [[tabbar_ view] bounds];
8174 if (![database_ prepare])
8177 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8178 [page setDelegate:self];
8179 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8180 [confirm_ setDelegate:self];
8183 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8184 [container_ presentModalViewController:confirm_ animated:YES];
8190 @synchronized (self) {
8195 - (void) clearPackage:(Package *)package {
8196 @synchronized (self) {
8203 - (void) installPackages:(NSArray *)packages {
8204 @synchronized (self) {
8205 for (Package *package in packages)
8212 - (void) installPackage:(Package *)package {
8213 @synchronized (self) {
8220 - (void) removePackage:(Package *)package {
8221 @synchronized (self) {
8228 - (void) distUpgrade {
8229 @synchronized (self) {
8230 if (![database_ upgrade])
8237 @synchronized (self) {
8242 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8243 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8245 if (navigation != nil) {
8246 [navigation pushViewController:progress animated:YES];
8248 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8250 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8251 [container_ presentModalViewController:navigation animated:YES];
8255 detachNewThreadSelector:@selector(perform)
8258 title:UCLocalize("RUNNING")
8262 - (void) progressControllerIsComplete:(ProgressController *)progress {
8266 - (void) setPage:(CYViewController *)page {
8267 [page setDelegate:self];
8269 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8270 [navController setViewControllers:[NSArray arrayWithObject:page]];
8271 for (CYNavigationController *page in [tabbar_ viewControllers])
8272 if (page != navController)
8273 [page setViewControllers:nil];
8276 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8277 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8278 [browser loadURL:url];
8282 - (SectionsController *) sectionsController {
8283 if (sections_ == nil)
8284 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8288 - (ChangesController *) changesController {
8289 if (changes_ == nil)
8290 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8294 - (ManageController *) manageController {
8295 if (manage_ == nil) {
8296 manage_ = (ManageController *) [[self
8297 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8298 withClass:[ManageController class]
8301 queueDelegate_ = manage_;
8306 - (SearchController *) searchController {
8308 search_ = [[SearchController alloc] initWithDatabase:database_];
8312 - (SourceTable *) sourcesController {
8313 if (sources_ == nil)
8314 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8318 - (InstalledController *) installedController {
8319 if (installed_ == nil) {
8320 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8322 queueDelegate_ = installed_;
8327 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8328 int tag = [[viewController tabBarItem] tag];
8330 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8332 } else if (tag_ == 1) {
8333 [[self sectionsController] resetView];
8337 case kCydiaTag: _setHomePage(self); break;
8339 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8340 case kChangesTag: [self setPage:[self changesController]]; break;
8341 case kManageTag: [self setPage:[self manageController]]; break;
8342 case kInstalledTag: [self setPage:[self installedController]]; break;
8343 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8344 case kSearchTag: [self setPage:[self searchController]]; break;
8352 - (void) showSettings {
8353 RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease];
8354 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8356 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8357 [container_ presentModalViewController:nav animated:YES];
8360 - (void) setPackageController:(PackageController *)view {
8362 [view setPackage:nil];
8366 - (PackageController *) _packageController {
8367 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8370 - (PackageController *) packageController {
8371 return [self _packageController];
8374 // Returns the navigation controller for the queuing badge.
8375 - (id) queueBadgeController {
8376 int index = [self indexOfTabWithTag:kManageTag];
8378 index = [self indexOfTabWithTag:kInstalledTag];
8380 return [[tabbar_ viewControllers] objectAtIndex:index];
8383 - (void) cancelAndClear:(bool)clear {
8384 @synchronized (self) {
8390 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
8394 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8398 [queueDelegate_ queueStatusDidChange];
8402 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8403 NSString *context([alert context]);
8405 if ([context isEqualToString:@"fixhalf"]) {
8406 if (button == [alert firstOtherButtonIndex]) {
8407 @synchronized (self) {
8408 for (Package *broken in broken_) {
8411 NSString *id = [broken id];
8412 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8413 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8414 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8415 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8421 } else if (button == [alert cancelButtonIndex]) {
8422 [broken_ removeAllObjects];
8426 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8427 } else if ([context isEqualToString:@"upgrade"]) {
8428 if (button == [alert firstOtherButtonIndex]) {
8429 @synchronized (self) {
8430 for (Package *essential in essential_)
8431 [essential install];
8436 } else if (button == [alert firstOtherButtonIndex] + 1) {
8438 } else if (button == [alert cancelButtonIndex]) {
8442 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8446 - (void) system:(NSString *)command { _pooled
8447 system([command UTF8String]);
8450 - (void) applicationWillSuspend {
8452 [super applicationWillSuspend];
8455 - (BOOL) hudIsShowing {
8459 - (void) applicationSuspend:(__GSEvent *)event {
8460 // Use external process status API internally.
8461 // This is probably a really bad idea.
8462 uint64_t status = 0;
8464 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8465 notify_get_state(notify_token, &status);
8466 notify_cancel(notify_token);
8469 if (![self hudIsShowing] && status == 0)
8470 [super applicationSuspend:event];
8473 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8474 if (![self hudIsShowing])
8475 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8478 - (void) _setSuspended:(BOOL)value {
8479 if (![self hudIsShowing])
8480 [super _setSuspended:value];
8483 - (UIProgressHUD *) addProgressHUD {
8484 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8485 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8487 [window_ setUserInteractionEnabled:NO];
8490 UIViewController *target = container_;
8491 while ([target modalViewController] != nil) target = [target modalViewController];
8492 [[target view] addSubview:hud];
8498 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8500 [hud removeFromSuperview];
8501 [window_ setUserInteractionEnabled:YES];
8505 - (CYViewController *) pageForPackage:(NSString *)name {
8506 if (Package *package = [database_ packageWithName:name]) {
8507 PackageController *view([self packageController]);
8508 [view setPackage:package];
8511 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8512 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8513 return [self _pageForURL:url withClass:[CYBrowserController class]];
8517 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8521 NSString *href([url absoluteString]);
8522 if ([href hasPrefix:@"apptapp://package/"])
8523 return [self pageForPackage:[href substringFromIndex:18]];
8525 NSString *scheme([[url scheme] lowercaseString]);
8526 if (![scheme isEqualToString:@"cydia"])
8528 NSString *path([url absoluteString]);
8529 if ([path length] < 8)
8531 path = [path substringFromIndex:8];
8532 if (![path hasPrefix:@"/"])
8533 path = [@"/" stringByAppendingString:path];
8535 if ([path isEqualToString:@"/add-source"])
8536 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8537 else if ([path isEqualToString:@"/storage"])
8538 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8539 else if ([path isEqualToString:@"/sources"])
8540 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8541 else if ([path isEqualToString:@"/packages"])
8542 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8543 else if ([path hasPrefix:@"/url/"])
8544 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8545 else if ([path hasPrefix:@"/launch/"])
8546 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8547 else if ([path hasPrefix:@"/package-settings/"])
8548 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8549 else if ([path hasPrefix:@"/package-signature/"])
8550 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8551 else if ([path hasPrefix:@"/package/"])
8552 return [self pageForPackage:[path substringFromIndex:9]];
8553 else if ([path hasPrefix:@"/files/"]) {
8554 NSString *name = [path substringFromIndex:7];
8556 if (Package *package = [database_ packageWithName:name]) {
8557 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8558 [files setPackage:package];
8566 - (void) applicationOpenURL:(NSURL *)url {
8567 [super applicationOpenURL:url];
8568 starturl_ = [url retain];
8571 - (void) applicationWillResignActive:(UIApplication *)application {
8572 // Stop refreshing if you get a phone call or lock the device.
8573 if ([container_ updating])
8574 [container_ cancelUpdate];
8576 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8577 [super applicationWillResignActive:application];
8580 - (void) addStashController {
8581 stash_ = [[CYStashController alloc] init];
8582 [window_ addSubview:[stash_ view]];
8585 - (void) removeStashController {
8586 [[stash_ view] removeFromSuperview];
8591 [self setIdleTimerDisabled:YES];
8593 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8594 [self setStatusBarShowsProgress:YES];
8595 UpdateExternalStatus(1);
8597 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8599 UpdateExternalStatus(0);
8600 [self setStatusBarShowsProgress:NO];
8602 [self removeStashController];
8604 if (ExecFork() == 0) {
8605 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8606 perror("launchctl stop");
8610 - (void) setupTabBarController {
8611 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8612 [tabbar_ setDelegate:self];
8614 NSMutableArray *items([NSMutableArray arrayWithObjects:
8615 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8616 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8617 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8618 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8622 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8623 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8625 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8628 NSMutableArray *controllers([NSMutableArray array]);
8630 for (UITabBarItem *item in items) {
8631 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8632 [controller setTabBarItem:item];
8633 [controllers addObject:controller];
8636 [tabbar_ setViewControllers:controllers];
8639 - (void) applicationDidFinishLaunching:(id)unused {
8640 [CYBrowserController _initialize];
8642 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8644 Font12_ = [[UIFont systemFontOfSize:12] retain];
8645 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8646 Font14_ = [[UIFont systemFontOfSize:14] retain];
8647 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8648 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8652 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8653 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8655 UIScreen *screen([UIScreen mainScreen]);
8657 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8658 [window_ orderFront:self];
8659 [window_ makeKey:self];
8660 [window_ setHidden:NO];
8663 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8664 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8665 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8666 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8667 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8668 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8669 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8670 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8671 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8674 [self addStashController];
8675 // XXX: this would be much cleaner as a yieldToSelector:
8676 // that way the removeStashController could happen right here inline
8677 // we also could no longer require the useless stash_ field anymore
8678 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8682 database_ = [Database sharedInstance];
8684 [self setupTabBarController];
8686 container_ = [[CYContainer alloc] initWithDatabase:database_];
8687 [container_ setUpdateDelegate:self];
8688 [container_ setTabBarController:tabbar_];
8689 [window_ addSubview:[container_ view]];
8691 // Show pinstripes while loading data.
8692 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8694 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8701 [self showSettings];
8705 [window_ setUserInteractionEnabled:NO];
8707 UIView *container = [[[UIView alloc] init] autorelease];
8708 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8710 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
8711 [spinner startAnimating];
8712 [container addSubview:spinner];
8714 UILabel *label = [[[UILabel alloc] init] autorelease];
8715 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8716 [label setBackgroundColor:[UIColor clearColor]];
8717 [label setTextColor:[UIColor blackColor]];
8718 [label setShadowColor:[UIColor whiteColor]];
8719 [label setShadowOffset:CGSizeMake(0, 1)];
8720 [label setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
8721 [container addSubview:label];
8723 CGSize viewsize = [[tabbar_ view] frame].size;
8724 CGSize spinnersize = [spinner bounds].size;
8725 CGSize textsize = [[label text] sizeWithFont:[label font]];
8726 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8728 CGRect containrect = {
8729 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8730 CGSizeMake(bothwidth, spinnersize.height)
8733 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8741 [container setFrame:containrect];
8742 [spinner setFrame:spinrect];
8743 [label setFrame:textrect];
8744 [[container_ view] addSubview:container];
8749 // Show the initial page
8750 CYViewController *page = nil;
8752 if (starturl_ != nil && (page = [self pageForURL:starturl_ hasTag:&tag])) {
8753 [starturl_ release];
8754 [self setPage:page];
8756 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8758 [tabbar_ setSelectedIndex:0];
8762 [window_ setUserInteractionEnabled:YES];
8764 // XXX: does this actually slow anything down?
8765 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8766 [container removeFromSuperview];
8769 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8770 if (item != nil && IsWildcat_) {
8771 [sheet showFromBarButtonItem:item animated:YES];
8773 [sheet showInView:window_];
8780 id Alloc_(id self, SEL selector) {
8781 id object = alloc_(self, selector);
8782 lprintf("[%s]A-%p\n", self->isa->name, object);
8787 id Dealloc_(id self, SEL selector) {
8788 id object = dealloc_(self, selector);
8789 lprintf("[%s]D-%p\n", self->isa->name, object);
8793 Class $WebDefaultUIKitDelegate;
8795 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8796 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8797 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8798 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8801 static NSNumber *shouldPlayKeyboardSounds;
8805 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8807 case 1104: // Keyboard Button Clicked
8808 case 1105: // Keyboard Delete Repeated
8809 if (shouldPlayKeyboardSounds == nil) {
8810 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8811 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8814 if (![shouldPlayKeyboardSounds boolValue])
8818 _UIHardware$_playSystemSound$(self, _cmd, sound);
8822 int main(int argc, char *argv[]) { _pooled
8825 if (Class $UIDevice = objc_getClass("UIDevice")) {
8826 UIDevice *device([$UIDevice currentDevice]);
8827 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8831 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8833 /* Library Hacks {{{ */
8834 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8836 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8837 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8838 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8839 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8840 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8843 $UIHardware = objc_getClass("UIHardware");
8844 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8845 if (UIHardware$_playSystemSound$ != NULL) {
8846 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8847 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8850 /* Set Locale {{{ */
8851 Locale_ = CFLocaleCopyCurrent();
8852 Languages_ = [NSLocale preferredLanguages];
8853 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8854 //NSLog(@"%@", [Languages_ description]);
8857 if (Languages_ == nil || [Languages_ count] == 0)
8858 // XXX: consider just setting to C and then falling through?
8861 lang = [[Languages_ objectAtIndex:0] UTF8String];
8862 setenv("LANG", lang, true);
8865 //std::setlocale(LC_ALL, lang);
8866 NSLog(@"Setting Language: %s", lang);
8869 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8871 /* Parse Arguments {{{ */
8872 bool substrate(false);
8878 for (int argi(1); argi != argc; ++argi)
8879 if (strcmp(argv[argi], "--") == 0) {
8881 argv[argi] = argv[0];
8887 for (int argi(1); argi != arge; ++argi)
8888 if (strcmp(args[argi], "--substrate") == 0)
8891 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8895 App_ = [[NSBundle mainBundle] bundlePath];
8896 Home_ = NSHomeDirectory();
8902 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8903 alloc_ = alloc->method_imp;
8904 alloc->method_imp = (IMP) &Alloc_;*/
8906 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8907 dealloc_ = dealloc->method_imp;
8908 dealloc->method_imp = (IMP) &Dealloc_;*/
8910 /* System Information {{{ */
8914 size = sizeof(maxproc);
8915 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8916 perror("sysctlbyname(\"kern.maxproc\", ?)");
8917 else if (maxproc < 64) {
8919 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8920 perror("sysctlbyname(\"kern.maxproc\", #)");
8923 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8924 char *osversion = new char[size];
8925 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8926 perror("sysctlbyname(\"kern.osversion\", ?)");
8928 System_ = [NSString stringWithUTF8String:osversion];
8930 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8931 char *machine = new char[size];
8932 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8933 perror("sysctlbyname(\"hw.machine\", ?)");
8937 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8938 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8939 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8940 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8944 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8945 NSData *data((NSData *) ecid);
8946 size_t length([data length]);
8947 uint8_t bytes[length];
8948 [data getBytes:bytes];
8949 char string[length * 2 + 1];
8950 for (size_t i(0); i != length; ++i)
8951 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8952 ChipID_ = [NSString stringWithUTF8String:string];
8956 IOObjectRelease(service);
8960 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8962 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
8963 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
8964 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
8966 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
8967 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
8968 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
8970 if (mcc != NULL && mnc != NULL)
8971 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
8978 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8979 Build_ = [system objectForKey:@"ProductBuildVersion"];
8980 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8981 Product_ = [info objectForKey:@"SafariProductVersion"];
8982 Safari_ = [info objectForKey:@"CFBundleVersion"];
8985 /* Load Database {{{ */
8987 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8989 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8991 if (Metadata_ == NULL)
8992 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8994 Settings_ = [Metadata_ objectForKey:@"Settings"];
8996 Packages_ = [Metadata_ objectForKey:@"Packages"];
8997 Sections_ = [Metadata_ objectForKey:@"Sections"];
8998 Sources_ = [Metadata_ objectForKey:@"Sources"];
9000 Token_ = [Metadata_ objectForKey:@"Token"];
9003 if (Settings_ != nil)
9004 Role_ = [Settings_ objectForKey:@"Role"];
9006 if (Packages_ == nil) {
9007 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
9008 [Metadata_ setObject:Packages_ forKey:@"Packages"];
9011 if (Sections_ == nil) {
9012 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9013 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9016 if (Sources_ == nil) {
9017 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9018 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9022 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9024 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9025 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9026 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9027 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9028 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9029 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9031 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9033 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9034 unlink("/tmp/.cydia.fw");
9036 } else if (access("/User", F_OK) != 0 || version < 2) {
9039 system("/usr/libexec/cydia/firmware.sh");
9043 _assert([[NSFileManager defaultManager]
9044 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9045 withIntermediateDirectories:YES
9050 if (access("/tmp/cydia.chk", F_OK) == 0) {
9051 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9052 _assert(errno == ENOENT);
9053 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9054 _assert(errno == ENOENT);
9057 /* APT Initialization {{{ */
9058 _assert(pkgInitConfig(*_config));
9059 _assert(pkgInitSystem(*_config, _system));
9062 _config->Set("APT::Acquire::Translation", lang);
9064 // XXX: this timeout might be important :(
9065 //_config->Set("Acquire::http::Timeout", 15);
9067 _config->Set("Acquire::http::MaxParallel", 3);
9069 /* Color Choices {{{ */
9070 space_ = CGColorSpaceCreateDeviceRGB();
9072 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9073 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9074 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9075 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9076 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9077 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9078 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9079 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9080 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9082 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9083 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9085 /* UIKit Configuration {{{ */
9086 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9087 if ($GSFontSetUseLegacyFontMetrics != NULL)
9088 $GSFontSetUseLegacyFontMetrics(YES);
9090 // XXX: I have a feeling this was important
9091 //UIKeyboardDisableAutomaticAppearance();
9094 Colon_ = UCLocalize("COLON_DELIMITED");
9095 Elision_ = UCLocalize("ELISION");
9096 Error_ = UCLocalize("ERROR");
9097 Warning_ = UCLocalize("WARNING");
9100 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9102 CGColorSpaceRelease(space_);