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_;
1740 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1741 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1743 - (pkgCache::PkgIterator) iterator;
1746 - (NSString *) section;
1747 - (NSString *) simpleSection;
1749 - (NSString *) longSection;
1750 - (NSString *) shortSection;
1754 - (Address *) maintainer;
1756 - (NSString *) longDescription;
1757 - (NSString *) shortDescription;
1760 - (NSMutableDictionary *) metadata;
1762 - (BOOL) subscribed;
1765 - (NSString *) latest;
1766 - (NSString *) installed;
1767 - (BOOL) uninstalled;
1770 - (BOOL) upgradableAndEssential:(BOOL)essential;
1773 - (BOOL) unfiltered;
1777 - (BOOL) halfConfigured;
1778 - (BOOL) halfInstalled;
1780 - (NSString *) mode;
1783 - (NSString *) name;
1785 - (NSString *) homepage;
1786 - (NSString *) depiction;
1787 - (Address *) author;
1789 - (NSString *) support;
1791 - (NSArray *) files;
1792 - (NSArray *) warnings;
1793 - (NSArray *) applications;
1795 - (Source *) source;
1796 - (NSString *) role;
1798 - (BOOL) matches:(NSString *)text;
1800 - (bool) hasSupportingRole;
1801 - (BOOL) hasTag:(NSString *)tag;
1802 - (NSString *) primaryPurpose;
1803 - (NSArray *) purposes;
1804 - (bool) isCommercial;
1806 - (CYString &) cyname;
1808 - (uint32_t) compareBySection:(NSArray *)sections;
1813 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1814 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1815 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1816 - (bool) isVisibleInSection:(NSString *)section;
1817 - (bool) isVisibleInSource:(Source *)source;
1821 uint32_t PackageChangesRadix(Package *self, void *) {
1826 uint32_t timestamp : 30;
1827 uint32_t ignored : 1;
1828 uint32_t upgradable : 1;
1832 bool upgradable([self upgradableAndEssential:YES]);
1833 value.bits.upgradable = upgradable ? 1 : 0;
1836 value.bits.timestamp = 0;
1837 value.bits.ignored = [self ignored] ? 0 : 1;
1838 value.bits.upgradable = 1;
1840 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1841 value.bits.ignored = 0;
1842 value.bits.upgradable = 0;
1845 return _not(uint32_t) - value.key;
1848 _finline static void Stifle(uint8_t &value) {
1851 uint32_t PackagePrefixRadix(Package *self, void *context) {
1852 size_t offset(reinterpret_cast<size_t>(context));
1853 CYString &name([self cyname]);
1855 size_t size(name.size());
1858 char *text(name.data());
1861 if (!isdigit(text[0]))
1865 while (size != digits && isdigit(text[digits]))
1875 if (offset == 0 && zeros != 0) {
1876 memset(data, '0', zeros);
1877 memcpy(data + zeros, text, 4 - zeros);
1879 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1880 if (size <= offset - zeros)
1883 text += offset - zeros;
1884 size -= offset - zeros;
1887 memcpy(data, text, 4);
1889 memcpy(data, text, size);
1890 memset(data + size, 0, 4 - size);
1893 for (size_t i(0); i != 4; ++i)
1894 if (isalpha(data[i]))
1902 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1904 /* XXX: ntohl may be more honest */
1905 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1908 CYString &(*PackageName)(Package *self, SEL sel);
1910 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1911 _profile(PackageNameCompare)
1912 CYString &lhi(PackageName(lhs, @selector(cyname)));
1913 CYString &rhi(PackageName(rhs, @selector(cyname)));
1914 CFStringRef lhn(lhi), rhn(rhi);
1917 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1918 else if (rhn == NULL)
1919 return NSOrderedDescending;
1921 _profile(PackageNameCompare$NumbersLast)
1922 if (!lhi.empty() && !rhi.empty()) {
1923 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1924 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1925 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1926 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1927 return lha ? NSOrderedAscending : NSOrderedDescending;
1931 CFIndex length = CFStringGetLength(lhn);
1933 _profile(PackageNameCompare$Compare)
1934 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1939 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1940 return PackageNameCompare(*lhs, *rhs, context);
1943 struct PackageNameOrdering :
1944 std::binary_function<Package *, Package *, bool>
1946 _finline bool operator ()(Package *lhs, Package *rhs) const {
1947 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1951 @implementation Package
1953 - (NSString *) description {
1954 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1964 if (sponsor$_ != nil)
1965 [sponsor$_ release];
1966 if (author$_ != nil)
1973 if (metadata_ != nil)
1974 [metadata_ release];
1979 + (NSString *) webScriptNameForSelector:(SEL)selector {
1980 if (selector == @selector(hasTag:))
1986 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1987 return [self webScriptNameForSelector:selector] == nil;
1990 + (NSArray *) _attributeKeys {
1991 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];
1994 - (NSArray *) attributeKeys {
1995 return [[self class] _attributeKeys];
1998 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1999 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2009 _profile(Package$parse)
2010 pkgRecords::Parser *parser;
2012 _profile(Package$parse$Lookup)
2013 parser = &[database_ records]->Lookup(file_);
2018 _profile(Package$parse$Find)
2024 {"depiction", &depiction_},
2025 {"homepage", &homepage_},
2026 {"website", &website},
2028 {"support", &support_},
2029 {"sponsor", &sponsor_},
2030 {"author", &author_},
2033 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2034 const char *start, *end;
2036 if (parser->Find(names[i].name_, start, end)) {
2037 CYString &value(*names[i].value_);
2038 _profile(Package$parse$Value)
2039 value.set(pool_, start, end - start);
2045 _profile(Package$parse$Tagline)
2046 const char *start, *end;
2047 if (parser->ShortDesc(start, end)) {
2048 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2051 while (stop != start && stop[-1] == '\r')
2053 tagline_.set(pool_, start, stop - start);
2057 _profile(Package$parse$Retain)
2058 if (homepage_.empty())
2059 homepage_ = website;
2060 if (homepage_ == depiction_)
2066 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2067 if ((self = [super init]) != nil) {
2068 _profile(Package$initWithVersion)
2069 era_ = [database era];
2074 _profile(Package$initWithVersion$ParentPkg)
2075 iterator_ = version.ParentPkg();
2078 database_ = database;
2080 _profile(Package$initWithVersion$Latest)
2081 const char *latest(StripVersion_(version_.VerStr()));
2082 latest_ = (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(latest), strlen(latest), kCFStringEncodingASCII, NO);
2085 pkgCache::VerIterator current;
2086 _profile(Package$initWithVersion$Versions)
2087 current = iterator_.CurrentVer();
2089 installed_.set(pool_, StripVersion_(current.VerStr()));
2091 if (!version_.end())
2092 file_ = version_.FileList();
2094 pkgCache &cache([database_ cache]);
2095 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2099 _profile(Package$initWithVersion$Name)
2100 id_.set(pool_, iterator_.Name());
2101 name_.set(pool, iterator_.Display());
2104 _profile(Package$initWithVersion$lowercaseString)
2105 char *data(id_.data());
2106 for (size_t i(0), e(id_.size()); i != e; ++i)
2107 // XXX: do not use tolower() as this is not locale-specific? :(
2111 _profile(Package$initWithVersion$Tags)
2112 pkgCache::TagIterator tag(iterator_.TagList());
2114 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2116 const char *name(tag.Name());
2117 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2118 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2119 role_ = (NSString *) CYStringCreate(name + 6);
2121 } while (!tag.end());
2125 bool changed(false);
2127 _profile(Package$initWithVersion$Metadata)
2128 metadata_ = [Packages_ objectForKey:id_];
2130 if (metadata_ == nil) {
2133 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2134 firstSeen_, @"FirstSeen",
2135 latest_, @"LastVersion",
2140 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2141 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2143 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2144 subscribed_ = [subscribed boolValue];
2146 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2148 if (firstSeen_ == nil) {
2149 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2150 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2154 if (version == nil) {
2155 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2157 } else if (![version isEqualToString:latest_]) {
2158 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2160 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2165 metadata_ = [metadata_ retain];
2168 [Packages_ setObject:metadata_ forKey:id_];
2173 _profile(Package$initWithVersion$Section)
2174 section_.set(pool_, iterator_.Section());
2177 _profile(Package$initWithVersion$hasTag)
2178 obsolete_ = [self hasTag:@"cydia::obsolete"];
2179 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2184 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2185 pkgCache::VerIterator version;
2187 _profile(Package$packageWithIterator$GetCandidateVer)
2188 version = [database policy]->GetCandidateVer(iterator);
2194 return [[[Package alloc]
2195 initWithVersion:version
2202 - (pkgCache::PkgIterator) iterator {
2206 - (NSString *) section {
2207 if (section$_ == nil) {
2208 if (section_.empty())
2211 _profile(Package$section)
2212 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2213 NSString *name(section_);
2214 section$_ = [SectionMap_ objectForKey:name] ?: name;
2219 - (NSString *) simpleSection {
2220 if (NSString *section = [self section])
2221 return Simplify(section);
2226 - (NSString *) longSection {
2227 return LocalizeSection([self section]);
2230 - (NSString *) shortSection {
2231 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2234 - (NSString *) uri {
2237 pkgIndexFile *index;
2238 pkgCache::PkgFileIterator file(file_.File());
2239 if (![database_ list].FindIndex(file, index))
2241 return [NSString stringWithUTF8String:iterator_->Path];
2242 //return [NSString stringWithUTF8String:file.Site()];
2243 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2247 - (Address *) maintainer {
2248 @synchronized (database_) {
2249 if ([database_ era] != era_ || file_.end())
2252 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2253 const std::string &maintainer(parser->Maintainer());
2254 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2258 @synchronized (database_) {
2259 if ([database_ era] != era_ || version_.end())
2262 return version_->InstalledSize;
2265 - (NSString *) longDescription {
2266 @synchronized (database_) {
2267 if ([database_ era] != era_ || file_.end())
2270 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2271 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2273 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2274 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2275 if ([lines count] < 2)
2278 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2279 for (size_t i(1), e([lines count]); i != e; ++i) {
2280 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2281 [trimmed addObject:trim];
2284 return [trimmed componentsJoinedByString:@"\n"];
2287 - (NSString *) shortDescription {
2292 _profile(Package$index)
2293 CFStringRef name((CFStringRef) [self name]);
2294 if (CFStringGetLength(name) == 0)
2296 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2297 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2299 return toupper(character);
2303 - (NSMutableDictionary *) metadata {
2308 if (subscribed_ && lastSeen_ != nil)
2313 - (BOOL) subscribed {
2318 NSDictionary *metadata([self metadata]);
2319 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2320 return [ignored boolValue];
2325 - (NSString *) latest {
2329 - (NSString *) installed {
2333 - (BOOL) uninstalled {
2334 return installed_.empty();
2338 return !version_.end();
2341 - (BOOL) upgradableAndEssential:(BOOL)essential {
2342 _profile(Package$upgradableAndEssential)
2343 pkgCache::VerIterator current(iterator_.CurrentVer());
2345 return essential && essential_;
2347 return !version_.end() && version_ != current;
2351 - (BOOL) essential {
2356 return [database_ cache][iterator_].InstBroken();
2359 - (BOOL) unfiltered {
2360 _profile(Package$unfiltered$obsolete)
2365 _profile(Package$unfiltered$hasSupportingRole)
2366 if (![self hasSupportingRole])
2374 if (![self unfiltered])
2377 NSString *section([self section]);
2379 _profile(Package$visible$isSectionVisible)
2380 if (section != nil && !isSectionVisible(section))
2388 unsigned char current(iterator_->CurrentState);
2389 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2392 - (BOOL) halfConfigured {
2393 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2396 - (BOOL) halfInstalled {
2397 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2401 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2402 return state.Mode != pkgDepCache::ModeKeep;
2405 - (NSString *) mode {
2406 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2408 switch (state.Mode) {
2409 case pkgDepCache::ModeDelete:
2410 if ((state.iFlags & pkgDepCache::Purge) != 0)
2414 case pkgDepCache::ModeKeep:
2415 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2416 return @"REINSTALL";
2417 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2421 case pkgDepCache::ModeInstall:
2422 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2423 return @"REINSTALL";
2424 else*/ switch (state.Status) {
2426 return @"DOWNGRADE";
2432 return @"NEW_INSTALL";
2443 - (NSString *) name {
2444 return name_.empty() ? id_ : name_;
2447 - (UIImage *) icon {
2448 NSString *section = [self simpleSection];
2452 if ([static_cast<id>(icon_) hasPrefix:@"file:///"])
2453 // XXX: correct escaping
2454 icon = [UIImage imageAtPath:[static_cast<id>(icon_) substringFromIndex:7]];
2455 if (icon == nil) if (section != nil)
2456 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2457 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2458 if ([dicon hasPrefix:@"file:///"])
2459 // XXX: correct escaping
2460 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2462 icon = [UIImage applicationImageNamed:@"unknown.png"];
2466 - (NSString *) homepage {
2470 - (NSString *) depiction {
2471 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2474 - (Address *) sponsor {
2475 if (sponsor$_ == nil) {
2476 if (sponsor_.empty())
2478 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2482 - (Address *) author {
2483 if (author$_ == nil) {
2484 if (author_.empty())
2486 author$_ = [[Address addressWithString:author_] retain];
2490 - (NSString *) support {
2491 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2494 - (NSArray *) files {
2495 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2496 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2499 fin.open([path UTF8String]);
2504 while (std::getline(fin, line))
2505 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2510 - (NSArray *) warnings {
2511 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2512 const char *name(iterator_.Name());
2514 size_t length(strlen(name));
2515 if (length < 2) invalid:
2516 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2517 else for (size_t i(0); i != length; ++i)
2519 /* XXX: technically this is not allowed */
2520 (name[i] < 'A' || name[i] > 'Z') &&
2521 (name[i] < 'a' || name[i] > 'z') &&
2522 (name[i] < '0' || name[i] > '9') &&
2523 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2526 if (strcmp(name, "cydia") != 0) {
2529 bool _private = false;
2532 bool repository = [[self section] isEqualToString:@"Repositories"];
2534 if (NSArray *files = [self files])
2535 for (NSString *file in files)
2536 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2538 else if (!user && [file isEqualToString:@"/User"])
2540 else if (!_private && [file isEqualToString:@"/private"])
2542 else if (!stash && [file isEqualToString:@"/var/stash"])
2545 /* XXX: this is not sensitive enough. only some folders are valid. */
2546 if (cydia && !repository)
2547 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2549 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2551 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2553 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2556 return [warnings count] == 0 ? nil : warnings;
2559 - (NSArray *) applications {
2560 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2562 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2564 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2565 if (NSArray *files = [self files])
2566 for (NSString *file in files)
2567 if (application_r(file)) {
2568 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2569 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2570 if ([id isEqualToString:me])
2573 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2575 display = application_r[1];
2577 NSString *bundle([file stringByDeletingLastPathComponent]);
2578 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2579 if (icon == nil || [icon length] == 0)
2581 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2583 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2584 [applications addObject:application];
2586 [application addObject:id];
2587 [application addObject:display];
2588 [application addObject:url];
2591 return [applications count] == 0 ? nil : applications;
2594 - (Source *) source {
2595 if (source_ == nil) {
2596 @synchronized (database_) {
2597 if ([database_ era] != era_ || file_.end())
2598 source_ = (Source *) [NSNull null];
2600 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2604 return source_ == (Source *) [NSNull null] ? nil : source_;
2607 - (NSString *) role {
2611 - (BOOL) matches:(NSString *)text {
2617 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2618 if (range.location != NSNotFound)
2621 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2622 if (range.location != NSNotFound)
2625 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2626 if (range.location != NSNotFound)
2632 - (bool) hasSupportingRole {
2635 if ([role_ isEqualToString:@"enduser"])
2637 if ([Role_ isEqualToString:@"User"])
2639 if ([role_ isEqualToString:@"hacker"])
2641 if ([Role_ isEqualToString:@"Hacker"])
2643 if ([role_ isEqualToString:@"developer"])
2645 if ([Role_ isEqualToString:@"Developer"])
2650 - (BOOL) hasTag:(NSString *)tag {
2651 return tags_ == nil ? NO : [tags_ containsObject:tag];
2654 - (NSString *) primaryPurpose {
2655 for (NSString *tag in tags_)
2656 if ([tag hasPrefix:@"purpose::"])
2657 return [tag substringFromIndex:9];
2661 - (NSArray *) purposes {
2662 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2663 for (NSString *tag in tags_)
2664 if ([tag hasPrefix:@"purpose::"])
2665 [purposes addObject:[tag substringFromIndex:9]];
2666 return [purposes count] == 0 ? nil : purposes;
2669 - (bool) isCommercial {
2670 return [self hasTag:@"cydia::commercial"];
2673 - (CYString &) cyname {
2674 return name_.empty() ? id_ : name_;
2677 - (uint32_t) compareBySection:(NSArray *)sections {
2678 NSString *section([self section]);
2679 for (size_t i(0), e([sections count]); i != e; ++i) {
2680 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2684 return _not(uint32_t);
2688 @synchronized (database_) {
2689 pkgProblemResolver *resolver = [database_ resolver];
2690 resolver->Clear(iterator_);
2692 pkgCacheFile &cache([database_ cache]);
2693 cache->SetReInstall(iterator_, false);
2694 cache->MarkKeep(iterator_, false);
2698 @synchronized (database_) {
2699 pkgProblemResolver *resolver = [database_ resolver];
2700 resolver->Clear(iterator_);
2701 resolver->Protect(iterator_);
2703 pkgCacheFile &cache([database_ cache]);
2704 cache->SetReInstall(iterator_, false);
2705 cache->MarkInstall(iterator_, false);
2707 pkgDepCache::StateCache &state((*cache)[iterator_]);
2708 if (!state.Install())
2709 cache->SetReInstall(iterator_, true);
2713 @synchronized (database_) {
2714 pkgProblemResolver *resolver = [database_ resolver];
2715 resolver->Clear(iterator_);
2716 resolver->Remove(iterator_);
2717 resolver->Protect(iterator_);
2719 pkgCacheFile &cache([database_ cache]);
2720 cache->SetReInstall(iterator_, false);
2721 cache->MarkDelete(iterator_, true);
2724 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2725 _profile(Package$isUnfilteredAndSearchedForBy)
2728 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2729 value &= [self unfiltered];
2732 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2733 value &= [self matches:search];
2740 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2741 if ([search length] == 0)
2744 _profile(Package$isUnfilteredAndSelectedForBy)
2747 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2748 value &= [self unfiltered];
2751 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2752 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2759 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2760 return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]);
2763 - (bool) isVisibleInSection:(NSString *)name {
2764 NSString *section([self section]);
2768 section == nil && [name length] == 0 ||
2769 [name isEqualToString:section]
2770 ) && [self visible];
2773 - (bool) isVisibleInSource:(Source *)source {
2774 return [self source] == source && [self visible];
2779 /* Section Class {{{ */
2780 @interface Section : NSObject {
2785 NSString *localized_;
2788 - (NSComparisonResult) compareByLocalized:(Section *)section;
2789 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2790 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2791 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2792 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2793 - (NSString *) name;
2800 - (void) addToCount;
2802 - (void) setCount:(size_t)count;
2803 - (NSString *) localized;
2807 @implementation Section
2811 if (localized_ != nil)
2812 [localized_ release];
2816 - (NSComparisonResult) compareByLocalized:(Section *)section {
2817 NSString *lhs(localized_);
2818 NSString *rhs([section localized]);
2820 /*if ([lhs length] != 0 && [rhs length] != 0) {
2821 unichar lhc = [lhs characterAtIndex:0];
2822 unichar rhc = [rhs characterAtIndex:0];
2824 if (isalpha(lhc) && !isalpha(rhc))
2825 return NSOrderedAscending;
2826 else if (!isalpha(lhc) && isalpha(rhc))
2827 return NSOrderedDescending;
2830 return [lhs compare:rhs options:LaxCompareOptions_];
2833 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2834 if ((self = [self initWithName:name localize:NO]) != nil) {
2835 if (localized != nil)
2836 localized_ = [localized retain];
2840 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2841 return [self initWithName:name row:0 localize:localize];
2844 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2845 if ((self = [super init]) != nil) {
2846 name_ = [name retain];
2850 localized_ = [LocalizeSection(name_) retain];
2854 /* XXX: localize the index thingees */
2855 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2856 if ((self = [super init]) != nil) {
2857 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2863 - (NSString *) name {
2883 - (void) addToCount {
2887 - (void) setCount:(size_t)count {
2891 - (NSString *) localized {
2898 static NSString *Colon_;
2899 static NSString *Elision_;
2900 static NSString *Error_;
2901 static NSString *Warning_;
2903 /* Database Implementation {{{ */
2904 @implementation Database
2906 + (Database *) sharedInstance {
2907 static Database *instance;
2908 if (instance == nil)
2909 instance = [[Database alloc] init];
2917 - (void) releasePackages {
2918 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
2919 CFArrayRemoveAllValues(packages_);
2923 // XXX: actually implement this thing
2925 [self releasePackages];
2926 apr_pool_destroy(pool_);
2927 NSRecycleZone(zone_);
2931 - (void) _readCydia:(NSNumber *)fd { _pooled
2932 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2933 std::istream is(&ib);
2936 static Pcre finish_r("^finish:([^:]*)$");
2938 while (std::getline(is, line)) {
2939 const char *data(line.c_str());
2940 size_t size = line.size();
2941 lprintf("C:%s\n", data);
2943 if (finish_r(data, size)) {
2944 NSString *finish = finish_r[1];
2945 int index = [Finishes_ indexOfObject:finish];
2946 if (index != INT_MAX && index > Finish_)
2954 - (void) _readStatus:(NSNumber *)fd { _pooled
2955 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2956 std::istream is(&ib);
2959 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2960 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2962 while (std::getline(is, line)) {
2963 const char *data(line.c_str());
2964 size_t size(line.size());
2965 lprintf("S:%s\n", data);
2967 if (conffile_r(data, size)) {
2968 [delegate_ setConfigurationData:conffile_r[1]];
2969 } else if (strncmp(data, "status: ", 8) == 0) {
2970 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2971 [delegate_ setProgressTitle:string];
2972 } else if (pmstatus_r(data, size)) {
2973 std::string type([pmstatus_r[1] UTF8String]);
2974 NSString *id = pmstatus_r[2];
2976 float percent([pmstatus_r[3] floatValue]);
2977 [delegate_ setProgressPercent:(percent / 100)];
2979 NSString *string = pmstatus_r[4];
2981 if (type == "pmerror")
2982 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
2983 withObject:[NSArray arrayWithObjects:string, id, nil]
2986 else if (type == "pmstatus") {
2987 [delegate_ setProgressTitle:string];
2988 } else if (type == "pmconffile")
2989 [delegate_ setConfigurationData:string];
2991 lprintf("E:unknown pmstatus\n");
2993 lprintf("E:unknown status\n");
2999 - (void) _readOutput:(NSNumber *)fd { _pooled
3000 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3001 std::istream is(&ib);
3004 while (std::getline(is, line)) {
3005 lprintf("O:%s\n", line.c_str());
3006 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3016 - (Package *) packageWithName:(NSString *)name {
3017 @synchronized (self) {
3018 if (static_cast<pkgDepCache *>(cache_) == NULL)
3020 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3021 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3025 if ((self = [super init]) != nil) {
3032 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3033 apr_pool_create(&pool_, NULL);
3035 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
3039 _assert(pipe(fds) != -1);
3042 _config->Set("APT::Keep-Fds::", cydiafd_);
3043 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3046 detachNewThreadSelector:@selector(_readCydia:)
3048 withObject:[NSNumber numberWithInt:fds[0]]
3051 _assert(pipe(fds) != -1);
3055 detachNewThreadSelector:@selector(_readStatus:)
3057 withObject:[NSNumber numberWithInt:fds[0]]
3060 _assert(pipe(fds) != -1);
3061 _assert(dup2(fds[0], 0) != -1);
3062 _assert(close(fds[0]) != -1);
3064 input_ = fdopen(fds[1], "a");
3066 _assert(pipe(fds) != -1);
3067 _assert(dup2(fds[1], 1) != -1);
3068 _assert(close(fds[1]) != -1);
3071 detachNewThreadSelector:@selector(_readOutput:)
3073 withObject:[NSNumber numberWithInt:fds[0]]
3078 - (pkgCacheFile &) cache {
3082 - (pkgDepCache::Policy *) policy {
3086 - (pkgRecords *) records {
3090 - (pkgProblemResolver *) resolver {
3094 - (pkgAcquire &) fetcher {
3098 - (pkgSourceList &) list {
3102 - (NSArray *) packages {
3103 return (NSArray *) packages_;
3106 - (NSArray *) sources {
3107 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3108 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3109 [sources addObject:i->second];
3113 - (NSArray *) issues {
3114 if (cache_->BrokenCount() == 0)
3117 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3119 for (Package *package in [self packages]) {
3120 if (![package broken])
3122 pkgCache::PkgIterator pkg([package iterator]);
3124 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3125 [entry addObject:[package name]];
3126 [issues addObject:entry];
3128 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3132 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3133 pkgCache::DepIterator start;
3134 pkgCache::DepIterator end;
3135 dep.GlobOr(start, end); // ++dep
3137 if (!cache_->IsImportantDep(end))
3139 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3142 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3143 [entry addObject:failure];
3144 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3146 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3147 if (Package *package = [self packageWithName:name])
3148 name = [package name];
3149 [failure addObject:name];
3151 pkgCache::PkgIterator target(start.TargetPkg());
3152 if (target->ProvidesList != 0)
3153 [failure addObject:@"?"];
3155 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3157 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3158 else if (!cache_[target].CandidateVerIter(cache_).end())
3159 [failure addObject:@"-"];
3160 else if (target->ProvidesList == 0)
3161 [failure addObject:@"!"];
3163 [failure addObject:@"%"];
3167 if (start.TargetVer() != 0)
3168 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3179 - (bool) popErrorWithTitle:(NSString *)title {
3181 std::string message;
3183 while (!_error->empty()) {
3185 bool warning(!_error->PopMessage(error));
3189 size_t size(error.size());
3190 if (size == 0 || error[size - 1] != '\n')
3192 error.resize(size - 1);
3194 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3196 if (!message.empty())
3201 if (fatal && !message.empty())
3202 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3207 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3208 return [self popErrorWithTitle:title] || !success;
3211 - (void) reloadData { CYPoolStart() {
3212 @synchronized (self) {
3215 [self releasePackages];
3241 apr_pool_clear(pool_);
3242 NSRecycleZone(zone_);
3244 int chk(creat("/tmp/cydia.chk", 0644));
3248 NSString *title(UCLocalize("DATABASE"));
3251 if (!cache_.Open(progress_, true)) { pop:
3253 bool warning(!_error->PopMessage(error));
3254 lprintf("cache_.Open():[%s]\n", error.c_str());
3256 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3257 [delegate_ repairWithSelector:@selector(configure)];
3258 else if (error == "The package lists or status file could not be parsed or opened.")
3259 [delegate_ repairWithSelector:@selector(update)];
3260 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3261 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3262 // else if (error == "The list of sources could not be read.")
3264 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3273 unlink("/tmp/cydia.chk");
3275 now_ = [[NSDate date] retain];
3277 policy_ = new pkgDepCache::Policy();
3278 records_ = new pkgRecords(cache_);
3279 resolver_ = new pkgProblemResolver(cache_);
3280 fetcher_ = new pkgAcquire(&status_);
3283 list_ = new pkgSourceList();
3284 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3287 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3288 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3292 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3295 if (cache_->BrokenCount() != 0) {
3296 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3299 if (cache_->BrokenCount() != 0) {
3300 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3304 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3308 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3309 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3310 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3311 // XXX: this could be more intelligent
3312 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3313 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3315 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3320 /*std::vector<Package *> packages;
3321 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3322 [packages_ release];
3327 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3328 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3329 //packages.push_back(package);
3330 CFArrayAppendValue(packages_, [package retain]);
3334 /*if (packages.empty())
3335 packages_ = [[NSArray alloc] init];
3337 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3340 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3341 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3342 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3350 /*if (!packages.empty())
3351 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3352 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3354 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3356 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3358 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3362 } } CYPoolEnd() _trace(); }
3365 @synchronized (self) {
3367 resolver_ = new pkgProblemResolver(cache_);
3369 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3370 if (!cache_[iterator].Keep()) {
3371 cache_->MarkKeep(iterator, false);
3372 cache_->SetReInstall(iterator, false);
3377 - (void) configure {
3378 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3379 system([dpkg UTF8String]);
3383 // XXX: I don't remember this condition
3388 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3390 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3392 if ([self popErrorWithTitle:title])
3396 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3399 public pkgArchiveCleaner
3402 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3407 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3414 fetcher_->Shutdown();
3416 pkgRecords records(cache_);
3418 lock_ = new FileFd();
3419 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3421 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3423 if ([self popErrorWithTitle:title])
3427 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3430 manager_ = (_system->CreatePM(cache_));
3431 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3438 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3440 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3442 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3444 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3445 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3448 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3453 bool failed = false;
3454 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3455 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3457 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3460 std::string uri = (*item)->DescURI();
3461 std::string error = (*item)->ErrorText;
3463 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3466 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3467 withObject:[NSArray arrayWithObjects:
3468 [NSString stringWithUTF8String:error.c_str()],
3480 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3482 if (_error->PendingError()) {
3487 if (result == pkgPackageManager::Failed) {
3492 if (result != pkgPackageManager::Completed) {
3497 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3499 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3501 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3502 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3505 if (![before isEqualToArray:after])
3510 NSString *title(UCLocalize("UPGRADE"));
3511 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3517 [self updateWithStatus:status_];
3520 - (void) updateWithStatus:(Status &)status {
3521 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3522 NSString *title(UCLocalize("REFRESHING_DATA"));
3525 if (!list.ReadMainList())
3526 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3529 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3530 if ([self popErrorWithTitle:title])
3533 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3534 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3535 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3537 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3541 - (void) setDelegate:(id)delegate {
3542 delegate_ = delegate;
3543 status_.setDelegate(delegate);
3544 progress_.setDelegate(delegate);
3547 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3548 SourceMap::const_iterator i(sources_.find(file->ID));
3549 return i == sources_.end() ? nil : i->second;
3555 /* Confirmation Controller {{{ */
3556 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3557 if (!iterator.end())
3558 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3559 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3561 pkgCache::PkgIterator package(dep.TargetPkg());
3564 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3572 /* Web Scripting {{{ */
3573 @interface CydiaObject : NSObject {
3575 _transient id delegate_;
3578 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3581 @implementation CydiaObject
3584 [indirect_ release];
3588 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3589 if ((self = [super init]) != nil) {
3590 indirect_ = [indirect retain];
3594 - (void) setDelegate:(id)delegate {
3595 delegate_ = delegate;
3598 + (NSArray *) _attributeKeys {
3599 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3602 - (NSArray *) attributeKeys {
3603 return [[self class] _attributeKeys];
3606 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3607 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3610 - (NSString *) device {
3611 return [[UIDevice currentDevice] uniqueIdentifier];
3614 #if 0 // XXX: implement!
3615 - (NSString *) mac {
3616 if (![indirect_ promptForSensitive:@"Mac Address"])
3620 - (NSString *) serial {
3621 if (![indirect_ promptForSensitive:@"Serial #"])
3625 - (NSString *) firewire {
3626 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3630 - (NSString *) imei {
3631 if (![indirect_ promptForSensitive:@"IMEI"])
3636 + (NSString *) webScriptNameForSelector:(SEL)selector {
3637 if (selector == @selector(close))
3639 else if (selector == @selector(getInstalledPackages))
3640 return @"getInstalledPackages";
3641 else if (selector == @selector(getPackageById:))
3642 return @"getPackageById";
3643 else if (selector == @selector(installPackages:))
3644 return @"installPackages";
3645 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3646 return @"setButtonImage";
3647 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3648 return @"setButtonTitle";
3649 else if (selector == @selector(setPopupHook:))
3650 return @"setPopupHook";
3651 else if (selector == @selector(setSpecial:))
3652 return @"setSpecial";
3653 else if (selector == @selector(setToken:))
3655 else if (selector == @selector(setViewportWidth:))
3656 return @"setViewportWidth";
3657 else if (selector == @selector(supports:))
3659 else if (selector == @selector(stringWithFormat:arguments:))
3661 else if (selector == @selector(localizedStringForKey:value:table:))
3663 else if (selector == @selector(du:))
3665 else if (selector == @selector(statfs:))
3671 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3672 return [self webScriptNameForSelector:selector] == nil;
3675 - (BOOL) supports:(NSString *)feature {
3676 return [feature isEqualToString:@"window.open"];
3679 - (NSArray *) getInstalledPackages {
3680 NSArray *packages([[Database sharedInstance] packages]);
3681 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3682 for (Package *package in packages)
3683 if ([package installed] != nil)
3684 [installed addObject:package];
3688 - (Package *) getPackageById:(NSString *)id {
3689 Package *package([[Database sharedInstance] packageWithName:id]);
3694 - (NSArray *) statfs:(NSString *)path {
3697 if (path == nil || statfs([path UTF8String], &stat) == -1)
3700 return [NSArray arrayWithObjects:
3701 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3702 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3703 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3707 - (NSNumber *) du:(NSString *)path {
3708 NSNumber *value(nil);
3711 _assert(pipe(fds) != -1);
3713 pid_t pid(ExecFork());
3715 _assert(dup2(fds[1], 1) != -1);
3716 _assert(close(fds[0]) != -1);
3717 _assert(close(fds[1]) != -1);
3718 /* XXX: this should probably not use du */
3719 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3724 _assert(close(fds[1]) != -1);
3726 if (FILE *du = fdopen(fds[0], "r")) {
3728 while (fgets(line, sizeof(line), du) != NULL) {
3729 size_t length(strlen(line));
3730 while (length != 0 && line[length - 1] == '\n')
3731 line[--length] = '\0';
3732 if (char *tab = strchr(line, '\t')) {
3734 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3739 } else _assert(close(fds[0]));
3743 if (waitpid(pid, &status, 0) == -1)
3746 else _assert(false);
3755 - (void) installPackages:(NSArray *)packages {
3756 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3759 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3760 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3763 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3764 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3767 - (void) setSpecial:(id)function {
3768 [indirect_ setSpecial:function];
3771 - (void) setToken:(NSString *)token {
3774 Token_ = [token retain];
3776 [Metadata_ setObject:Token_ forKey:@"Token"];
3780 - (void) setPopupHook:(id)function {
3781 [indirect_ setPopupHook:function];
3784 - (void) setViewportWidth:(float)width {
3785 [indirect_ setViewportWidth:width];
3788 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3789 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3790 unsigned count([arguments count]);
3792 for (unsigned i(0); i != count; ++i)
3793 values[i] = [arguments objectAtIndex:i];
3794 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3797 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3798 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3800 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3802 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3808 /* Cydia Browser Controller {{{ */
3809 @interface CYBrowserController : BrowserController {
3810 CydiaObject *cydia_;
3815 @implementation CYBrowserController
3822 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3825 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3826 [super webView:view didClearWindowObject:window forFrame:frame];
3828 WebDataSource *source([frame dataSource]);
3829 NSURLResponse *response([source response]);
3830 NSURL *url([response URL]);
3831 NSString *scheme([url scheme]);
3833 NSHTTPURLResponse *http;
3834 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3835 http = (NSHTTPURLResponse *) response;
3839 NSDictionary *headers([http allHeaderFields]);
3840 NSString *host([url host]);
3841 [self setHeaders:headers forHost:host];
3844 [host isEqualToString:@"cydia.saurik.com"] ||
3845 [host hasSuffix:@".cydia.saurik.com"] ||
3846 [scheme isEqualToString:@"file"]
3848 [window setValue:cydia_ forKey:@"cydia"];
3851 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3852 if (System_ != NULL)
3853 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3854 if (Machine_ != NULL)
3855 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3857 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3859 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3862 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3863 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3864 [self _setMoreHeaders:copy];
3868 - (void) setDelegate:(id)delegate {
3869 [super setDelegate:delegate];
3870 [cydia_ setDelegate:delegate];
3874 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3875 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3877 WebView *webview([[webview_ _documentView] webView]);
3879 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3881 NSString *application = package == nil ? @"Cydia" : [NSString
3882 stringWithFormat:@"Cydia/%@",
3887 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3889 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3890 if (Product_ != nil)
3891 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3893 [webview setApplicationNameForUserAgent:application];
3900 /* Confirmation {{{ */
3901 @protocol ConfirmationControllerDelegate
3902 - (void) cancelAndClear:(bool)clear;
3903 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3907 @interface ConfirmationController : CYBrowserController {
3908 _transient Database *database_;
3909 UIAlertView *essential_;
3916 - (id) initWithDatabase:(Database *)database;
3920 @implementation ConfirmationController
3927 if (essential_ != nil)
3928 [essential_ release];
3932 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3933 NSString *context([alert context]);
3935 if ([context isEqualToString:@"remove"]) {
3936 if (button == [alert cancelButtonIndex]) {
3937 [self dismissModalViewControllerAnimated:YES];
3938 } else if (button == [alert firstOtherButtonIndex]) {
3941 [delegate_ confirmWithNavigationController:[self navigationController]];
3944 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3945 } else if ([context isEqualToString:@"unable"]) {
3946 [self dismissModalViewControllerAnimated:YES];
3947 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3949 [super alertView:alert clickedButtonAtIndex:button];
3953 - (void) _doContinue {
3954 [self dismissModalViewControllerAnimated:YES];
3955 [delegate_ cancelAndClear:NO];
3958 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
3959 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
3963 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3964 [super webView:view didClearWindowObject:window forFrame:frame];
3965 [window setValue:changes_ forKey:@"changes"];
3966 [window setValue:issues_ forKey:@"issues"];
3967 [window setValue:sizes_ forKey:@"sizes"];
3968 [window setValue:self forKey:@"queue"];
3971 - (id) initWithDatabase:(Database *)database {
3972 if ((self = [super init]) != nil) {
3973 database_ = database;
3975 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
3977 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3978 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3979 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3980 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3981 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3985 pkgDepCache::Policy *policy([database_ policy]);
3987 pkgCacheFile &cache([database_ cache]);
3988 NSArray *packages = [database_ packages];
3989 for (Package *package in packages) {
3990 pkgCache::PkgIterator iterator = [package iterator];
3991 pkgDepCache::StateCache &state(cache[iterator]);
3993 NSString *name([package name]);
3995 if (state.NewInstall())
3996 [installing addObject:name];
3997 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3998 [reinstalling addObject:name];
3999 else if (state.Upgrade())
4000 [upgrading addObject:name];
4001 else if (state.Downgrade())
4002 [downgrading addObject:name];
4003 else if (state.Delete()) {
4004 if ([package essential])
4006 [removing addObject:name];
4009 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4010 substrate_ |= DepSubstrate(iterator.CurrentVer());
4015 else if (Advanced_) {
4016 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4018 essential_ = [[UIAlertView alloc]
4019 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4020 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4022 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4023 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4026 [essential_ setContext:@"remove"];
4028 essential_ = [[UIAlertView alloc]
4029 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4030 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4032 cancelButtonTitle:UCLocalize("OKAY")
4033 otherButtonTitles:nil
4036 [essential_ setContext:@"unable"];
4039 changes_ = [[NSArray alloc] initWithObjects:
4047 issues_ = [database_ issues];
4049 issues_ = [issues_ retain];
4051 sizes_ = [[NSArray alloc] initWithObjects:
4052 SizeString([database_ fetcher].FetchNeeded()),
4053 SizeString([database_ fetcher].PartialPresent()),
4056 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4058 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4059 initWithTitle:UCLocalize("CANCEL")
4060 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4061 style:UIBarButtonItemStylePlain
4063 action:@selector(cancelButtonClicked)
4068 - (void) applyRightButton {
4069 #if !AlwaysReload && !IgnoreInstall
4070 if (issues_ == nil && ![self isLoading])
4071 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4072 initWithTitle:UCLocalize("CONFIRM")
4073 style:UIBarButtonItemStylePlain
4075 action:@selector(confirmButtonClicked)
4078 [super applyRightButton];
4080 [[self navigationItem] setRightBarButtonItem:nil];
4084 - (void) cancelButtonClicked {
4085 [self dismissModalViewControllerAnimated:YES];
4086 [delegate_ cancelAndClear:YES];
4090 - (void) confirmButtonClicked {
4094 if (essential_ != nil)
4099 [delegate_ confirmWithNavigationController:[self navigationController]];
4107 /* Progress Data {{{ */
4108 @interface ProgressData : NSObject {
4110 // XXX: should these really both be _transient?
4111 _transient id target_;
4112 _transient id object_;
4115 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4122 @implementation ProgressData
4124 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4125 if ((self = [super init]) != nil) {
4126 selector_ = selector;
4146 /* Progress Controller {{{ */
4147 @interface ProgressController : CYViewController <
4148 ConfigurationDelegate,
4151 _transient Database *database_;
4152 UIProgressBar *progress_;
4153 UITextView *output_;
4154 UITextLabel *status_;
4155 UIPushButton *close_;
4157 SHA1SumValue springlist_;
4158 SHA1SumValue notifyconf_;
4162 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4164 - (void) _retachThread;
4165 - (void) _detachNewThreadData:(ProgressData *)data;
4166 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4172 @protocol ProgressControllerDelegate
4173 - (void) progressControllerIsComplete:(ProgressController *)sender;
4176 @implementation ProgressController
4179 [database_ setDelegate:nil];
4180 [progress_ release];
4189 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4190 if ((self = [super init]) != nil) {
4191 database_ = database;
4192 [database_ setDelegate:self];
4193 delegate_ = delegate;
4195 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4197 progress_ = [[UIProgressBar alloc] init];
4198 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4199 [progress_ setStyle:0];
4201 status_ = [[UITextLabel alloc] init];
4202 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4203 [status_ setColor:[UIColor whiteColor]];
4204 [status_ setBackgroundColor:[UIColor clearColor]];
4205 [status_ setCentersHorizontally:YES];
4206 //[status_ setFont:font];
4208 output_ = [[UITextView alloc] init];
4210 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4211 //[output_ setTextFont:@"Courier New"];
4212 [output_ setFont:[[output_ font] fontWithSize:12]];
4213 [output_ setTextColor:[UIColor whiteColor]];
4214 [output_ setBackgroundColor:[UIColor clearColor]];
4215 [output_ setMarginTop:0];
4216 [output_ setAllowsRubberBanding:YES];
4217 [output_ setEditable:NO];
4218 [[self view] addSubview:output_];
4220 close_ = [[UIPushButton alloc] init];
4221 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4222 [close_ setAutosizesToFit:NO];
4223 [close_ setDrawsShadow:YES];
4224 [close_ setStretchBackground:YES];
4225 [close_ setEnabled:YES];
4226 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4227 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4228 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4229 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4233 - (void) positionViews {
4234 CGRect bounds = [[self view] bounds];
4235 CGSize prgsize = [UIProgressBar defaultSize];
4238 (bounds.size.width - prgsize.width) / 2,
4239 bounds.size.height - prgsize.height - 20
4242 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4244 [progress_ setFrame:prgrect];
4245 [status_ setFrame:CGRectMake(
4247 bounds.size.height - prgsize.height - 50,
4248 bounds.size.width - 20,
4251 [output_ setFrame:CGRectMake(
4254 bounds.size.width - 20,
4255 bounds.size.height - 62
4257 [close_ setFrame:CGRectMake(
4258 (bounds.size.width - closewidth) / 2,
4259 bounds.size.height - prgsize.height - 50,
4265 - (void) viewWillAppear:(BOOL)animated {
4266 [super viewDidAppear:animated];
4267 [[self navigationItem] setHidesBackButton:YES];
4268 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4270 [self positionViews];
4273 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4274 [self positionViews];
4277 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4278 NSString *context([alert context]);
4280 if ([context isEqualToString:@"conffile"]) {
4281 FILE *input = [database_ input];
4282 if (button == [alert cancelButtonIndex])
4283 fprintf(input, "N\n");
4284 else if (button == [alert firstOtherButtonIndex])
4285 fprintf(input, "Y\n");
4290 - (void) closeButtonPushed {
4293 UpdateExternalStatus(0);
4297 [self dismissModalViewControllerAnimated:YES];
4301 [delegate_ terminateWithSuccess];
4302 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4303 [delegate_ suspendWithAnimation:YES];
4305 [delegate_ suspend];*/
4309 system("launchctl stop com.apple.SpringBoard");
4313 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4322 - (void) _retachThread {
4323 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4325 [[self view] addSubview:close_];
4326 [progress_ removeFromSuperview];
4327 [status_ removeFromSuperview];
4329 [database_ popErrorWithTitle:title_];
4330 [delegate_ progressControllerIsComplete:self];
4334 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4337 MMap mmap(file, MMap::ReadOnly);
4339 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4340 if (!(notifyconf_ == sha1.Result()))
4347 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4350 MMap mmap(file, MMap::ReadOnly);
4352 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4353 if (!(springlist_ == sha1.Result()))
4359 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4360 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4361 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4362 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4363 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4366 system("su -c /usr/bin/uicache mobile");
4368 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4370 [delegate_ setStatusBarShowsProgress:NO];
4373 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4374 [[data target] performSelector:[data selector] withObject:[data object]];
4375 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4378 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4379 UpdateExternalStatus(1);
4386 title_ = [title retain];
4388 [[self navigationItem] setTitle:title_];
4390 [status_ setText:nil];
4391 [output_ setText:@""];
4392 [progress_ setProgress:0];
4394 [close_ removeFromSuperview];
4395 [[self view] addSubview:progress_];
4396 [[self view] addSubview:status_];
4398 [delegate_ setStatusBarShowsProgress:YES];
4403 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4406 MMap mmap(file, MMap::ReadOnly);
4408 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4409 notifyconf_ = sha1.Result();
4415 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4418 MMap mmap(file, MMap::ReadOnly);
4420 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4421 springlist_ = sha1.Result();
4426 detachNewThreadSelector:@selector(_detachNewThreadData:)
4428 withObject:[[[ProgressData alloc]
4429 initWithSelector:selector
4436 - (void) repairWithSelector:(SEL)selector {
4438 detachNewThreadSelector:selector
4441 title:UCLocalize("REPAIRING")
4445 - (void) setConfigurationData:(NSString *)data {
4447 performSelectorOnMainThread:@selector(_setConfigurationData:)
4453 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4454 CYActionSheet *sheet([[[CYActionSheet alloc]
4456 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4457 defaultButtonIndex:0
4460 [sheet setMessage:error];
4461 [sheet yieldToPopupAlertAnimated:YES];
4465 - (void) setProgressTitle:(NSString *)title {
4467 performSelectorOnMainThread:@selector(_setProgressTitle:)
4473 - (void) setProgressPercent:(float)percent {
4475 performSelectorOnMainThread:@selector(_setProgressPercent:)
4476 withObject:[NSNumber numberWithFloat:percent]
4481 - (void) startProgress {
4484 - (void) addProgressOutput:(NSString *)output {
4486 performSelectorOnMainThread:@selector(_addProgressOutput:)
4492 - (bool) isCancelling:(size_t)received {
4496 - (void) _setConfigurationData:(NSString *)data {
4497 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4499 if (!conffile_r(data)) {
4500 lprintf("E:invalid conffile\n");
4504 NSString *ofile = conffile_r[1];
4505 //NSString *nfile = conffile_r[2];
4507 UIAlertView *alert = [[[UIAlertView alloc]
4508 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4509 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4511 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4512 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4513 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4517 [alert setContext:@"conffile"];
4521 - (void) _setProgressTitle:(NSString *)title {
4522 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4523 for (size_t i(0), e([words count]); i != e; ++i) {
4524 NSString *word([words objectAtIndex:i]);
4525 if (Package *package = [database_ packageWithName:word])
4526 [words replaceObjectAtIndex:i withObject:[package name]];
4529 [status_ setText:[words componentsJoinedByString:@" "]];
4532 - (void) _setProgressPercent:(NSNumber *)percent {
4533 [progress_ setProgress:[percent floatValue]];
4536 - (void) _addProgressOutput:(NSString *)output {
4537 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4538 CGSize size = [output_ contentSize];
4539 CGRect rect = {{0, size.height}, {size.width, 0}};
4540 [output_ scrollRectToVisible:rect animated:YES];
4543 - (BOOL) isRunning {
4550 /* Cell Content View {{{ */
4551 @protocol ContentDelegate
4552 - (void) drawContentRect:(CGRect)rect;
4555 @interface ContentView : UIView {
4556 _transient id<ContentDelegate> delegate_;
4561 @implementation ContentView
4563 - (id) initWithFrame:(CGRect)frame {
4564 if ((self = [super initWithFrame:frame]) != nil) {
4565 [self setNeedsDisplayOnBoundsChange:YES];
4569 - (void) setDelegate:(id<ContentDelegate>)delegate {
4570 delegate_ = delegate;
4573 - (void) drawRect:(CGRect)rect {
4574 [super drawRect:rect];
4575 [delegate_ drawContentRect:rect];
4580 /* Cydia TableView Cell {{{ */
4581 @interface CYTableViewCell : UITableViewCell {
4582 ContentView *content_;
4588 @implementation CYTableViewCell
4595 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4596 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4598 if (view == content_) {
4599 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4600 highlighted_ = highlighted;
4603 [super _updateHighlightColorsForView:view highlighted:highlighted];
4606 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4607 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4608 highlighted_ = selected;
4610 [super setSelected:selected animated:animated];
4611 [content_ setNeedsDisplay];
4616 /* Package Cell {{{ */
4617 @interface PackageCell : CYTableViewCell <
4622 NSString *description_;
4630 - (PackageCell *) init;
4631 - (void) setPackage:(Package *)package;
4633 + (int) heightForPackage:(Package *)package;
4634 - (void) drawContentRect:(CGRect)rect;
4638 @implementation PackageCell
4640 - (void) clearPackage {
4651 if (description_ != nil) {
4652 [description_ release];
4656 if (source_ != nil) {
4661 if (badge_ != nil) {
4666 if (placard_ != nil) {
4676 [self clearPackage];
4680 - (PackageCell *) init {
4681 CGRect frame(CGRectMake(0, 0, 320, 74));
4682 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4683 UIView *content([self contentView]);
4684 CGRect bounds([content bounds]);
4686 content_ = [[ContentView alloc] initWithFrame:bounds];
4687 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4688 [content addSubview:content_];
4690 [content_ setDelegate:self];
4691 [content_ setOpaque:YES];
4695 - (void) _setBackgroundColor {
4697 if (NSString *mode = [package_ mode]) {
4698 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4699 color = remove ? RemovingColor_ : InstallingColor_;
4701 color = [UIColor whiteColor];
4703 [content_ setBackgroundColor:color];
4704 [self setNeedsDisplay];
4707 - (void) setPackage:(Package *)package {
4708 [self clearPackage];
4711 Source *source = [package source];
4713 icon_ = [[package icon] retain];
4714 name_ = [[package name] retain];
4717 description_ = [package longDescription];
4718 if (description_ == nil)
4719 description_ = [package shortDescription];
4720 if (description_ != nil)
4721 description_ = [description_ retain];
4723 commercial_ = [package isCommercial];
4725 package_ = [package retain];
4727 NSString *label = nil;
4728 bool trusted = false;
4730 if (source != nil) {
4731 label = [source label];
4732 trusted = [source trusted];
4733 } else if ([[package id] isEqualToString:@"firmware"])
4734 label = UCLocalize("APPLE");
4736 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4738 NSString *from(label);
4740 NSString *section = [package simpleSection];
4741 if (section != nil && ![section isEqualToString:label]) {
4742 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4743 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4746 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4747 source_ = [from retain];
4749 if (NSString *purpose = [package primaryPurpose])
4750 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4751 badge_ = [badge_ retain];
4753 if ([package installed] != nil)
4754 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4755 placard_ = [placard_ retain];
4757 [self _setBackgroundColor];
4758 [content_ setNeedsDisplay];
4761 - (void) drawContentRect:(CGRect)rect {
4762 bool highlighted(highlighted_);
4763 float width([self bounds].size.width);
4766 CGContextRef context(UIGraphicsGetCurrentContext());
4767 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4768 CGContextFillRect(context, rect);
4773 rect.size = [icon_ size];
4775 rect.size.width /= 2;
4776 rect.size.height /= 2;
4778 rect.origin.x = 25 - rect.size.width / 2;
4779 rect.origin.y = 25 - rect.size.height / 2;
4781 [icon_ drawInRect:rect];
4784 if (badge_ != nil) {
4785 CGSize size = [badge_ size];
4787 [badge_ drawAtPoint:CGPointMake(
4788 36 - size.width / 2,
4789 36 - size.height / 2
4797 UISetColor(commercial_ ? Purple_ : Black_);
4798 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4799 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4802 UISetColor(commercial_ ? Purplish_ : Gray_);
4803 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4805 if (placard_ != nil)
4806 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4809 + (int) heightForPackage:(Package *)package {
4815 /* Section Cell {{{ */
4816 @interface SectionCell : CYTableViewCell <
4828 - (void) setSection:(Section *)section editing:(BOOL)editing;
4832 @implementation SectionCell
4834 - (void) clearSection {
4835 if (basic_ != nil) {
4840 if (section_ != nil) {
4850 if (count_ != nil) {
4857 [self clearSection];
4863 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4864 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4865 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4866 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4867 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4869 UIView *content([self contentView]);
4870 CGRect bounds([content bounds]);
4872 content_ = [[ContentView alloc] initWithFrame:bounds];
4873 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4874 [content addSubview:content_];
4875 [content_ setBackgroundColor:[UIColor whiteColor]];
4877 [content_ setDelegate:self];
4881 - (void) onSwitch:(id)sender {
4882 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4883 if (metadata == nil) {
4884 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4885 [Sections_ setObject:metadata forKey:basic_];
4889 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4892 - (void) setSection:(Section *)section editing:(BOOL)editing {
4893 if (editing != editing_) {
4895 [switch_ removeFromSuperview];
4897 [self addSubview:switch_];
4901 [self clearSection];
4903 if (section == nil) {
4904 name_ = [UCLocalize("ALL_PACKAGES") retain];
4907 basic_ = [section name];
4909 basic_ = [basic_ retain];
4911 section_ = [section localized];
4912 if (section_ != nil)
4913 section_ = [section_ retain];
4915 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4916 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4919 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4922 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4923 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
4925 [content_ setNeedsDisplay];
4928 - (void) setFrame:(CGRect)frame {
4929 [super setFrame:frame];
4931 CGRect rect([switch_ frame]);
4932 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4935 - (void) drawContentRect:(CGRect)rect {
4936 bool highlighted(highlighted_);
4938 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4943 float width(rect.size.width);
4949 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4951 CGSize size = [count_ sizeWithFont:Font14_];
4955 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4961 /* File Table {{{ */
4962 @interface FileTable : CYViewController <
4963 UITableViewDataSource,
4966 _transient Database *database_;
4969 NSMutableArray *files_;
4973 - (id) initWithDatabase:(Database *)database;
4974 - (void) setPackage:(Package *)package;
4978 @implementation FileTable
4981 if (package_ != nil)
4990 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
4991 return files_ == nil ? 0 : [files_ count];
4994 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
4998 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
4999 static NSString *reuseIdentifier = @"Cell";
5001 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5003 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5004 [cell setFont:[UIFont systemFontOfSize:16]];
5006 [cell setText:[files_ objectAtIndex:indexPath.row]];
5007 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5012 - (id) initWithDatabase:(Database *)database {
5013 if ((self = [super init]) != nil) {
5014 database_ = database;
5016 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5018 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5020 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5021 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5022 [list_ setRowHeight:24.0f];
5023 [[self view] addSubview:list_];
5025 [list_ setDataSource:self];
5026 [list_ setDelegate:self];
5030 - (void) setPackage:(Package *)package {
5031 if (package_ != nil) {
5032 [package_ autorelease];
5041 [files_ removeAllObjects];
5043 if (package != nil) {
5044 package_ = [package retain];
5045 name_ = [[package id] retain];
5047 if (NSArray *files = [package files])
5048 [files_ addObjectsFromArray:files];
5050 if ([files_ count] != 0) {
5051 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5052 [files_ removeObjectAtIndex:0];
5053 [files_ sortUsingSelector:@selector(compareByPath:)];
5055 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5056 [stack addObject:@"/"];
5058 for (int i(0), e([files_ count]); i != e; ++i) {
5059 NSString *file = [files_ objectAtIndex:i];
5060 while (![file hasPrefix:[stack lastObject]])
5061 [stack removeLastObject];
5062 NSString *directory = [stack lastObject];
5063 [stack addObject:[file stringByAppendingString:@"/"]];
5064 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5065 ([stack count] - 2) * 3, "",
5066 [file substringFromIndex:[directory length]]
5075 - (void) reloadData {
5076 [self setPackage:[database_ packageWithName:name_]];
5081 /* Package Controller {{{ */
5082 @interface PackageController : CYBrowserController <
5083 UIActionSheetDelegate
5085 _transient Database *database_;
5089 NSMutableArray *buttons_;
5090 UIBarButtonItem *button_;
5093 - (id) initWithDatabase:(Database *)database;
5094 - (void) setPackage:(Package *)package;
5098 @implementation PackageController
5101 if (package_ != nil)
5115 if ([self retainCount] == 1)
5116 [delegate_ setPackageController:self];
5120 /* XXX: this is not safe at all... localization of /fail/ */
5121 - (void) _clickButtonWithName:(NSString *)name {
5122 if ([name isEqualToString:UCLocalize("CLEAR")])
5123 [delegate_ clearPackage:package_];
5124 else if ([name isEqualToString:UCLocalize("INSTALL")])
5125 [delegate_ installPackage:package_];
5126 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5127 [delegate_ installPackage:package_];
5128 else if ([name isEqualToString:UCLocalize("REMOVE")])
5129 [delegate_ removePackage:package_];
5130 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5131 [delegate_ installPackage:package_];
5132 else _assert(false);
5135 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5136 NSString *context([sheet context]);
5138 if ([context isEqualToString:@"modify"]) {
5139 if (button != [sheet cancelButtonIndex]) {
5140 NSString *buttonName = [buttons_ objectAtIndex:button];
5141 [self _clickButtonWithName:buttonName];
5144 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5148 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5149 [super webView:view didClearWindowObject:window forFrame:frame];
5150 [window setValue:package_ forKey:@"package"];
5153 - (bool) _allowJavaScriptPanel {
5158 - (void) _customButtonClicked {
5159 int count([buttons_ count]);
5164 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5166 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5167 [buttons addObjectsFromArray:buttons_];
5169 UIActionSheet *sheet = [[[UIActionSheet alloc]
5172 cancelButtonTitle:nil
5173 destructiveButtonTitle:nil
5174 otherButtonTitles:nil
5177 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5179 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5180 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5182 [sheet setContext:@"modify"];
5184 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5188 // We don't want to allow non-commercial packages to do custom things to the install button,
5189 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5190 - (void) customButtonClicked {
5192 [super customButtonClicked];
5194 [self _customButtonClicked];
5197 - (void) reloadButtonClicked {
5198 // Don't reload a package view by clicking the button.
5201 - (void) applyLoadingTitle {
5202 // Don't show "Loading" as the title. Ever.
5205 - (UIBarButtonItem *) rightButton {
5210 - (id) initWithDatabase:(Database *)database {
5211 if ((self = [super init]) != nil) {
5212 database_ = database;
5213 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5214 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5218 - (void) setPackage:(Package *)package {
5219 if (package_ != nil) {
5220 [package_ autorelease];
5229 [buttons_ removeAllObjects];
5231 if (package != nil) {
5234 package_ = [package retain];
5235 name_ = [[package id] retain];
5236 commercial_ = [package isCommercial];
5238 if ([package_ mode] != nil)
5239 [buttons_ addObject:UCLocalize("CLEAR")];
5240 if ([package_ source] == nil);
5241 else if ([package_ upgradableAndEssential:NO])
5242 [buttons_ addObject:UCLocalize("UPGRADE")];
5243 else if ([package_ uninstalled])
5244 [buttons_ addObject:UCLocalize("INSTALL")];
5246 [buttons_ addObject:UCLocalize("REINSTALL")];
5247 if (![package_ uninstalled])
5248 [buttons_ addObject:UCLocalize("REMOVE")];
5255 switch ([buttons_ count]) {
5256 case 0: title = nil; break;
5257 case 1: title = [buttons_ objectAtIndex:0]; break;
5258 default: title = UCLocalize("MODIFY"); break;
5261 button_ = [[UIBarButtonItem alloc]
5263 style:UIBarButtonItemStylePlain
5265 action:@selector(customButtonClicked)
5271 - (bool) isLoading {
5272 return commercial_ ? [super isLoading] : false;
5275 - (void) reloadData {
5276 [self setPackage:[database_ packageWithName:name_]];
5281 /* Package Table {{{ */
5282 @interface PackageTable : UIView <
5283 UITableViewDataSource,
5286 _transient Database *database_;
5287 NSMutableArray *packages_;
5288 NSMutableArray *sections_;
5290 NSMutableArray *index_;
5291 NSMutableDictionary *indices_;
5292 // XXX: this target_ seems to be delegate_. :(
5293 _transient id target_;
5295 // XXX: why do we even have this delegate_?
5296 _transient id delegate_;
5299 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5301 - (void) setDelegate:(id)delegate;
5303 - (void) reloadData;
5304 - (void) resetCursor;
5306 - (UITableView *) list;
5308 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5310 - (void) deselectWithAnimation:(BOOL)animated;
5314 @implementation PackageTable
5317 [packages_ release];
5318 [sections_ release];
5326 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5327 NSInteger count([sections_ count]);
5328 return count == 0 ? 1 : count;
5331 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5332 if ([sections_ count] == 0)
5334 return [[sections_ objectAtIndex:section] name];
5337 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5338 if ([sections_ count] == 0)
5340 return [[sections_ objectAtIndex:section] count];
5343 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5344 Section *section([sections_ objectAtIndex:[path section]]);
5345 NSInteger row([path row]);
5346 Package *package([packages_ objectAtIndex:([section row] + row)]);
5350 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5351 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5353 cell = [[[PackageCell alloc] init] autorelease];
5354 [cell setPackage:[self packageAtIndexPath:path]];
5358 - (void) deselectWithAnimation:(BOOL)animated {
5359 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5362 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5363 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5366 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5367 Package *package([self packageAtIndexPath:path]);
5368 package = [database_ packageWithName:[package id]];
5369 [target_ performSelector:action_ withObject:package];
5373 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5374 return [packages_ count] > 20 ? index_ : nil;
5377 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5381 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5382 if ((self = [super initWithFrame:frame]) != nil) {
5383 database_ = database;
5388 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5389 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5391 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5392 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5394 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5395 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5396 [list_ setRowHeight:73.0f];
5397 [self addSubview:list_];
5399 [list_ setDataSource:self];
5400 [list_ setDelegate:self];
5404 - (void) setDelegate:(id)delegate {
5405 delegate_ = delegate;
5408 - (bool) hasPackage:(Package *)package {
5412 - (void) reloadData {
5413 NSArray *packages = [database_ packages];
5415 [packages_ removeAllObjects];
5416 [sections_ removeAllObjects];
5418 _profile(PackageTable$reloadData$Filter)
5419 for (Package *package in packages)
5420 if ([self hasPackage:package])
5421 [packages_ addObject:package];
5424 [index_ removeAllObjects];
5425 [indices_ removeAllObjects];
5427 Section *section = nil;
5429 _profile(PackageTable$reloadData$Section)
5430 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5434 _profile(PackageTable$reloadData$Section$Package)
5435 package = [packages_ objectAtIndex:offset];
5436 index = [package index];
5439 if (section == nil || [section index] != index) {
5440 _profile(PackageTable$reloadData$Section$Allocate)
5441 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5444 [index_ addObject:[section name]];
5445 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5447 _profile(PackageTable$reloadData$Section$Add)
5448 [sections_ addObject:section];
5452 [section addToCount];
5456 _profile(PackageTable$reloadData$List)
5461 - (void) resetCursor {
5462 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5465 - (UITableView *) list {
5469 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5470 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5475 /* Filtered Package Table {{{ */
5476 @interface FilteredPackageTable : PackageTable {
5482 - (void) setObject:(id)object;
5483 - (void) setObject:(id)object forFilter:(SEL)filter;
5485 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5489 @implementation FilteredPackageTable
5497 - (void) setFilter:(SEL)filter {
5500 /* XXX: this is an unsafe optimization of doomy hell */
5501 Method method(class_getInstanceMethod([Package class], filter));
5502 _assert(method != NULL);
5503 imp_ = method_getImplementation(method);
5504 _assert(imp_ != NULL);
5507 - (void) setObject:(id)object {
5513 object_ = [object retain];
5516 - (void) setObject:(id)object forFilter:(SEL)filter {
5517 [self setFilter:filter];
5518 [self setObject:object];
5521 - (bool) hasPackage:(Package *)package {
5522 _profile(FilteredPackageTable$hasPackage)
5523 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5527 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5528 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5529 [self setFilter:filter];
5530 object_ = [object retain];
5538 /* Filtered Package Controller {{{ */
5539 @interface FilteredPackageController : CYViewController {
5540 _transient Database *database_;
5541 FilteredPackageTable *packages_;
5545 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5549 @implementation FilteredPackageController
5552 [packages_ release];
5558 - (void) viewDidAppear:(BOOL)animated {
5559 [super viewDidAppear:animated];
5560 [packages_ deselectWithAnimation:animated];
5563 - (void) didSelectPackage:(Package *)package {
5564 PackageController *view([delegate_ packageController]);
5565 [view setPackage:package];
5566 [view setDelegate:delegate_];
5567 [[self navigationController] pushViewController:view animated:YES];
5570 - (NSString *) title { return title_; }
5572 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5573 if ((self = [super init]) != nil) {
5574 database_ = database;
5575 title_ = [title copy];
5576 [[self navigationItem] setTitle:title_];
5578 packages_ = [[FilteredPackageTable alloc]
5579 initWithFrame:[[self view] bounds]
5582 action:@selector(didSelectPackage:)
5587 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5588 [[self view] addSubview:packages_];
5592 - (void) reloadData {
5593 [packages_ reloadData];
5596 - (void) setDelegate:(id)delegate {
5597 [super setDelegate:delegate];
5598 [packages_ setDelegate:delegate];
5605 /* Add Source Controller {{{ */
5606 @interface AddSourceController : CYViewController {
5607 _transient Database *database_;
5610 - (id) initWithDatabase:(Database *)database;
5614 @implementation AddSourceController
5616 - (id) initWithDatabase:(Database *)database {
5617 if ((self = [super init]) != nil) {
5618 database_ = database;
5624 /* Source Cell {{{ */
5625 @interface SourceCell : CYTableViewCell <
5630 NSString *description_;
5634 - (void) setSource:(Source *)source;
5638 @implementation SourceCell
5640 - (void) clearSource {
5643 [description_ release];
5652 - (void) setSource:(Source *)source {
5656 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5658 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5659 icon_ = [icon_ retain];
5661 origin_ = [[source name] retain];
5662 label_ = [[source uri] retain];
5663 description_ = [[source description] retain];
5665 [content_ setNeedsDisplay];
5673 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5674 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5675 UIView *content([self contentView]);
5676 CGRect bounds([content bounds]);
5678 content_ = [[ContentView alloc] initWithFrame:bounds];
5679 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5680 [content_ setBackgroundColor:[UIColor whiteColor]];
5681 [content addSubview:content_];
5683 [content_ setDelegate:self];
5684 [content_ setOpaque:YES];
5688 - (void) drawContentRect:(CGRect)rect {
5689 bool highlighted(highlighted_);
5690 float width(rect.size.width);
5693 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5700 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5704 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5708 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5713 /* Source Table {{{ */
5714 @interface SourceTable : CYViewController <
5715 UITableViewDataSource,
5718 _transient Database *database_;
5720 NSMutableArray *sources_;
5724 UIProgressHUD *hud_;
5727 //NSURLConnection *installer_;
5728 NSURLConnection *trivial_;
5729 NSURLConnection *trivial_bz2_;
5730 NSURLConnection *trivial_gz_;
5731 //NSURLConnection *automatic_;
5736 - (id) initWithDatabase:(Database *)database;
5738 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5742 @implementation SourceTable
5744 - (void) _releaseConnection:(NSURLConnection *)connection {
5745 if (connection != nil) {
5746 [connection cancel];
5747 //[connection setDelegate:nil];
5748 [connection release];
5760 //[self _releaseConnection:installer_];
5761 [self _releaseConnection:trivial_];
5762 [self _releaseConnection:trivial_gz_];
5763 [self _releaseConnection:trivial_bz2_];
5764 //[self _releaseConnection:automatic_];
5771 - (void) viewDidAppear:(BOOL)animated {
5772 [super viewDidAppear:animated];
5773 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5776 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5777 return offset_ == 0 ? 1 : 2;
5780 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5781 switch (section + (offset_ == 0 ? 1 : 0)) {
5782 case 0: return UCLocalize("ENTERED_BY_USER");
5783 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5789 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5790 int count = [sources_ count];
5792 case 0: return (offset_ == 0 ? count : offset_);
5793 case 1: return count - offset_;
5799 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5801 switch (indexPath.section) {
5802 case 0: idx = indexPath.row; break;
5803 case 1: idx = indexPath.row + offset_; break;
5807 return [sources_ objectAtIndex:idx];
5810 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5811 Source *source = [self sourceAtIndexPath:indexPath];
5812 return [source description] == nil ? 56 : 73;
5815 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5816 static NSString *cellIdentifier = @"SourceCell";
5818 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5819 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5820 [cell setSource:[self sourceAtIndexPath:indexPath]];
5825 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5826 return UITableViewCellAccessoryDisclosureIndicator;
5829 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5830 Source *source = [self sourceAtIndexPath:indexPath];
5832 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5833 initWithDatabase:database_
5834 title:[source label]
5835 filter:@selector(isVisibleInSource:)
5839 [packages setDelegate:delegate_];
5841 [[self navigationController] pushViewController:packages animated:YES];
5844 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5845 Source *source = [self sourceAtIndexPath:indexPath];
5846 return [source record] != nil;
5849 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5850 Source *source = [self sourceAtIndexPath:indexPath];
5851 [Sources_ removeObjectForKey:[source key]];
5852 [delegate_ syncData];
5856 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5859 @"./", @"Distribution",
5860 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5862 [delegate_ syncData];
5865 - (NSString *) getWarning {
5866 NSString *href(href_);
5867 NSRange colon([href rangeOfString:@"://"]);
5868 if (colon.location != NSNotFound)
5869 href = [href substringFromIndex:(colon.location + 3)];
5870 href = [href stringByAddingPercentEscapes];
5871 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5872 href = [href stringByCachingURLWithCurrentCDN];
5874 NSURL *url([NSURL URLWithString:href]);
5876 NSStringEncoding encoding;
5877 NSError *error(nil);
5879 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5880 return [warning length] == 0 ? nil : warning;
5884 - (void) _endConnection:(NSURLConnection *)connection {
5885 // XXX: the memory management in this method is horribly awkward
5887 NSURLConnection **field = NULL;
5888 if (connection == trivial_)
5890 else if (connection == trivial_bz2_)
5891 field = &trivial_bz2_;
5892 else if (connection == trivial_gz_)
5893 field = &trivial_gz_;
5894 _assert(field != NULL);
5895 [connection release];
5900 trivial_bz2_ == nil &&
5906 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5909 UIAlertView *alert = [[[UIAlertView alloc]
5910 initWithTitle:UCLocalize("SOURCE_WARNING")
5913 cancelButtonTitle:UCLocalize("CANCEL")
5914 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5917 [alert setContext:@"warning"];
5918 [alert setNumberOfRows:1];
5922 } else if (error_ != nil) {
5923 UIAlertView *alert = [[[UIAlertView alloc]
5924 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5925 message:[error_ localizedDescription]
5927 cancelButtonTitle:UCLocalize("OK")
5928 otherButtonTitles:nil
5931 [alert setContext:@"urlerror"];
5934 UIAlertView *alert = [[[UIAlertView alloc]
5935 initWithTitle:UCLocalize("NOT_REPOSITORY")
5936 message:UCLocalize("NOT_REPOSITORY_EX")
5938 cancelButtonTitle:UCLocalize("OK")
5939 otherButtonTitles:nil
5942 [alert setContext:@"trivial"];
5946 [delegate_ setStatusBarShowsProgress:NO];
5947 [delegate_ removeProgressHUD:hud_];
5957 if (error_ != nil) {
5964 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5965 switch ([response statusCode]) {
5971 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5972 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5974 error_ = [error retain];
5975 [self _endConnection:connection];
5978 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5979 [self _endConnection:connection];
5982 - (NSString *) title { return UCLocalize("SOURCES"); }
5984 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5985 NSMutableURLRequest *request = [NSMutableURLRequest
5986 requestWithURL:[NSURL URLWithString:href]
5987 cachePolicy:NSURLRequestUseProtocolCachePolicy
5988 timeoutInterval:120.0
5991 [request setHTTPMethod:method];
5993 if (Machine_ != NULL)
5994 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5995 if (UniqueID_ != nil)
5996 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5998 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6000 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6003 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6004 NSString *context([alert context]);
6006 if ([context isEqualToString:@"source"]) {
6009 NSString *href = [[alert textField] text];
6011 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6013 if (![href hasSuffix:@"/"])
6014 href_ = [href stringByAppendingString:@"/"];
6017 href_ = [href_ retain];
6019 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6020 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6021 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6022 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6026 // XXX: this is stupid
6027 hud_ = [[delegate_ addProgressHUD] retain];
6028 [hud_ setText:UCLocalize("VERIFYING_URL")];
6037 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6038 } else if ([context isEqualToString:@"trivial"])
6039 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6040 else if ([context isEqualToString:@"urlerror"])
6041 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6042 else if ([context isEqualToString:@"warning"]) {
6057 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6061 - (id) initWithDatabase:(Database *)database {
6062 if ((self = [super init]) != nil) {
6063 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6064 [self updateButtonsForEditingStatus:NO animated:NO];
6066 database_ = database;
6067 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6069 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6070 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6071 [[self view] addSubview:list_];
6073 [list_ setDataSource:self];
6074 [list_ setDelegate:self];
6080 - (void) reloadData {
6082 if (!list.ReadMainList())
6085 [sources_ removeAllObjects];
6086 [sources_ addObjectsFromArray:[database_ sources]];
6088 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6091 int count([sources_ count]);
6093 for (int i = 0; i != count; i++) {
6094 if ([[sources_ objectAtIndex:i] record] == nil)
6099 [list_ setEditing:NO];
6100 [self updateButtonsForEditingStatus:NO animated:NO];
6104 - (void) addButtonClicked {
6105 /*[book_ pushPage:[[[AddSourceController alloc]
6110 UIAlertView *alert = [[[UIAlertView alloc]
6111 initWithTitle:UCLocalize("ENTER_APT_URL")
6114 cancelButtonTitle:UCLocalize("CANCEL")
6115 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6118 [alert setContext:@"source"];
6119 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6121 [alert setNumberOfRows:1];
6122 [alert addTextFieldWithValue:@"http://" label:@""];
6124 UITextInputTraits *traits = [[alert textField] textInputTraits];
6125 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6126 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6127 [traits setKeyboardType:UIKeyboardTypeURL];
6128 // XXX: UIReturnKeyDone
6129 [traits setReturnKeyType:UIReturnKeyNext];
6134 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6135 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6136 initWithTitle:UCLocalize("ADD")
6137 style:UIBarButtonItemStylePlain
6139 action:@selector(addButtonClicked)
6140 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6142 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6143 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6144 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6146 action:@selector(editButtonClicked)
6147 ] autorelease] animated:animated];
6149 if (IsWildcat_ && !editing)
6150 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6151 initWithTitle:UCLocalize("SETTINGS")
6152 style:UIBarButtonItemStylePlain
6154 action:@selector(settingsButtonClicked)
6158 - (void) settingsButtonClicked {
6159 [delegate_ showSettings];
6162 - (void) editButtonClicked {
6163 [list_ setEditing:![list_ isEditing] animated:YES];
6165 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6171 /* Installed Controller {{{ */
6172 @interface InstalledController : FilteredPackageController {
6176 - (id) initWithDatabase:(Database *)database;
6178 - (void) updateRoleButton;
6179 - (void) queueStatusDidChange;
6183 @implementation InstalledController
6189 - (NSString *) title { return UCLocalize("INSTALLED"); }
6191 - (id) initWithDatabase:(Database *)database {
6192 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
6193 [self updateRoleButton];
6194 [self queueStatusDidChange];
6199 - (void) queueButtonClicked {
6204 - (void) queueStatusDidChange {
6208 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6209 initWithTitle:UCLocalize("QUEUE")
6210 style:UIBarButtonItemStyleDone
6212 action:@selector(queueButtonClicked)
6215 [[self navigationItem] setLeftBarButtonItem:nil];
6221 - (void) reloadData {
6222 [packages_ reloadData];
6225 - (void) updateRoleButton {
6226 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6227 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6228 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6229 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6231 action:@selector(roleButtonClicked)
6235 - (void) roleButtonClicked {
6236 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6237 [packages_ reloadData];
6240 [self updateRoleButton];
6243 - (void) setDelegate:(id)delegate {
6244 [super setDelegate:delegate];
6245 [packages_ setDelegate:delegate];
6251 /* Home Controller {{{ */
6252 @interface HomeController : CYBrowserController {
6257 @implementation HomeController
6259 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6260 [super _setMoreHeaders:request];
6263 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6264 if (UniqueID_ != nil)
6265 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6267 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6270 - (void) aboutButtonClicked {
6271 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6273 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6274 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6275 [alert setCancelButtonIndex:0];
6278 @"Copyright (C) 2008-2010\n"
6279 "Jay Freeman (saurik)\n"
6280 "saurik@saurik.com\n"
6281 "http://www.saurik.com/"
6287 - (void) viewWillAppear:(BOOL)animated {
6288 [super viewWillAppear:animated];
6289 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6292 - (void) viewWillDisappear:(BOOL)animated {
6293 [super viewWillDisappear:animated];
6294 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6298 if ((self = [super init]) != nil) {
6299 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6300 initWithTitle:UCLocalize("ABOUT")
6301 style:UIBarButtonItemStylePlain
6303 action:@selector(aboutButtonClicked)
6310 /* Manage Controller {{{ */
6311 @interface ManageController : CYBrowserController {
6314 - (void) queueStatusDidChange;
6317 @implementation ManageController
6320 if ((self = [super init]) != nil) {
6321 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6323 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6324 initWithTitle:UCLocalize("SETTINGS")
6325 style:UIBarButtonItemStylePlain
6327 action:@selector(settingsButtonClicked)
6330 [self queueStatusDidChange];
6334 - (void) settingsButtonClicked {
6335 [delegate_ showSettings];
6339 - (void) queueButtonClicked {
6343 - (void) applyLoadingTitle {
6344 // No "Loading" title.
6347 - (void) applyRightButton {
6352 - (void) queueStatusDidChange {
6354 if (!IsWildcat_ && Queuing_) {
6355 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6356 initWithTitle:UCLocalize("QUEUE")
6357 style:UIBarButtonItemStyleDone
6359 action:@selector(queueButtonClicked)
6362 [[self navigationItem] setRightBarButtonItem:nil];
6367 - (bool) isLoading {
6374 /* Refresh Bar {{{ */
6375 @interface RefreshBar : UINavigationBar {
6376 UIProgressIndicator *indicator_;
6377 UITextLabel *prompt_;
6378 UIProgressBar *progress_;
6379 UINavigationButton *cancel_;
6384 @implementation RefreshBar
6387 [indicator_ release];
6389 [progress_ release];
6394 - (void) positionViews {
6395 CGRect frame = [cancel_ frame];
6396 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6397 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6398 [cancel_ setFrame:frame];
6400 CGSize prgsize = {75, 100};
6402 [self frame].size.width - prgsize.width - 10,
6403 ([self frame].size.height - prgsize.height) / 2
6405 [progress_ setFrame:prgrect];
6407 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6408 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6409 CGRect indrect = {{indoffset, indoffset}, indsize};
6410 [indicator_ setFrame:indrect];
6412 CGSize prmsize = {215, indsize.height + 4};
6414 indoffset * 2 + indsize.width,
6415 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6417 [prompt_ setFrame:prmrect];
6420 - (void)setFrame:(CGRect)frame {
6421 [super setFrame:frame];
6423 [self positionViews];
6426 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6427 if ((self = [super initWithFrame:frame])) {
6428 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6430 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6431 [self setBarStyle:UIBarStyleBlack];
6433 UIBarStyle barstyle([self _barStyle:NO]);
6434 bool ugly(barstyle == UIBarStyleDefault);
6436 UIProgressIndicatorStyle style = ugly ?
6437 UIProgressIndicatorStyleMediumBrown :
6438 UIProgressIndicatorStyleMediumWhite;
6440 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6441 [indicator_ setStyle:style];
6442 [indicator_ startAnimation];
6443 [self addSubview:indicator_];
6445 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6446 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6447 [prompt_ setBackgroundColor:[UIColor clearColor]];
6448 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6449 [self addSubview:prompt_];
6451 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6452 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6453 [progress_ setStyle:0];
6454 [self addSubview:progress_];
6456 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6457 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6458 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6459 [cancel_ setBarStyle:barstyle];
6461 [self positionViews];
6466 [cancel_ removeFromSuperview];
6470 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6471 [progress_ setProgress:0];
6472 [self addSubview:cancel_];
6476 [cancel_ removeFromSuperview];
6479 - (void) setPrompt:(NSString *)prompt {
6480 [prompt_ setText:prompt];
6483 - (void) setProgress:(float)progress {
6484 [progress_ setProgress:progress];
6490 @class CYNavigationController;
6492 /* Cydia Tab Bar Controller {{{ */
6493 @interface CYTabBarController : UITabBarController {
6494 _transient Database *database_;
6499 @implementation CYTabBarController
6501 /* XXX: some logic should probably go here related to
6502 freeing the view controllers on tab change */
6504 - (void) reloadData {
6505 size_t count([[self viewControllers] count]);
6506 for (size_t i(0); i != count; ++i) {
6507 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6512 - (id) initWithDatabase:(Database *)database {
6513 if ((self = [super init]) != nil) {
6514 database_ = database;
6521 /* Cydia Navigation Controller {{{ */
6522 @interface CYNavigationController : UINavigationController {
6523 _transient Database *database_;
6524 _transient id<UINavigationControllerDelegate> delegate_;
6527 - (id) initWithDatabase:(Database *)database;
6528 - (void) reloadData;
6533 @implementation CYNavigationController
6535 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6536 // Inherit autorotation settings for modal parents.
6537 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6538 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6540 return [super shouldAutorotateToInterfaceOrientation:orientation];
6548 - (void) reloadData {
6549 size_t count([[self viewControllers] count]);
6550 for (size_t i(0); i != count; ++i) {
6551 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6556 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6557 delegate_ = delegate;
6560 - (id) initWithDatabase:(Database *)database {
6561 if ((self = [super init]) != nil) {
6562 database_ = database;
6568 /* Cydia:// Protocol {{{ */
6569 @interface CydiaURLProtocol : NSURLProtocol {
6574 @implementation CydiaURLProtocol
6576 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6577 NSURL *url([request URL]);
6580 NSString *scheme([[url scheme] lowercaseString]);
6581 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6586 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6590 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6591 id<NSURLProtocolClient> client([self client]);
6593 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6595 NSData *data(UIImagePNGRepresentation(icon));
6597 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6598 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6599 [client URLProtocol:self didLoadData:data];
6600 [client URLProtocolDidFinishLoading:self];
6604 - (void) startLoading {
6605 id<NSURLProtocolClient> client([self client]);
6606 NSURLRequest *request([self request]);
6608 NSURL *url([request URL]);
6609 NSString *href([url absoluteString]);
6611 NSString *path([href substringFromIndex:8]);
6612 NSRange slash([path rangeOfString:@"/"]);
6615 if (slash.location == NSNotFound) {
6619 command = [path substringToIndex:slash.location];
6620 path = [path substringFromIndex:(slash.location + 1)];
6623 Database *database([Database sharedInstance]);
6625 if ([command isEqualToString:@"package-icon"]) {
6628 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6629 Package *package([database packageWithName:path]);
6632 UIImage *icon([package icon]);
6633 [self _returnPNGWithImage:icon forRequest:request];
6634 } else if ([command isEqualToString:@"source-icon"]) {
6637 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6638 NSString *source(Simplify(path));
6639 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6641 icon = [UIImage applicationImageNamed:@"unknown.png"];
6642 [self _returnPNGWithImage:icon forRequest:request];
6643 } else if ([command isEqualToString:@"uikit-image"]) {
6646 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6647 UIImage *icon(_UIImageWithName(path));
6648 [self _returnPNGWithImage:icon forRequest:request];
6649 } else if ([command isEqualToString:@"section-icon"]) {
6652 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6653 NSString *section(Simplify(path));
6654 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6656 icon = [UIImage applicationImageNamed:@"unknown.png"];
6657 [self _returnPNGWithImage:icon forRequest:request];
6659 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6663 - (void) stopLoading {
6669 /* Sections Controller {{{ */
6670 @interface SectionsController : CYViewController <
6671 UITableViewDataSource,
6674 _transient Database *database_;
6675 NSMutableArray *sections_;
6676 NSMutableArray *filtered_;
6682 - (id) initWithDatabase:(Database *)database;
6683 - (void) reloadData;
6686 - (void) editButtonClicked;
6690 @implementation SectionsController
6693 [list_ setDataSource:nil];
6694 [list_ setDelegate:nil];
6696 [sections_ release];
6697 [filtered_ release];
6699 [accessory_ release];
6703 - (void) viewDidAppear:(BOOL)animated {
6704 [super viewDidAppear:animated];
6705 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6708 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6709 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6713 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6714 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6717 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6721 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6722 static NSString *reuseIdentifier = @"SectionCell";
6724 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6726 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6728 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6733 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6737 Section *section = [self sectionAtIndexPath:indexPath];
6738 NSString *name = [section name];
6741 if ([indexPath row] == 0) {
6744 title = UCLocalize("ALL_PACKAGES");
6747 name = [NSString stringWithString:name];
6748 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6751 title = UCLocalize("NO_SECTION");
6755 FilteredPackageController *table = [[[FilteredPackageController alloc]
6756 initWithDatabase:database_
6758 filter:@selector(isVisibleInSection:)
6762 [table setDelegate:delegate_];
6764 [[self navigationController] pushViewController:table animated:YES];
6767 - (NSString *) title { return UCLocalize("SECTIONS"); }
6769 - (id) initWithDatabase:(Database *)database {
6770 if ((self = [super init]) != nil) {
6771 database_ = database;
6773 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6775 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6776 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6778 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6779 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6780 [list_ setRowHeight:45.0f];
6781 [[self view] addSubview:list_];
6783 [list_ setDataSource:self];
6784 [list_ setDelegate:self];
6790 - (void) reloadData {
6791 NSArray *packages = [database_ packages];
6793 [sections_ removeAllObjects];
6794 [filtered_ removeAllObjects];
6796 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6799 for (Package *package in packages) {
6800 NSString *name([package section]);
6801 NSString *key(name == nil ? @"" : name);
6805 _profile(SectionsView$reloadData$Section)
6806 section = [sections objectForKey:key];
6807 if (section == nil) {
6808 _profile(SectionsView$reloadData$Section$Allocate)
6809 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6810 [sections setObject:section forKey:key];
6815 [section addToCount];
6817 _profile(SectionsView$reloadData$Filter)
6818 if (![package valid] || ![package visible])
6826 [sections_ addObjectsFromArray:[sections allValues]];
6828 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6830 for (Section *section in sections_) {
6831 size_t count([section row]);
6835 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6836 [section setCount:count];
6837 [filtered_ addObject:section];
6840 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6841 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
6842 style:UIBarButtonItemStylePlain
6844 action:@selector(editButtonClicked)
6845 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6851 - (void) resetView {
6853 [self editButtonClicked];
6856 - (void) editButtonClicked {
6857 if ((editing_ = !editing_))
6860 [delegate_ updateData];
6862 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6863 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6864 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6867 - (UIView *) accessoryView {
6873 /* Changes Controller {{{ */
6874 @interface ChangesController : CYViewController <
6875 UITableViewDataSource,
6878 _transient Database *database_;
6879 CFMutableArrayRef packages_;
6880 NSMutableArray *sections_;
6883 BOOL hasSentFirstLoad_;
6886 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6887 - (void) reloadData;
6891 @implementation ChangesController
6894 [list_ setDelegate:nil];
6895 [list_ setDataSource:nil];
6897 CFRelease(packages_);
6899 [sections_ release];
6904 - (void) viewDidAppear:(BOOL)animated {
6905 [super viewDidAppear:animated];
6906 if (!hasSentFirstLoad_) {
6907 hasSentFirstLoad_ = YES;
6908 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6910 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6914 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6915 NSInteger count([sections_ count]);
6916 return count == 0 ? 1 : count;
6919 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6920 if ([sections_ count] == 0)
6922 return [[sections_ objectAtIndex:section] name];
6925 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6926 if ([sections_ count] == 0)
6928 return [[sections_ objectAtIndex:section] count];
6931 - (Package *) packageAtIndex:(NSUInteger)index {
6932 return (Package *) CFArrayGetValueAtIndex(packages_, index);
6935 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6936 Section *section([sections_ objectAtIndex:[path section]]);
6937 NSInteger row([path row]);
6938 return [self packageAtIndex:([section row] + row)];
6941 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6942 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6944 cell = [[[PackageCell alloc] init] autorelease];
6945 [cell setPackage:[self packageAtIndexPath:path]];
6949 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
6950 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
6953 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6954 Package *package([self packageAtIndexPath:path]);
6955 PackageController *view([delegate_ packageController]);
6956 [view setDelegate:delegate_];
6957 [view setPackage:package];
6958 [[self navigationController] pushViewController:view animated:YES];
6962 - (void) refreshButtonClicked {
6963 [delegate_ beginUpdate];
6964 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
6967 - (void) upgradeButtonClicked {
6968 [delegate_ distUpgrade];
6971 - (NSString *) title { return UCLocalize("CHANGES"); }
6973 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
6974 if ((self = [super init]) != nil) {
6975 database_ = database;
6976 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
6978 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
6980 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6982 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6983 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6984 [list_ setRowHeight:73.0f];
6985 [[self view] addSubview:list_];
6987 [list_ setDataSource:self];
6988 [list_ setDelegate:self];
6990 delegate_ = delegate;
6994 - (void) _reloadPackages:(NSArray *)packages {
6996 for (Package *package in packages)
6997 if ([package upgradableAndEssential:YES] || [package visible])
6998 CFArrayAppendValue(packages_, package);
7001 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7005 - (void) reloadData {
7006 NSArray *packages = [database_ packages];
7008 CFArrayRemoveAllValues(packages_);
7010 [sections_ removeAllObjects];
7013 UIProgressHUD *hud([delegate_ addProgressHUD]);
7014 [hud setText:UCLocalize("LOADING")];
7015 //NSLog(@"HUD:%@::%@", delegate_, hud);
7016 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7017 [delegate_ removeProgressHUD:hud];
7019 [self _reloadPackages:packages];
7022 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7023 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7024 Section *section = nil;
7028 bool unseens = false;
7030 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7032 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7033 Package *package = [self packageAtIndex:offset];
7035 BOOL uae = [package upgradableAndEssential:YES];
7041 _profile(ChangesController$reloadData$Remember)
7042 seen = [package seen];
7045 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7050 name = UCLocalize("UNKNOWN");
7052 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7056 _profile(ChangesController$reloadData$Allocate)
7057 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7058 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7059 [sections_ addObject:section];
7063 [section addToCount];
7064 } else if ([package ignored])
7065 [ignored addToCount];
7068 [upgradable addToCount];
7073 CFRelease(formatter);
7076 Section *last = [sections_ lastObject];
7077 size_t count = [last count];
7078 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7079 [sections_ removeLastObject];
7082 if ([ignored count] != 0)
7083 [sections_ insertObject:ignored atIndex:0];
7085 [sections_ insertObject:upgradable atIndex:0];
7090 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7091 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7092 style:UIBarButtonItemStylePlain
7094 action:@selector(upgradeButtonClicked)
7097 if (![delegate_ updating])
7098 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7099 initWithTitle:UCLocalize("REFRESH")
7100 style:UIBarButtonItemStylePlain
7102 action:@selector(refreshButtonClicked)
7108 /* Search Controller {{{ */
7109 @interface SearchController : FilteredPackageController <
7112 UISearchBar *search_;
7115 - (id) initWithDatabase:(Database *)database;
7116 - (void) reloadData;
7120 @implementation SearchController
7127 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7128 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7129 [search_ resignFirstResponder];
7133 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7134 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7138 - (NSString *) title { return nil; }
7140 - (id) initWithDatabase:(Database *)database {
7141 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7144 - (void)viewDidAppear:(BOOL)animated {
7145 [super viewDidAppear:animated];
7147 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7148 [search_ layoutSubviews];
7149 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7150 UITextField *textField = [search_ searchField];
7151 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7152 [search_ setDelegate:self];
7153 [textField setEnablesReturnKeyAutomatically:NO];
7154 [[self navigationItem] setTitleView:textField];
7158 - (void) _reloadData {
7161 - (void) reloadData {
7162 _profile(SearchController$reloadData)
7163 [packages_ reloadData];
7166 [packages_ resetCursor];
7169 - (void) didSelectPackage:(Package *)package {
7170 [search_ resignFirstResponder];
7171 [super didSelectPackage:package];
7176 /* Settings Controller {{{ */
7177 @interface SettingsController : CYViewController <
7178 UITableViewDataSource,
7181 _transient Database *database_;
7184 UITableView *table_;
7185 UISwitch *subscribedSwitch_;
7186 UISwitch *ignoredSwitch_;
7187 UITableViewCell *subscribedCell_;
7188 UITableViewCell *ignoredCell_;
7191 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7195 @implementation SettingsController
7199 if (package_ != nil)
7202 [subscribedSwitch_ release];
7203 [ignoredSwitch_ release];
7204 [subscribedCell_ release];
7205 [ignoredCell_ release];
7210 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7211 if (package_ == nil)
7217 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7218 if (package_ == nil)
7224 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7225 return UCLocalize("SHOW_ALL_CHANGES_EX");
7228 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7229 if (package_ == nil)
7232 NSMutableDictionary *metadata([package_ metadata]);
7235 if (NSNumber *number = [metadata objectForKey:key])
7236 before = [number boolValue];
7240 if (value != before) {
7241 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7243 [delegate_ updateData];
7247 - (void) onSubscribed:(id)control {
7248 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7251 - (void) onIgnored:(id)control {
7252 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
7255 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7256 if (package_ == nil)
7259 switch ([indexPath row]) {
7260 case 0: return subscribedCell_;
7261 case 1: return ignoredCell_;
7269 - (NSString *) title { return UCLocalize("SETTINGS"); }
7271 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7272 if ((self = [super init])) {
7273 database_ = database;
7274 name_ = [package retain];
7276 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7278 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7279 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7280 [[self view] addSubview:table_];
7282 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7283 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7284 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7286 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7287 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7288 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7290 subscribedCell_ = [[UITableViewCell alloc] init];
7291 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7292 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7293 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7295 ignoredCell_ = [[UITableViewCell alloc] init];
7296 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7297 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7298 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7300 [table_ setDataSource:self];
7301 [table_ setDelegate:self];
7306 - (void) reloadData {
7307 if (package_ != nil)
7308 [package_ autorelease];
7309 package_ = [database_ packageWithName:name_];
7310 if (package_ != nil) {
7312 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7313 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7316 [table_ reloadData];
7321 /* Signature Controller {{{ */
7322 @interface SignatureController : CYBrowserController {
7323 _transient Database *database_;
7327 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7331 @implementation SignatureController
7338 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7340 [super webView:view didClearWindowObject:window forFrame:frame];
7343 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7344 if ((self = [super init]) != nil) {
7345 database_ = database;
7346 package_ = [package retain];
7351 - (void) reloadData {
7352 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7358 /* Role Controller {{{ */
7359 @interface RoleController : CYViewController <
7360 UITableViewDataSource,
7363 _transient Database *database_;
7364 // XXX: ok, "roledelegate_"?...
7365 _transient id roledelegate_;
7366 UITableView *table_;
7367 UISegmentedControl *segment_;
7371 - (void) showDoneButton;
7372 - (void) resizeSegmentedControl;
7376 @implementation RoleController
7380 [container_ release];
7385 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7386 if ((self = [super init])) {
7387 database_ = database;
7388 roledelegate_ = delegate;
7390 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7392 NSArray *items = [NSArray arrayWithObjects:
7394 UCLocalize("HACKER"),
7395 UCLocalize("DEVELOPER"),
7397 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7398 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7399 [container_ addSubview:segment_];
7402 if ([Role_ isEqualToString:@"User"]) index = 0;
7403 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7404 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7406 [segment_ setSelectedSegmentIndex:index];
7407 [self showDoneButton];
7410 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7411 [self resizeSegmentedControl];
7413 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7414 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7415 [table_ setDelegate:self];
7416 [table_ setDataSource:self];
7417 [[self view] addSubview:table_];
7418 [table_ reloadData];
7422 - (void) resizeSegmentedControl {
7423 CGFloat width = [[self view] frame].size.width;
7424 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7427 - (void) viewWillAppear:(BOOL)animated {
7428 [super viewWillAppear:animated];
7430 [self resizeSegmentedControl];
7433 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7434 [self resizeSegmentedControl];
7437 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7438 [self resizeSegmentedControl];
7442 NSString *role(nil);
7444 switch ([segment_ selectedSegmentIndex]) {
7445 case 0: role = @"User"; break;
7446 case 1: role = @"Hacker"; break;
7447 case 2: role = @"Developer"; break;
7452 if (![role isEqualToString:Role_]) {
7453 bool rolling(Role_ == nil);
7456 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7460 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7465 [roledelegate_ loadData];
7467 [roledelegate_ updateData];
7471 - (void) segmentChanged:(UISegmentedControl *)control {
7472 [self showDoneButton];
7475 - (void) saveAndClose {
7478 [[self navigationItem] setRightBarButtonItem:nil];
7479 [[self navigationController] dismissModalViewControllerAnimated:YES];
7482 - (void) doneButtonClicked {
7483 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7484 [spinner startAnimating];
7485 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7486 [[self navigationItem] setRightBarButtonItem:spinItem];
7488 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7491 - (void) showDoneButton {
7492 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7493 initWithTitle:UCLocalize("DONE")
7494 style:UIBarButtonItemStyleDone
7496 action:@selector(doneButtonClicked)
7497 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
7500 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7501 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7505 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7509 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7510 return nil; // This method is required by the protocol.
7513 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7515 return UCLocalize("ROLE_EX");
7517 return [NSString stringWithFormat:
7518 @"%@: %@\n%@: %@\n%@: %@",
7519 UCLocalize("USER"), UCLocalize("USER_EX"),
7520 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7521 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7526 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7527 return section == 3 ? 44.0f : 0;
7530 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7531 return section == 3 ? container_ : nil;
7536 /* Stash Controller {{{ */
7537 @interface CYStashController : CYViewController {
7538 // XXX: just delete these things
7539 _transient UIActivityIndicatorView *spinner_;
7540 _transient UILabel *status_;
7541 _transient UILabel *caption_;
7545 @implementation CYStashController
7547 if ((self = [super init])) {
7548 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7550 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
7551 CGRect spinrect = [spinner_ frame];
7552 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7553 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7554 [spinner_ setFrame:spinrect];
7555 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7556 [[self view] addSubview:spinner_];
7557 [spinner_ startAnimating];
7560 captrect.size.width = [[self view] frame].size.width;
7561 captrect.size.height = 40.0f;
7562 captrect.origin.x = 0;
7563 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7564 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
7565 [caption_ setText:@"Initializing Filesystem"];
7566 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7567 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7568 [caption_ setTextColor:[UIColor whiteColor]];
7569 [caption_ setBackgroundColor:[UIColor clearColor]];
7570 [caption_ setShadowColor:[UIColor blackColor]];
7571 [caption_ setTextAlignment:UITextAlignmentCenter];
7572 [[self view] addSubview:caption_];
7575 statusrect.size.width = [[self view] frame].size.width;
7576 statusrect.size.height = 30.0f;
7577 statusrect.origin.x = 0;
7578 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7579 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
7580 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7581 [status_ setText:@"(Cydia will exit when complete.)"];
7582 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7583 [status_ setTextColor:[UIColor whiteColor]];
7584 [status_ setBackgroundColor:[UIColor clearColor]];
7585 [status_ setShadowColor:[UIColor blackColor]];
7586 [status_ setTextAlignment:UITextAlignmentCenter];
7587 [[self view] addSubview:status_];
7591 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7592 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7597 /* Cydia Container {{{ */
7598 @interface CYContainer : UIViewController <ProgressDelegate> {
7599 _transient Database *database_;
7600 RefreshBar *refreshbar_;
7604 // XXX: ok, "updatedelegate_"?...
7605 _transient NSObject<CydiaDelegate> *updatedelegate_;
7606 // XXX: can't we query for this variable when we need it?
7607 _transient UITabBarController *root_;
7610 - (void) setTabBarController:(UITabBarController *)controller;
7612 - (void) dropBar:(BOOL)animated;
7613 - (void) beginUpdate;
7614 - (void) raiseBar:(BOOL)animated;
7619 @implementation CYContainer
7621 - (BOOL) _reallyWantsFullScreenLayout {
7625 // NOTE: UIWindow only sends the top controller these messages,
7626 // So we have to forward them on.
7628 - (void) viewDidAppear:(BOOL)animated {
7629 [super viewDidAppear:animated];
7630 [root_ viewDidAppear:animated];
7633 - (void) viewWillAppear:(BOOL)animated {
7634 [super viewWillAppear:animated];
7635 [root_ viewWillAppear:animated];
7638 - (void) viewDidDisappear:(BOOL)animated {
7639 [super viewDidDisappear:animated];
7640 [root_ viewDidDisappear:animated];
7643 - (void) viewWillDisappear:(BOOL)animated {
7644 [super viewWillDisappear:animated];
7645 [root_ viewWillDisappear:animated];
7648 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7649 return ![updatedelegate_ hudIsShowing] && (IsWildcat_ || orientation == UIInterfaceOrientationPortrait);
7652 - (void) setTabBarController:(UITabBarController *)controller {
7654 [[self view] addSubview:[root_ view]];
7657 - (void) setUpdate:(NSDate *)date {
7661 - (void) beginUpdate {
7663 [refreshbar_ start];
7668 detachNewThreadSelector:@selector(performUpdate)
7674 - (void) performUpdate { _pooled
7676 status.setDelegate(self);
7677 [database_ updateWithStatus:status];
7680 performSelectorOnMainThread:@selector(completeUpdate)
7686 - (void) completeUpdate {
7691 [self raiseBar:YES];
7693 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7696 - (void) cancelUpdate {
7698 [self raiseBar:YES];
7700 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7703 - (void) cancelPressed {
7704 [self cancelUpdate];
7711 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7712 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7715 - (void) startProgress {
7718 - (void) setProgressTitle:(NSString *)title {
7720 performSelectorOnMainThread:@selector(_setProgressTitle:)
7726 - (bool) isCancelling:(size_t)received {
7730 - (void) setProgressPercent:(float)percent {
7732 performSelectorOnMainThread:@selector(_setProgressPercent:)
7733 withObject:[NSNumber numberWithFloat:percent]
7738 - (void) addProgressOutput:(NSString *)output {
7740 performSelectorOnMainThread:@selector(_addProgressOutput:)
7746 - (void) _setProgressTitle:(NSString *)title {
7747 [refreshbar_ setPrompt:title];
7750 - (void) _setProgressPercent:(NSNumber *)percent {
7751 [refreshbar_ setProgress:[percent floatValue]];
7754 - (void) _addProgressOutput:(NSString *)output {
7757 - (void) setUpdateDelegate:(id)delegate {
7758 updatedelegate_ = delegate;
7761 - (CGFloat) statusBarHeight {
7762 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7763 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7765 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7769 - (void) dropBar:(BOOL)animated {
7774 [[self view] addSubview:refreshbar_];
7776 CGFloat sboffset = [self statusBarHeight];
7778 CGRect barframe = [refreshbar_ frame];
7779 barframe.origin.y = sboffset;
7780 [refreshbar_ setFrame:barframe];
7783 [UIView beginAnimations:nil context:NULL];
7784 CGRect viewframe = [[root_ view] frame];
7785 viewframe.origin.y += barframe.size.height + sboffset;
7786 viewframe.size.height -= barframe.size.height + sboffset;
7787 [[root_ view] setFrame:viewframe];
7789 [UIView commitAnimations];
7791 // Ensure bar has the proper width for our view, it might have changed
7792 barframe.size.width = viewframe.size.width;
7793 [refreshbar_ setFrame:barframe];
7795 // XXX: fix Apple's layout bug
7796 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7799 - (void) raiseBar:(BOOL)animated {
7804 [refreshbar_ removeFromSuperview];
7806 CGFloat sboffset = [self statusBarHeight];
7809 [UIView beginAnimations:nil context:NULL];
7810 CGRect barframe = [refreshbar_ frame];
7811 CGRect viewframe = [[root_ view] frame];
7812 viewframe.origin.y -= barframe.size.height + sboffset;
7813 viewframe.size.height += barframe.size.height + sboffset;
7814 [[root_ view] setFrame:viewframe];
7816 [UIView commitAnimations];
7818 // XXX: fix Apple's layout bug
7819 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7822 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7823 // XXX: fix Apple's layout bug
7824 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7827 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7833 // XXX: fix Apple's layout bug
7834 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7837 - (void) statusBarFrameChanged:(NSNotification *)notification {
7845 [refreshbar_ release];
7846 [[NSNotificationCenter defaultCenter] removeObserver:self];
7850 - (id) initWithDatabase:(Database *)database {
7851 if ((self = [super init]) != nil) {
7852 database_ = database;
7854 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7855 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7857 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7874 @interface Cydia : UIApplication <
7875 ConfirmationControllerDelegate,
7876 ProgressControllerDelegate,
7878 UINavigationControllerDelegate,
7879 UITabBarControllerDelegate
7881 // XXX: evaluate all fields for _transient
7884 CYContainer *container_;
7885 CYTabBarController *tabbar_;
7887 NSMutableArray *essential_;
7888 NSMutableArray *broken_;
7890 Database *database_;
7894 UIKeyboard *keyboard_;
7897 SectionsController *sections_;
7898 ChangesController *changes_;
7899 ManageController *manage_;
7900 SearchController *search_;
7901 SourceTable *sources_;
7902 InstalledController *installed_;
7905 CYStashController *stash_;
7910 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7911 - (void) setPage:(CYViewController *)page;
7916 static _finline void _setHomePage(Cydia *self) {
7917 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7920 @implementation Cydia
7922 - (void) beginUpdate {
7923 [container_ beginUpdate];
7927 return [container_ updating];
7930 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7935 if ([broken_ count] != 0) {
7936 int count = [broken_ count];
7938 UIAlertView *alert = [[[UIAlertView alloc]
7939 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7940 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7942 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7943 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
7946 [alert setContext:@"fixhalf"];
7948 } else if (!Ignored_ && [essential_ count] != 0) {
7949 int count = [essential_ count];
7951 UIAlertView *alert = [[[UIAlertView alloc]
7952 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7953 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
7955 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
7956 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
7959 [alert setContext:@"upgrade"];
7964 - (void) _saveConfig {
7967 NSString *error(nil);
7968 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7970 NSError *error(nil);
7971 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7972 NSLog(@"failure to save metadata data: %@", error);
7975 NSLog(@"failure to serialize metadata: %@", error);
7983 - (void) _updateData {
7986 /* XXX: this is just stupid */
7987 if (tag_ != 1 && sections_ != nil)
7988 [sections_ reloadData];
7989 if (tag_ != 2 && changes_ != nil)
7990 [changes_ reloadData];
7991 if (tag_ != 4 && search_ != nil)
7992 [search_ reloadData];
7994 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
7997 - (int)indexOfTabWithTag:(int)tag {
7999 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8000 if ([[controller tabBarItem] tag] == tag)
8008 - (void) _refreshIfPossible {
8009 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8011 bool recently = false;
8012 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8013 if (update != nil) {
8014 NSTimeInterval interval([update timeIntervalSinceNow]);
8015 if (interval <= 0 && interval > -(15*60))
8019 // Don't automatic refresh if:
8020 // - We already refreshed recently.
8021 // - We already auto-refreshed this launch.
8022 // - Auto-refresh is disabled.
8023 if (recently || loaded_ || ManualRefresh) {
8024 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8026 // If we are cancelling due to ManualRefresh or a recent refresh
8027 // we need to make sure it knows it's already loaded.
8031 // We are going to load, so remember that.
8035 SCNetworkReachabilityFlags flags; {
8036 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8037 SCNetworkReachabilityGetFlags(reachability, &flags);
8038 CFRelease(reachability);
8041 // XXX: this elaborate mess is what Apple is using to determine this? :(
8042 // XXX: do we care if the user has to intervene? maybe that's ok?
8044 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8045 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8046 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8047 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8048 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8049 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8053 // If we can reach the server, auto-refresh!
8055 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8060 - (void) refreshIfPossible {
8061 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8064 - (void) _reloadData {
8065 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8066 [hud setText:UCLocalize("RELOADING_DATA")];
8068 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8071 [self removeProgressHUD:hud];
8075 [essential_ removeAllObjects];
8076 [broken_ removeAllObjects];
8078 NSArray *packages([database_ packages]);
8079 for (Package *package in packages) {
8081 [broken_ addObject:package];
8082 if ([package upgradableAndEssential:NO]) {
8083 if ([package essential])
8084 [essential_ addObject:package];
8089 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8091 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8092 [changesItem setBadgeValue:badge];
8093 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8095 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8096 [self setApplicationBadge:badge];
8098 [self setApplicationBadgeString:badge];
8100 [changesItem setBadgeValue:nil];
8101 [changesItem setAnimatedBadge:NO];
8103 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8104 [self removeApplicationBadge];
8105 else // XXX: maybe use setApplicationBadgeString also?
8106 [self setApplicationIconBadgeNumber:0];
8111 [self refreshIfPossible];
8114 - (void) updateData {
8123 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8124 _assert(file != NULL);
8126 for (NSString *key in [Sources_ allKeys]) {
8127 NSDictionary *source([Sources_ objectForKey:key]);
8129 fprintf(file, "%s %s %s\n",
8130 [[source objectForKey:@"Type"] UTF8String],
8131 [[source objectForKey:@"URI"] UTF8String],
8132 [[source objectForKey:@"Distribution"] UTF8String]
8140 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8141 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8143 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8144 [container_ presentModalViewController:navigation animated:YES];
8147 detachNewThreadSelector:@selector(update_)
8150 title:UCLocalize("UPDATING_SOURCES")
8154 - (void) reloadData {
8155 @synchronized (self) {
8161 pkgProblemResolver *resolver = [database_ resolver];
8163 resolver->InstallProtect();
8164 if (!resolver->Resolve(true))
8168 - (CGRect) popUpBounds {
8169 return [[tabbar_ view] bounds];
8173 if (![database_ prepare])
8176 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8177 [page setDelegate:self];
8178 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8179 [confirm_ setDelegate:self];
8182 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8183 [container_ presentModalViewController:confirm_ animated:YES];
8189 @synchronized (self) {
8194 - (void) clearPackage:(Package *)package {
8195 @synchronized (self) {
8202 - (void) installPackages:(NSArray *)packages {
8203 @synchronized (self) {
8204 for (Package *package in packages)
8211 - (void) installPackage:(Package *)package {
8212 @synchronized (self) {
8219 - (void) removePackage:(Package *)package {
8220 @synchronized (self) {
8227 - (void) distUpgrade {
8228 @synchronized (self) {
8229 if (![database_ upgrade])
8236 @synchronized (self) {
8241 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8242 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8244 if (navigation != nil) {
8245 [navigation pushViewController:progress animated:YES];
8247 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8249 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8250 [container_ presentModalViewController:navigation animated:YES];
8254 detachNewThreadSelector:@selector(perform)
8257 title:UCLocalize("RUNNING")
8261 - (void) progressControllerIsComplete:(ProgressController *)progress {
8265 - (void) setPage:(CYViewController *)page {
8266 [page setDelegate:self];
8268 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8269 [navController setViewControllers:[NSArray arrayWithObject:page]];
8270 for (CYNavigationController *page in [tabbar_ viewControllers])
8271 if (page != navController)
8272 [page setViewControllers:nil];
8275 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8276 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8277 [browser loadURL:url];
8281 - (SectionsController *) sectionsController {
8282 if (sections_ == nil)
8283 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8287 - (ChangesController *) changesController {
8288 if (changes_ == nil)
8289 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8293 - (ManageController *) manageController {
8294 if (manage_ == nil) {
8295 manage_ = (ManageController *) [[self
8296 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8297 withClass:[ManageController class]
8300 queueDelegate_ = manage_;
8305 - (SearchController *) searchController {
8307 search_ = [[SearchController alloc] initWithDatabase:database_];
8311 - (SourceTable *) sourcesController {
8312 if (sources_ == nil)
8313 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8317 - (InstalledController *) installedController {
8318 if (installed_ == nil) {
8319 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8321 queueDelegate_ = installed_;
8326 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8327 int tag = [[viewController tabBarItem] tag];
8329 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8331 } else if (tag_ == 1) {
8332 [[self sectionsController] resetView];
8336 case kCydiaTag: _setHomePage(self); break;
8338 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8339 case kChangesTag: [self setPage:[self changesController]]; break;
8340 case kManageTag: [self setPage:[self manageController]]; break;
8341 case kInstalledTag: [self setPage:[self installedController]]; break;
8342 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8343 case kSearchTag: [self setPage:[self searchController]]; break;
8351 - (void) showSettings {
8352 RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease];
8353 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8355 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8356 [container_ presentModalViewController:nav animated:YES];
8359 - (void) setPackageController:(PackageController *)view {
8361 [view setPackage:nil];
8365 - (PackageController *) _packageController {
8366 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8369 - (PackageController *) packageController {
8370 return [self _packageController];
8373 // Returns the navigation controller for the queuing badge.
8374 - (id) queueBadgeController {
8375 int index = [self indexOfTabWithTag:kManageTag];
8377 index = [self indexOfTabWithTag:kInstalledTag];
8379 return [[tabbar_ viewControllers] objectAtIndex:index];
8382 - (void) cancelAndClear:(bool)clear {
8383 @synchronized (self) {
8389 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
8393 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8397 [queueDelegate_ queueStatusDidChange];
8401 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8402 NSString *context([alert context]);
8404 if ([context isEqualToString:@"fixhalf"]) {
8405 if (button == [alert firstOtherButtonIndex]) {
8406 @synchronized (self) {
8407 for (Package *broken in broken_) {
8410 NSString *id = [broken id];
8411 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8412 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8413 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8414 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8420 } else if (button == [alert cancelButtonIndex]) {
8421 [broken_ removeAllObjects];
8425 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8426 } else if ([context isEqualToString:@"upgrade"]) {
8427 if (button == [alert firstOtherButtonIndex]) {
8428 @synchronized (self) {
8429 for (Package *essential in essential_)
8430 [essential install];
8435 } else if (button == [alert firstOtherButtonIndex] + 1) {
8437 } else if (button == [alert cancelButtonIndex]) {
8441 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8445 - (void) system:(NSString *)command { _pooled
8446 system([command UTF8String]);
8449 - (void) applicationWillSuspend {
8451 [super applicationWillSuspend];
8454 - (BOOL) hudIsShowing {
8458 - (void) applicationSuspend:(__GSEvent *)event {
8459 // Use external process status API internally.
8460 // This is probably a really bad idea.
8461 uint64_t status = 0;
8463 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8464 notify_get_state(notify_token, &status);
8465 notify_cancel(notify_token);
8468 if (![self hudIsShowing] && status == 0)
8469 [super applicationSuspend:event];
8472 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8473 if (![self hudIsShowing])
8474 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8477 - (void) _setSuspended:(BOOL)value {
8478 if (![self hudIsShowing])
8479 [super _setSuspended:value];
8482 - (UIProgressHUD *) addProgressHUD {
8483 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8484 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8486 [window_ setUserInteractionEnabled:NO];
8489 UIViewController *target = container_;
8490 while ([target modalViewController] != nil) target = [target modalViewController];
8491 [[target view] addSubview:hud];
8497 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8499 [hud removeFromSuperview];
8500 [window_ setUserInteractionEnabled:YES];
8504 - (CYViewController *) pageForPackage:(NSString *)name {
8505 if (Package *package = [database_ packageWithName:name]) {
8506 PackageController *view([self packageController]);
8507 [view setPackage:package];
8510 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8511 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8512 return [self _pageForURL:url withClass:[CYBrowserController class]];
8516 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8520 NSString *href([url absoluteString]);
8521 if ([href hasPrefix:@"apptapp://package/"])
8522 return [self pageForPackage:[href substringFromIndex:18]];
8524 NSString *scheme([[url scheme] lowercaseString]);
8525 if (![scheme isEqualToString:@"cydia"])
8527 NSString *path([url absoluteString]);
8528 if ([path length] < 8)
8530 path = [path substringFromIndex:8];
8531 if (![path hasPrefix:@"/"])
8532 path = [@"/" stringByAppendingString:path];
8534 if ([path isEqualToString:@"/add-source"])
8535 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8536 else if ([path isEqualToString:@"/storage"])
8537 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8538 else if ([path isEqualToString:@"/sources"])
8539 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8540 else if ([path isEqualToString:@"/packages"])
8541 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8542 else if ([path hasPrefix:@"/url/"])
8543 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8544 else if ([path hasPrefix:@"/launch/"])
8545 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8546 else if ([path hasPrefix:@"/package-settings/"])
8547 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8548 else if ([path hasPrefix:@"/package-signature/"])
8549 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8550 else if ([path hasPrefix:@"/package/"])
8551 return [self pageForPackage:[path substringFromIndex:9]];
8552 else if ([path hasPrefix:@"/files/"]) {
8553 NSString *name = [path substringFromIndex:7];
8555 if (Package *package = [database_ packageWithName:name]) {
8556 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8557 [files setPackage:package];
8565 - (void) applicationOpenURL:(NSURL *)url {
8566 [super applicationOpenURL:url];
8568 if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
8569 [self setPage:page];
8571 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8575 - (void) applicationWillResignActive:(UIApplication *)application {
8576 // Stop refreshing if you get a phone call or lock the device.
8577 if ([container_ updating])
8578 [container_ cancelUpdate];
8580 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8581 [super applicationWillResignActive:application];
8584 - (void) addStashController {
8585 stash_ = [[CYStashController alloc] init];
8586 [window_ addSubview:[stash_ view]];
8589 - (void) removeStashController {
8590 [[stash_ view] removeFromSuperview];
8595 [self setIdleTimerDisabled:YES];
8597 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8598 [self setStatusBarShowsProgress:YES];
8599 UpdateExternalStatus(1);
8601 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8603 UpdateExternalStatus(0);
8604 [self setStatusBarShowsProgress:NO];
8606 [self removeStashController];
8608 if (ExecFork() == 0) {
8609 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8610 perror("launchctl stop");
8614 - (void) setupTabBarController {
8615 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8616 [tabbar_ setDelegate:self];
8618 NSMutableArray *items([NSMutableArray arrayWithObjects:
8619 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8620 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8621 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8622 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8626 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8627 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8629 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8632 NSMutableArray *controllers([NSMutableArray array]);
8634 for (UITabBarItem *item in items) {
8635 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8636 [controller setTabBarItem:item];
8637 [controllers addObject:controller];
8640 [tabbar_ setViewControllers:controllers];
8643 - (void) applicationDidFinishLaunching:(id)unused {
8644 [CYBrowserController _initialize];
8646 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8648 Font12_ = [[UIFont systemFontOfSize:12] retain];
8649 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8650 Font14_ = [[UIFont systemFontOfSize:14] retain];
8651 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8652 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8656 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8657 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8659 UIScreen *screen([UIScreen mainScreen]);
8661 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8662 [window_ orderFront:self];
8663 [window_ makeKey:self];
8664 [window_ setHidden:NO];
8667 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8668 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8669 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8670 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8671 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8672 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8673 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8674 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8675 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8678 [self addStashController];
8679 // XXX: this would be much cleaner as a yieldToSelector:
8680 // that way the removeStashController could happen right here inline
8681 // we also could no longer require the useless stash_ field anymore
8682 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8686 database_ = [Database sharedInstance];
8688 [self setupTabBarController];
8690 container_ = [[CYContainer alloc] initWithDatabase:database_];
8691 [container_ setUpdateDelegate:self];
8692 [container_ setTabBarController:tabbar_];
8693 [window_ addSubview:[container_ view]];
8695 // Show pinstripes while loading data.
8696 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8698 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8705 [self showSettings];
8709 [window_ setUserInteractionEnabled:NO];
8711 UIView *container = [[[UIView alloc] init] autorelease];
8712 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8714 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
8715 [spinner startAnimating];
8716 [container addSubview:spinner];
8718 UILabel *label = [[[UILabel alloc] init] autorelease];
8719 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8720 [label setBackgroundColor:[UIColor clearColor]];
8721 [label setTextColor:[UIColor blackColor]];
8722 [label setShadowColor:[UIColor whiteColor]];
8723 [label setShadowOffset:CGSizeMake(0, 1)];
8724 [label setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
8725 [container addSubview:label];
8727 CGSize viewsize = [[tabbar_ view] frame].size;
8728 CGSize spinnersize = [spinner bounds].size;
8729 CGSize textsize = [[label text] sizeWithFont:[label font]];
8730 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8732 CGRect containrect = {
8733 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8734 CGSizeMake(bothwidth, spinnersize.height)
8737 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8745 [container setFrame:containrect];
8746 [spinner setFrame:spinrect];
8747 [label setFrame:textrect];
8748 [[container_ view] addSubview:container];
8753 // Show the home page
8754 [tabbar_ setSelectedIndex:0];
8756 [window_ setUserInteractionEnabled:YES];
8758 // XXX: does this actually slow anything down?
8759 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8760 [container removeFromSuperview];
8763 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8764 if (item != nil && IsWildcat_) {
8765 [sheet showFromBarButtonItem:item animated:YES];
8767 [sheet showInView:window_];
8774 id Alloc_(id self, SEL selector) {
8775 id object = alloc_(self, selector);
8776 lprintf("[%s]A-%p\n", self->isa->name, object);
8781 id Dealloc_(id self, SEL selector) {
8782 id object = dealloc_(self, selector);
8783 lprintf("[%s]D-%p\n", self->isa->name, object);
8787 Class $WebDefaultUIKitDelegate;
8789 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8790 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8791 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8792 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8795 static NSNumber *shouldPlayKeyboardSounds;
8799 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8801 case 1104: // Keyboard Button Clicked
8802 case 1105: // Keyboard Delete Repeated
8803 if (shouldPlayKeyboardSounds == nil) {
8804 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8805 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8808 if (![shouldPlayKeyboardSounds boolValue])
8812 _UIHardware$_playSystemSound$(self, _cmd, sound);
8816 int main(int argc, char *argv[]) { _pooled
8819 if (Class $UIDevice = objc_getClass("UIDevice")) {
8820 UIDevice *device([$UIDevice currentDevice]);
8821 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8825 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8827 /* Library Hacks {{{ */
8828 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8830 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8831 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8832 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8833 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8834 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8837 $UIHardware = objc_getClass("UIHardware");
8838 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8839 if (UIHardware$_playSystemSound$ != NULL) {
8840 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8841 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8844 /* Set Locale {{{ */
8845 Locale_ = CFLocaleCopyCurrent();
8846 Languages_ = [NSLocale preferredLanguages];
8847 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8848 //NSLog(@"%@", [Languages_ description]);
8851 if (Languages_ == nil || [Languages_ count] == 0)
8852 // XXX: consider just setting to C and then falling through?
8855 lang = [[Languages_ objectAtIndex:0] UTF8String];
8856 setenv("LANG", lang, true);
8859 //std::setlocale(LC_ALL, lang);
8860 NSLog(@"Setting Language: %s", lang);
8863 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8865 /* Parse Arguments {{{ */
8866 bool substrate(false);
8872 for (int argi(1); argi != argc; ++argi)
8873 if (strcmp(argv[argi], "--") == 0) {
8875 argv[argi] = argv[0];
8881 for (int argi(1); argi != arge; ++argi)
8882 if (strcmp(args[argi], "--substrate") == 0)
8885 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8889 App_ = [[NSBundle mainBundle] bundlePath];
8890 Home_ = NSHomeDirectory();
8896 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8897 alloc_ = alloc->method_imp;
8898 alloc->method_imp = (IMP) &Alloc_;*/
8900 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8901 dealloc_ = dealloc->method_imp;
8902 dealloc->method_imp = (IMP) &Dealloc_;*/
8904 /* System Information {{{ */
8908 size = sizeof(maxproc);
8909 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8910 perror("sysctlbyname(\"kern.maxproc\", ?)");
8911 else if (maxproc < 64) {
8913 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8914 perror("sysctlbyname(\"kern.maxproc\", #)");
8917 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8918 char *osversion = new char[size];
8919 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8920 perror("sysctlbyname(\"kern.osversion\", ?)");
8922 System_ = [NSString stringWithUTF8String:osversion];
8924 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8925 char *machine = new char[size];
8926 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8927 perror("sysctlbyname(\"hw.machine\", ?)");
8931 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8932 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8933 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8934 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8938 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8939 NSData *data((NSData *) ecid);
8940 size_t length([data length]);
8941 uint8_t bytes[length];
8942 [data getBytes:bytes];
8943 char string[length * 2 + 1];
8944 for (size_t i(0); i != length; ++i)
8945 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8946 ChipID_ = [NSString stringWithUTF8String:string];
8950 IOObjectRelease(service);
8954 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8956 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
8957 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
8958 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
8960 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
8961 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
8962 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
8964 if (mcc != NULL && mnc != NULL)
8965 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
8972 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8973 Build_ = [system objectForKey:@"ProductBuildVersion"];
8974 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8975 Product_ = [info objectForKey:@"SafariProductVersion"];
8976 Safari_ = [info objectForKey:@"CFBundleVersion"];
8979 /* Load Database {{{ */
8981 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8983 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8985 if (Metadata_ == NULL)
8986 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8988 Settings_ = [Metadata_ objectForKey:@"Settings"];
8990 Packages_ = [Metadata_ objectForKey:@"Packages"];
8991 Sections_ = [Metadata_ objectForKey:@"Sections"];
8992 Sources_ = [Metadata_ objectForKey:@"Sources"];
8994 Token_ = [Metadata_ objectForKey:@"Token"];
8997 if (Settings_ != nil)
8998 Role_ = [Settings_ objectForKey:@"Role"];
9000 if (Packages_ == nil) {
9001 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
9002 [Metadata_ setObject:Packages_ forKey:@"Packages"];
9005 if (Sections_ == nil) {
9006 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9007 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9010 if (Sources_ == nil) {
9011 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9012 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9016 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9018 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9019 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9020 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9021 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9022 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9023 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9025 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9027 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9028 unlink("/tmp/.cydia.fw");
9030 } else if (access("/User", F_OK) != 0 || version < 2) {
9033 system("/usr/libexec/cydia/firmware.sh");
9037 _assert([[NSFileManager defaultManager]
9038 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9039 withIntermediateDirectories:YES
9044 if (access("/tmp/cydia.chk", F_OK) == 0) {
9045 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9046 _assert(errno == ENOENT);
9047 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9048 _assert(errno == ENOENT);
9051 /* APT Initialization {{{ */
9052 _assert(pkgInitConfig(*_config));
9053 _assert(pkgInitSystem(*_config, _system));
9056 _config->Set("APT::Acquire::Translation", lang);
9058 // XXX: this timeout might be important :(
9059 //_config->Set("Acquire::http::Timeout", 15);
9061 _config->Set("Acquire::http::MaxParallel", 3);
9063 /* Color Choices {{{ */
9064 space_ = CGColorSpaceCreateDeviceRGB();
9066 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9067 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9068 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9069 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9070 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9071 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9072 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9073 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9074 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9076 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9077 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9079 /* UIKit Configuration {{{ */
9080 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9081 if ($GSFontSetUseLegacyFontMetrics != NULL)
9082 $GSFontSetUseLegacyFontMetrics(YES);
9084 // XXX: I have a feeling this was important
9085 //UIKeyboardDisableAutomaticAppearance();
9088 Colon_ = UCLocalize("COLON_DELIMITED");
9089 Elision_ = UCLocalize("ELISION");
9090 Error_ = UCLocalize("ERROR");
9091 Warning_ = UCLocalize("WARNING");
9094 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9096 CGColorSpaceRelease(space_);