1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2010 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "UICaboodle/UCPlatform.h"
45 #include "UICaboodle/UCLocalize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
111 #include <mach-o/nlist.h>
121 #include "UICaboodle/BrowserView.h"
123 #include "substrate.h"
130 #define _timestamp ({ \
132 gettimeofday(&tv, NULL); \
133 tv.tv_sec * 1000000 + tv.tv_usec; \
136 typedef std::vector<class ProfileTime *> TimeList;
146 ProfileTime(const char *name) :
150 times_.push_back(this);
153 void AddTime(uint64_t time) {
160 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
172 ProfileTimer(ProfileTime &time) :
179 time_.AddTime(_timestamp - start_);
184 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
186 std::cerr << "========" << std::endl;
189 #define _profile(name) { \
190 static ProfileTime name(#name); \
191 ProfileTimer _ ## name(name);
196 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
198 #define CYPoolStart() \
199 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
201 #define CYPoolEnd() \
205 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
207 void NSLogPoint(const char *fix, const CGPoint &point) {
208 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
211 void NSLogRect(const char *fix, const CGRect &rect) {
212 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
215 static _finline NSString *CydiaURL(NSString *path) {
217 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
218 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
219 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
220 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
221 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
222 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
225 static _finline void UpdateExternalStatus(uint64_t newStatus) {
227 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
228 notify_set_state(notify_token, newStatus);
229 notify_cancel(notify_token);
231 notify_post("com.saurik.Cydia.status");
234 /* [NSObject yieldToSelector:(withObject:)] {{{*/
235 @interface NSObject (Cydia)
236 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
237 - (id) yieldToSelector:(SEL)selector;
240 @implementation NSObject (Cydia)
245 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
246 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
247 id object([[context objectAtIndex:1] nonretainedObjectValue]);
248 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
250 /* XXX: deal with exceptions */
251 id value([self performSelector:selector withObject:object]);
253 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
254 [context removeAllObjects];
255 if ([signature methodReturnLength] != 0 && value != nil)
256 [context addObject:value];
261 performSelectorOnMainThread:@selector(doNothing)
267 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
268 /*return [self performSelector:selector withObject:object];*/
270 volatile bool stopped(false);
272 NSMutableArray *context([NSMutableArray arrayWithObjects:
273 [NSValue valueWithPointer:selector],
274 [NSValue valueWithNonretainedObject:object],
275 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
278 NSThread *thread([[[NSThread alloc]
280 selector:@selector(_yieldToContext:)
286 NSRunLoop *loop([NSRunLoop currentRunLoop]);
287 NSDate *future([NSDate distantFuture]);
289 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
291 return [context count] == 0 ? nil : [context objectAtIndex:0];
294 - (id) yieldToSelector:(SEL)selector {
295 return [self yieldToSelector:selector withObject:nil];
301 /* Cydia Action Sheet {{{ */
302 @interface CYActionSheet : UIAlertView {
306 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
309 @implementation CYActionSheet
311 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
312 if ((self = [super init])) {
313 [self setTitle:title];
314 [self setDelegate:self];
315 for (NSString *button in buttons) [self addButtonWithTitle:button];
316 [self setCancelButtonIndex:index];
320 - (void) _updateFrameForDisplay {
321 [super _updateFrameForDisplay];
322 if ([self cancelButtonIndex] == -1) {
323 NSArray *buttons = [self buttons];
324 if ([buttons count]) {
325 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
326 for (UIThreePartButton *button in buttons)
327 [button setBackground:background forState:0];
332 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
333 button_ = buttonIndex + 1;
337 [self dismissWithClickedButtonIndex:-1 animated:YES];
340 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
341 [self setRunsModal:YES];
350 /* NSForcedOrderingSearch doesn't work on the iPhone */
351 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
352 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
353 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
355 /* Information Dictionaries {{{ */
356 @interface NSMutableArray (Cydia)
357 - (void) addInfoDictionary:(NSDictionary *)info;
360 @implementation NSMutableArray (Cydia)
362 - (void) addInfoDictionary:(NSDictionary *)info {
363 [self addObject:info];
368 @interface NSMutableDictionary (Cydia)
369 - (void) addInfoDictionary:(NSDictionary *)info;
372 @implementation NSMutableDictionary (Cydia)
374 - (void) addInfoDictionary:(NSDictionary *)info {
375 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
381 #define lprintf(args...) fprintf(stderr, args)
384 #define TraceLogging (1 && !ForRelease)
385 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
386 #define ProfileTimes (0 && !ForRelease)
387 #define ForSaurik (0 && !ForRelease)
388 #define LogBrowser (0 && !ForRelease)
389 #define TrackResize (0 && !ForRelease)
390 #define ManualRefresh (1 && !ForRelease)
391 #define ShowInternals (0 && !ForRelease)
392 #define IgnoreInstall (0 && !ForRelease)
393 #define AlwaysReload (0 && !ForRelease)
397 #define _trace(args...)
402 #define _profile(name) {
405 #define PrintTimes() do {} while (false)
409 typedef uint32_t (*SKRadixFunction)(id, void *);
411 @interface NSMutableArray (Radix)
412 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
420 @implementation NSMutableArray (Radix)
422 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
423 size_t count([self count]);
424 struct RadixItem_ *swap(new RadixItem_[count * 2]);
426 for (size_t i(0); i != count; ++i) {
427 RadixItem_ &item(swap[i]);
430 id object([self objectAtIndex:i]);
431 item.key = function(object, argument);
434 struct RadixItem_ *lhs(swap), *rhs(swap + count);
436 static const size_t width = 32;
437 static const size_t bits = 11;
438 static const size_t slots = 1 << bits;
439 static const size_t passes = (width + (bits - 1)) / bits;
441 size_t *hist(new size_t[slots]);
443 for (size_t pass(0); pass != passes; ++pass) {
444 memset(hist, 0, sizeof(size_t) * slots);
446 for (size_t i(0); i != count; ++i) {
447 uint32_t key(lhs[i].key);
449 key &= _not(uint32_t) >> width - bits;
454 for (size_t i(0); i != slots; ++i) {
455 size_t local(offset);
460 for (size_t i(0); i != count; ++i) {
461 uint32_t key(lhs[i].key);
463 key &= _not(uint32_t) >> width - bits;
464 rhs[hist[key]++] = lhs[i];
467 RadixItem_ *tmp(lhs);
474 const void **values(new const void *[count]);
475 for (size_t i(0); i != count; ++i)
476 values[i] = [self objectAtIndex:lhs[i].index];
477 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
485 /* Insertion Sort {{{ */
487 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
488 const char *ptr = (const char *)list;
490 CFIndex half = count / 2;
491 const char *probe = ptr + elementSize * half;
492 CFComparisonResult cr = comparator(element, probe, context);
493 if (0 == cr) return (probe - (const char *)list) / elementSize;
494 ptr = (cr < 0) ? ptr : probe + elementSize;
495 count = (cr < 0) ? half : (half + (count & 1) - 1);
497 return (ptr - (const char *)list) / elementSize;
500 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
501 const char *ptr = (const char *)list;
503 CFIndex half = count / 2;
504 const char *probe = ptr + elementSize * half;
505 CFComparisonResult cr = comparator(element, probe, context);
506 if (0 == cr) return (probe - (const char *)list) / elementSize;
507 ptr = (cr < 0) ? ptr : probe + elementSize;
508 count = (cr < 0) ? half : (half + (count & 1) - 1);
510 return (ptr - (const char *)list) / elementSize;
513 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
514 if (range.length == 0)
516 const void **values(new const void *[range.length]);
517 CFArrayGetValues(array, range, values);
519 #if HistogramInsertionSort > 0
520 uint32_t total(0), *offsets(new uint32_t[range.length]);
523 for (CFIndex index(1); index != range.length; ++index) {
524 const void *value(values[index]);
525 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
526 CFIndex correct(index);
527 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
528 #if HistogramInsertionSort > 1
529 NSLog(@"%@ < %@", value, values[correct - 1]);
534 if (correct != index) {
535 size_t offset(index - correct);
536 #if HistogramInsertionSort
540 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
542 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
543 values[correct] = value;
547 CFArrayReplaceValues(array, range, values, range.length);
550 #if HistogramInsertionSort > 0
551 for (CFIndex index(0); index != range.length; ++index)
552 if (offsets[index] != 0)
553 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
554 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
561 /* Apple Bug Fixes {{{ */
562 @implementation UIWebDocumentView (Cydia)
564 - (void) _setScrollerOffset:(CGPoint)offset {
565 UIScroller *scroller([self _scroller]);
567 CGSize size([scroller contentSize]);
568 CGSize bounds([scroller bounds].size);
571 max.x = size.width - bounds.width;
572 max.y = size.height - bounds.height;
580 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
581 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
583 [scroller setOffset:offset];
589 @implementation WebScriptObject (NSFastEnumeration)
591 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
592 size_t length([self count] - state->state);
595 else if (length > count)
597 for (size_t i(0); i != length; ++i)
598 objects[i] = [self objectAtIndex:state->state++];
599 state->itemsPtr = objects;
600 state->mutationsPtr = (unsigned long *) self;
606 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
607 size_t length([self length] - state->state);
610 else if (length > count)
612 for (size_t i(0); i != length; ++i)
613 objects[i] = [self item:state->state++];
614 state->itemsPtr = objects;
615 state->mutationsPtr = (unsigned long *) self;
619 /* Cydia NSString Additions {{{ */
620 @interface NSString (Cydia)
621 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
622 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
623 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
624 - (NSComparisonResult) compareByPath:(NSString *)other;
625 - (NSString *) stringByCachingURLWithCurrentCDN;
626 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
629 @implementation NSString (Cydia)
631 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
632 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
635 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
636 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
637 memcpy(data, bytes, length);
638 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
641 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
642 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
645 - (NSComparisonResult) compareByPath:(NSString *)other {
646 NSString *prefix = [self commonPrefixWithString:other options:0];
647 size_t length = [prefix length];
649 NSRange lrange = NSMakeRange(length, [self length] - length);
650 NSRange rrange = NSMakeRange(length, [other length] - length);
652 lrange = [self rangeOfString:@"/" options:0 range:lrange];
653 rrange = [other rangeOfString:@"/" options:0 range:rrange];
655 NSComparisonResult value;
657 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
658 value = NSOrderedSame;
659 else if (lrange.location == NSNotFound)
660 value = NSOrderedAscending;
661 else if (rrange.location == NSNotFound)
662 value = NSOrderedDescending;
664 value = NSOrderedSame;
666 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
667 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
668 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
669 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
671 NSComparisonResult result = [lpath compare:rpath];
672 return result == NSOrderedSame ? value : result;
675 - (NSString *) stringByCachingURLWithCurrentCDN {
677 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
678 withString:@"://cache.cydia.saurik.com/"
682 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
683 return [(id)CFURLCreateStringByAddingPercentEscapes(
688 kCFStringEncodingUTF8
695 /* C++ NSString Wrapper Cache {{{ */
696 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
697 return size == 0 ? NULL :
698 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
699 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
702 static _finline CFStringRef CYStringCreate(const char *data) {
703 return CYStringCreate(data, strlen(data));
712 _finline void clear_() {
713 if (cache_ != NULL) {
720 _finline bool empty() const {
724 _finline size_t size() const {
728 _finline char *data() const {
732 _finline void clear() {
737 _finline CYString() :
744 _finline ~CYString() {
748 void operator =(const CYString &rhs) {
752 if (rhs.cache_ == nil)
755 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
758 void set(apr_pool_t *pool, const char *data, size_t size) {
764 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
765 memcpy(temp, data, size);
772 _finline void set(apr_pool_t *pool, const char *data) {
773 set(pool, data, data == NULL ? 0 : strlen(data));
776 _finline void set(apr_pool_t *pool, const std::string &rhs) {
777 set(pool, rhs.data(), rhs.size());
780 bool operator ==(const CYString &rhs) const {
781 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
784 _finline operator CFStringRef() {
786 cache_ = CYStringCreate(data_, size_);
790 _finline operator id() {
791 return (NSString *) static_cast<CFStringRef>(*this);
795 /* C++ NSString Algorithm Adapters {{{ */
797 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
800 struct NSStringMapHash :
801 std::unary_function<NSString *, size_t>
803 _finline size_t operator ()(NSString *value) const {
804 return CFStringHashNSString((CFStringRef) value);
808 struct NSStringMapLess :
809 std::binary_function<NSString *, NSString *, bool>
811 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
812 return [lhs compare:rhs] == NSOrderedAscending;
816 struct NSStringMapEqual :
817 std::binary_function<NSString *, NSString *, bool>
819 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
820 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
821 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
822 //[lhs isEqualToString:rhs];
827 /* Perl-Compatible RegEx {{{ */
837 Pcre(const char *regex) :
842 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
845 lprintf("%d:%s\n", offset, error);
849 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
850 matches_ = new int[(capture_ + 1) * 3];
858 NSString *operator [](size_t match) {
859 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
862 bool operator ()(NSString *data) {
863 // XXX: length is for characters, not for bytes
864 return operator ()([data UTF8String], [data length]);
867 bool operator ()(const char *data, size_t size) {
869 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
873 /* Mime Addresses {{{ */
874 @interface Address : NSObject {
880 - (NSString *) address;
882 - (void) setAddress:(NSString *)address;
884 + (Address *) addressWithString:(NSString *)string;
885 - (Address *) initWithString:(NSString *)string;
888 @implementation Address
897 - (NSString *) name {
901 - (NSString *) address {
905 - (void) setAddress:(NSString *)address {
907 [address_ autorelease];
911 address_ = [address retain];
914 + (Address *) addressWithString:(NSString *)string {
915 return [[[Address alloc] initWithString:string] autorelease];
918 + (NSArray *) _attributeKeys {
919 return [NSArray arrayWithObjects:@"address", @"name", nil];
922 - (NSArray *) attributeKeys {
923 return [[self class] _attributeKeys];
926 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
927 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
930 - (Address *) initWithString:(NSString *)string {
931 if ((self = [super init]) != nil) {
932 const char *data = [string UTF8String];
933 size_t size = [string length];
935 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
937 if (address_r(data, size)) {
938 name_ = [address_r[1] retain];
939 address_ = [address_r[2] retain];
941 name_ = [string retain];
949 /* CoreGraphics Primitives {{{ */
954 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
955 CGFloat color[] = {red, green, blue, alpha};
956 return CGColorCreate(space, color);
965 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
966 color_(Create_(space, red, green, blue, alpha))
968 Set(space, red, green, blue, alpha);
973 CGColorRelease(color_);
980 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
982 color_ = Create_(space, red, green, blue, alpha);
985 operator CGColorRef() {
991 /* Random Global Variables {{{ */
992 static const int PulseInterval_ = 50000;
993 static const int ButtonBarWidth_ = 60;
994 static const int ButtonBarHeight_ = 48;
995 static const float KeyboardTime_ = 0.3f;
998 static NSArray *Finishes_;
1000 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1001 #define NotifyConfig_ "/etc/notify.conf"
1003 static bool Queuing_;
1005 static CYColor Blue_;
1006 static CYColor Blueish_;
1007 static CYColor Black_;
1008 static CYColor Off_;
1009 static CYColor White_;
1010 static CYColor Gray_;
1011 static CYColor Green_;
1012 static CYColor Purple_;
1013 static CYColor Purplish_;
1015 static UIColor *InstallingColor_;
1016 static UIColor *RemovingColor_;
1018 static NSString *App_;
1019 static NSString *Home_;
1021 static BOOL Advanced_;
1022 static BOOL Ignored_;
1024 static UIFont *Font12_;
1025 static UIFont *Font12Bold_;
1026 static UIFont *Font14_;
1027 static UIFont *Font18Bold_;
1028 static UIFont *Font22Bold_;
1030 static const char *Machine_ = NULL;
1031 static NSString *System_ = nil;
1032 static NSString *SerialNumber_ = nil;
1033 static NSString *ChipID_ = nil;
1034 static NSString *Token_ = nil;
1035 static NSString *UniqueID_ = nil;
1036 static NSString *PLMN_ = nil;
1037 static NSString *Build_ = nil;
1038 static NSString *Product_ = nil;
1039 static NSString *Safari_ = nil;
1041 static CFLocaleRef Locale_;
1042 static NSArray *Languages_;
1043 static CGColorSpaceRef space_;
1045 static NSDictionary *SectionMap_;
1046 static NSMutableDictionary *Metadata_;
1047 static _transient NSMutableDictionary *Settings_;
1048 static _transient NSString *Role_;
1049 static _transient NSMutableDictionary *Packages_;
1050 static _transient NSMutableDictionary *Sections_;
1051 static _transient NSMutableDictionary *Sources_;
1052 static bool Changed_;
1053 static NSDate *now_;
1055 static bool IsWildcat_;
1058 /* Display Helpers {{{ */
1059 inline float Interpolate(float begin, float end, float fraction) {
1060 return (end - begin) * fraction + begin;
1063 /* XXX: localize this! */
1064 NSString *SizeString(double size) {
1065 bool negative = size < 0;
1070 while (size > 1024) {
1075 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1077 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1080 static _finline const char *StripVersion_(const char *version) {
1081 const char *colon(strchr(version, ':'));
1083 version = colon + 1;
1087 NSString *LocalizeSection(NSString *section) {
1088 static Pcre title_r("^(.*?) \\((.*)\\)$");
1089 if (title_r(section)) {
1090 NSString *parent(title_r[1]);
1091 NSString *child(title_r[2]);
1093 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1094 LocalizeSection(parent),
1095 LocalizeSection(child)
1099 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1102 NSString *Simplify(NSString *title) {
1103 const char *data = [title UTF8String];
1104 size_t size = [title length];
1106 static Pcre square_r("^\\[(.*)\\]$");
1107 if (square_r(data, size))
1108 return Simplify(square_r[1]);
1110 static Pcre paren_r("^\\((.*)\\)$");
1111 if (paren_r(data, size))
1112 return Simplify(paren_r[1]);
1114 static Pcre title_r("^(.*?) \\((.*)\\)$");
1115 if (title_r(data, size))
1116 return Simplify(title_r[1]);
1122 NSString *GetLastUpdate() {
1123 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1126 return UCLocalize("NEVER_OR_UNKNOWN");
1128 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1129 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1131 CFRelease(formatter);
1133 return [(NSString *) formatted autorelease];
1136 bool isSectionVisible(NSString *section) {
1137 NSDictionary *metadata([Sections_ objectForKey:section]);
1138 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1139 return hidden == nil || ![hidden boolValue];
1144 /* Delegate Prototypes {{{ */
1148 @interface NSObject (ProgressDelegate)
1151 @protocol ProgressDelegate
1152 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1153 - (void) setProgressTitle:(NSString *)title;
1154 - (void) setProgressPercent:(float)percent;
1155 - (void) startProgress;
1156 - (void) addProgressOutput:(NSString *)output;
1157 - (bool) isCancelling:(size_t)received;
1160 @protocol ConfigurationDelegate
1161 - (void) repairWithSelector:(SEL)selector;
1162 - (void) setConfigurationData:(NSString *)data;
1165 @class PackageController;
1167 @protocol CydiaDelegate
1168 - (void) setPackageController:(PackageController *)view;
1169 - (void) clearPackage:(Package *)package;
1170 - (void) installPackage:(Package *)package;
1171 - (void) installPackages:(NSArray *)packages;
1172 - (void) removePackage:(Package *)package;
1173 - (void) beginUpdate;
1175 - (void) distUpgrade;
1177 - (void) updateData;
1179 - (void) showSettings;
1180 - (UIProgressHUD *) addProgressHUD;
1181 - (BOOL) hudIsShowing;
1182 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1183 - (CYViewController *) pageForPackage:(NSString *)name;
1184 - (PackageController *) packageController;
1185 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1189 /* Status Delegation {{{ */
1191 public pkgAcquireStatus
1194 _transient NSObject<ProgressDelegate> *delegate_;
1202 void setDelegate(id delegate) {
1203 delegate_ = delegate;
1206 NSObject<ProgressDelegate> *getDelegate() const {
1210 virtual bool MediaChange(std::string media, std::string drive) {
1214 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1217 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1218 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1219 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1222 virtual void Done(pkgAcquire::ItemDesc &item) {
1225 virtual void Fail(pkgAcquire::ItemDesc &item) {
1227 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1228 item.Owner->Status == pkgAcquire::Item::StatDone
1232 std::string &error(item.Owner->ErrorText);
1236 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1237 NSArray *fields([description componentsSeparatedByString:@" "]);
1238 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1240 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1241 withObject:[NSArray arrayWithObjects:
1242 [NSString stringWithUTF8String:error.c_str()],
1249 virtual bool Pulse(pkgAcquire *Owner) {
1250 bool value = pkgAcquireStatus::Pulse(Owner);
1253 double(CurrentBytes + CurrentItems) /
1254 double(TotalBytes + TotalItems)
1257 [delegate_ setProgressPercent:percent];
1258 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1261 virtual void Start() {
1262 [delegate_ startProgress];
1265 virtual void Stop() {
1269 /* Progress Delegation {{{ */
1274 _transient id<ProgressDelegate> delegate_;
1278 virtual void Update() {
1279 /*if (abs(Percent - percent_) > 2)
1280 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1284 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1285 [delegate_ setProgressPercent:(Percent / 100)];*/
1295 void setDelegate(id delegate) {
1296 delegate_ = delegate;
1299 id getDelegate() const {
1303 virtual void Done() {
1305 //[delegate_ setProgressPercent:1];
1310 /* Database Interface {{{ */
1311 typedef std::map< unsigned long, _H<Source> > SourceMap;
1313 @interface Database : NSObject {
1319 pkgCacheFile cache_;
1320 pkgDepCache::Policy *policy_;
1321 pkgRecords *records_;
1322 pkgProblemResolver *resolver_;
1323 pkgAcquire *fetcher_;
1325 SPtr<pkgPackageManager> manager_;
1326 pkgSourceList *list_;
1329 CFMutableArrayRef packages_;
1331 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1340 + (Database *) sharedInstance;
1343 - (void) _readCydia:(NSNumber *)fd;
1344 - (void) _readStatus:(NSNumber *)fd;
1345 - (void) _readOutput:(NSNumber *)fd;
1349 - (Package *) packageWithName:(NSString *)name;
1351 - (pkgCacheFile &) cache;
1352 - (pkgDepCache::Policy *) policy;
1353 - (pkgRecords *) records;
1354 - (pkgProblemResolver *) resolver;
1355 - (pkgAcquire &) fetcher;
1356 - (pkgSourceList &) list;
1357 - (NSArray *) packages;
1358 - (NSArray *) sources;
1359 - (void) reloadData;
1367 - (void) updateWithStatus:(Status &)status;
1369 - (void) setDelegate:(id)delegate;
1370 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1373 /* Delegate Helpers {{{ */
1374 @implementation NSObject (ProgressDelegate)
1376 - (void) _setProgressErrorPackage:(NSArray *)args {
1377 [self performSelector:@selector(setProgressError:forPackage:)
1378 withObject:[args objectAtIndex:0]
1379 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1383 - (void) _setProgressErrorTitle:(NSArray *)args {
1384 [self performSelector:@selector(setProgressError:withTitle:)
1385 withObject:[args objectAtIndex:0]
1386 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1390 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1391 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1392 withObject:[NSArray arrayWithObjects:error, title, nil]
1397 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1398 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1400 [self performSelector:@selector(setProgressError:withTitle:)
1402 withObject:(package == nil ? id : [package name])
1409 /* Source Class {{{ */
1410 @interface Source : NSObject {
1411 CYString depiction_;
1412 CYString description_;
1418 CYString distribution_;
1423 NSString *authority_;
1425 CYString defaultIcon_;
1427 NSDictionary *record_;
1431 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1433 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1435 - (NSString *) depictionForPackage:(NSString *)package;
1436 - (NSString *) supportForPackage:(NSString *)package;
1438 - (NSDictionary *) record;
1442 - (NSString *) distribution;
1443 - (NSString *) type;
1445 - (NSString *) host;
1447 - (NSString *) name;
1448 - (NSString *) description;
1449 - (NSString *) label;
1450 - (NSString *) origin;
1451 - (NSString *) version;
1453 - (NSString *) defaultIcon;
1457 @implementation Source
1461 distribution_.clear();
1464 description_.clear();
1470 defaultIcon_.clear();
1472 if (record_ != nil) {
1482 if (authority_ != nil) {
1483 [authority_ release];
1489 // XXX: this is a very inefficient way to call these deconstructors
1494 + (NSArray *) _attributeKeys {
1495 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1498 - (NSArray *) attributeKeys {
1499 return [[self class] _attributeKeys];
1502 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1503 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1506 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1509 trusted_ = index->IsTrusted();
1511 uri_.set(pool, index->GetURI());
1512 distribution_.set(pool, index->GetDist());
1513 type_.set(pool, index->GetType());
1515 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1516 if (dindex != NULL) {
1518 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1521 pkgTagFile tags(&fd);
1523 pkgTagSection section;
1530 {"default-icon", &defaultIcon_},
1531 {"depiction", &depiction_},
1532 {"description", &description_},
1534 {"origin", &origin_},
1535 {"support", &support_},
1536 {"version", &version_},
1539 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1540 const char *start, *end;
1542 if (section.Find(names[i].name_, start, end)) {
1543 CYString &value(*names[i].value_);
1544 value.set(pool, start, end - start);
1550 record_ = [Sources_ objectForKey:[self key]];
1552 record_ = [record_ retain];
1554 NSURL *url([NSURL URLWithString:uri_]);
1558 host_ = [[host_ lowercaseString] retain];
1563 authority_ = [url path];
1565 if (authority_ != nil)
1566 authority_ = [authority_ retain];
1569 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1570 if ((self = [super init]) != nil) {
1571 [self setMetaIndex:index inPool:pool];
1575 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1576 NSDictionary *lhr = [self record];
1577 NSDictionary *rhr = [source record];
1580 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1582 NSString *lhs = [self name];
1583 NSString *rhs = [source name];
1585 if ([lhs length] != 0 && [rhs length] != 0) {
1586 unichar lhc = [lhs characterAtIndex:0];
1587 unichar rhc = [rhs characterAtIndex:0];
1589 if (isalpha(lhc) && !isalpha(rhc))
1590 return NSOrderedAscending;
1591 else if (!isalpha(lhc) && isalpha(rhc))
1592 return NSOrderedDescending;
1595 return [lhs compare:rhs options:LaxCompareOptions_];
1598 - (NSString *) depictionForPackage:(NSString *)package {
1599 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1602 - (NSString *) supportForPackage:(NSString *)package {
1603 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1606 - (NSDictionary *) record {
1614 - (NSString *) uri {
1618 - (NSString *) distribution {
1619 return distribution_;
1622 - (NSString *) type {
1626 - (NSString *) key {
1627 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1630 - (NSString *) host {
1634 - (NSString *) name {
1635 return origin_.empty() ? authority_ : origin_;
1638 - (NSString *) description {
1639 return description_;
1642 - (NSString *) label {
1643 return label_.empty() ? authority_ : label_;
1646 - (NSString *) origin {
1650 - (NSString *) version {
1654 - (NSString *) defaultIcon {
1655 return defaultIcon_;
1660 /* Relationship Class {{{ */
1661 @interface Relationship : NSObject {
1666 - (NSString *) type;
1668 - (NSString *) name;
1672 @implementation Relationship
1680 - (NSString *) type {
1688 - (NSString *) name {
1695 /* Package Class {{{ */
1696 @interface Package : NSObject {
1700 pkgCache::VerIterator version_;
1701 pkgCache::PkgIterator iterator_;
1702 _transient Database *database_;
1703 pkgCache::VerFileIterator file_;
1709 _transient NSString *section$_;
1714 CYString installed_;
1720 CYString depiction_;
1731 NSMutableArray *tags_;
1734 NSMutableDictionary *metadata_;
1735 _transient NSDate *firstSeen_;
1736 _transient NSDate *lastSeen_;
1741 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1742 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1744 - (pkgCache::PkgIterator) iterator;
1747 - (NSString *) section;
1748 - (NSString *) simpleSection;
1750 - (NSString *) longSection;
1751 - (NSString *) shortSection;
1755 - (Address *) maintainer;
1757 - (NSString *) longDescription;
1758 - (NSString *) shortDescription;
1761 - (NSMutableDictionary *) metadata;
1763 - (BOOL) subscribed;
1766 - (NSString *) latest;
1767 - (NSString *) installed;
1768 - (BOOL) uninstalled;
1771 - (BOOL) upgradableAndEssential:(BOOL)essential;
1774 - (BOOL) unfiltered;
1778 - (BOOL) halfConfigured;
1779 - (BOOL) halfInstalled;
1781 - (NSString *) mode;
1784 - (NSString *) name;
1786 - (NSString *) homepage;
1787 - (NSString *) depiction;
1788 - (Address *) author;
1790 - (NSString *) support;
1792 - (NSArray *) files;
1793 - (NSArray *) warnings;
1794 - (NSArray *) applications;
1796 - (Source *) source;
1797 - (NSString *) role;
1799 - (BOOL) matches:(NSString *)text;
1801 - (bool) hasSupportingRole;
1802 - (BOOL) hasTag:(NSString *)tag;
1803 - (NSString *) primaryPurpose;
1804 - (NSArray *) purposes;
1805 - (bool) isCommercial;
1807 - (CYString &) cyname;
1809 - (uint32_t) compareBySection:(NSArray *)sections;
1811 - (uint32_t) compareForChanges;
1816 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1817 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1818 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1819 - (bool) isVisibleInSection:(NSString *)section;
1820 - (bool) isVisibleInSource:(Source *)source;
1824 uint32_t PackageChangesRadix(Package *self, void *) {
1829 uint32_t timestamp : 30;
1830 uint32_t ignored : 1;
1831 uint32_t upgradable : 1;
1835 bool upgradable([self upgradableAndEssential:YES]);
1836 value.bits.upgradable = upgradable ? 1 : 0;
1839 value.bits.timestamp = 0;
1840 value.bits.ignored = [self ignored] ? 0 : 1;
1841 value.bits.upgradable = 1;
1843 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1844 value.bits.ignored = 0;
1845 value.bits.upgradable = 0;
1848 return _not(uint32_t) - value.key;
1851 _finline static void Stifle(uint8_t &value) {
1854 uint32_t PackagePrefixRadix(Package *self, void *context) {
1855 size_t offset(reinterpret_cast<size_t>(context));
1856 CYString &name([self cyname]);
1858 size_t size(name.size());
1861 char *text(name.data());
1864 if (!isdigit(text[0]))
1868 while (size != digits && isdigit(text[digits]))
1878 if (offset == 0 && zeros != 0) {
1879 memset(data, '0', zeros);
1880 memcpy(data + zeros, text, 4 - zeros);
1882 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1883 if (size <= offset - zeros)
1886 text += offset - zeros;
1887 size -= offset - zeros;
1890 memcpy(data, text, 4);
1892 memcpy(data, text, size);
1893 memset(data + size, 0, 4 - size);
1896 for (size_t i(0); i != 4; ++i)
1897 if (isalpha(data[i]))
1905 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1907 /* XXX: ntohl may be more honest */
1908 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1911 CYString &(*PackageName)(Package *self, SEL sel);
1913 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1914 _profile(PackageNameCompare)
1915 CYString &lhi(PackageName(lhs, @selector(cyname)));
1916 CYString &rhi(PackageName(rhs, @selector(cyname)));
1917 CFStringRef lhn(lhi), rhn(rhi);
1920 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1921 else if (rhn == NULL)
1922 return NSOrderedDescending;
1924 _profile(PackageNameCompare$NumbersLast)
1925 if (!lhi.empty() && !rhi.empty()) {
1926 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1927 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1928 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1929 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1930 return lha ? NSOrderedAscending : NSOrderedDescending;
1934 CFIndex length = CFStringGetLength(lhn);
1936 _profile(PackageNameCompare$Compare)
1937 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1942 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1943 return PackageNameCompare(*lhs, *rhs, context);
1946 struct PackageNameOrdering :
1947 std::binary_function<Package *, Package *, bool>
1949 _finline bool operator ()(Package *lhs, Package *rhs) const {
1950 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1954 @implementation Package
1956 - (NSString *) description {
1957 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1967 if (sponsor$_ != nil)
1968 [sponsor$_ release];
1969 if (author$_ != nil)
1976 if (metadata_ != nil)
1977 [metadata_ release];
1982 + (NSString *) webScriptNameForSelector:(SEL)selector {
1983 if (selector == @selector(hasTag:))
1989 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1990 return [self webScriptNameForSelector:selector] == nil;
1993 + (NSArray *) _attributeKeys {
1994 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];
1997 - (NSArray *) attributeKeys {
1998 return [[self class] _attributeKeys];
2001 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2002 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2012 _profile(Package$parse)
2013 pkgRecords::Parser *parser;
2015 _profile(Package$parse$Lookup)
2016 parser = &[database_ records]->Lookup(file_);
2021 _profile(Package$parse$Find)
2027 {"depiction", &depiction_},
2028 {"homepage", &homepage_},
2029 {"website", &website},
2031 {"support", &support_},
2032 {"sponsor", &sponsor_},
2033 {"author", &author_},
2036 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2037 const char *start, *end;
2039 if (parser->Find(names[i].name_, start, end)) {
2040 CYString &value(*names[i].value_);
2041 _profile(Package$parse$Value)
2042 value.set(pool_, start, end - start);
2048 _profile(Package$parse$Tagline)
2049 const char *start, *end;
2050 if (parser->ShortDesc(start, end)) {
2051 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2054 while (stop != start && stop[-1] == '\r')
2056 tagline_.set(pool_, start, stop - start);
2060 _profile(Package$parse$Retain)
2061 if (homepage_.empty())
2062 homepage_ = website;
2063 if (homepage_ == depiction_)
2069 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2070 if ((self = [super init]) != nil) {
2071 _profile(Package$initWithVersion)
2072 era_ = [database era];
2077 _profile(Package$initWithVersion$ParentPkg)
2078 iterator_ = version.ParentPkg();
2081 database_ = database;
2083 _profile(Package$initWithVersion$Latest)
2084 const char *latest(StripVersion_(version_.VerStr()));
2085 latest_ = (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(latest), strlen(latest), kCFStringEncodingASCII, NO);
2088 pkgCache::VerIterator current;
2089 _profile(Package$initWithVersion$Versions)
2090 current = iterator_.CurrentVer();
2092 installed_.set(pool_, StripVersion_(current.VerStr()));
2094 if (!version_.end())
2095 file_ = version_.FileList();
2097 pkgCache &cache([database_ cache]);
2098 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2102 _profile(Package$initWithVersion$Name)
2103 id_.set(pool_, iterator_.Name());
2104 name_.set(pool, iterator_.Display());
2107 _profile(Package$initWithVersion$lowercaseString)
2108 char *data(id_.data());
2109 for (size_t i(0), e(id_.size()); i != e; ++i)
2110 // XXX: do not use tolower() as this is not locale-specific? :(
2114 _profile(Package$initWithVersion$Tags)
2115 pkgCache::TagIterator tag(iterator_.TagList());
2117 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2119 const char *name(tag.Name());
2120 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2121 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2122 role_ = (NSString *) CYStringCreate(name + 6);
2124 } while (!tag.end());
2128 bool changed(false);
2130 _profile(Package$initWithVersion$Metadata)
2131 metadata_ = [Packages_ objectForKey:id_];
2133 if (metadata_ == nil) {
2136 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2137 firstSeen_, @"FirstSeen",
2138 latest_, @"LastVersion",
2143 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2144 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2146 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2147 subscribed_ = [subscribed boolValue];
2149 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2151 if (firstSeen_ == nil) {
2152 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2153 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2157 if (version == nil) {
2158 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2160 } else if (![version isEqualToString:latest_]) {
2161 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2163 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2168 metadata_ = [metadata_ retain];
2171 [Packages_ setObject:metadata_ forKey:id_];
2176 _profile(Package$initWithVersion$Section)
2177 section_.set(pool_, iterator_.Section());
2180 _profile(Package$initWithVersion$hasTag)
2181 obsolete_ = [self hasTag:@"cydia::obsolete"];
2182 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2185 ignored_ = iterator_->SelectedState == pkgCache::State::Hold;
2189 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2190 pkgCache::VerIterator version;
2192 _profile(Package$packageWithIterator$GetCandidateVer)
2193 version = [database policy]->GetCandidateVer(iterator);
2199 return [[[Package alloc]
2200 initWithVersion:version
2207 - (pkgCache::PkgIterator) iterator {
2211 - (NSString *) section {
2212 if (section$_ == nil) {
2213 if (section_.empty())
2216 _profile(Package$section)
2217 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2218 NSString *name(section_);
2219 section$_ = [SectionMap_ objectForKey:name] ?: name;
2224 - (NSString *) simpleSection {
2225 if (NSString *section = [self section])
2226 return Simplify(section);
2231 - (NSString *) longSection {
2232 return LocalizeSection([self section]);
2235 - (NSString *) shortSection {
2236 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2239 - (NSString *) uri {
2242 pkgIndexFile *index;
2243 pkgCache::PkgFileIterator file(file_.File());
2244 if (![database_ list].FindIndex(file, index))
2246 return [NSString stringWithUTF8String:iterator_->Path];
2247 //return [NSString stringWithUTF8String:file.Site()];
2248 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2252 - (Address *) maintainer {
2255 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2256 const std::string &maintainer(parser->Maintainer());
2257 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2261 return version_.end() ? 0 : version_->InstalledSize;
2264 - (NSString *) longDescription {
2265 @synchronized (database_) {
2266 if ([database_ era] != era_ || file_.end())
2269 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2270 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2272 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2273 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2274 if ([lines count] < 2)
2277 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2278 for (size_t i(1), e([lines count]); i != e; ++i) {
2279 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2280 [trimmed addObject:trim];
2283 return [trimmed componentsJoinedByString:@"\n"];
2286 - (NSString *) shortDescription {
2291 _profile(Package$index)
2292 CFStringRef name((CFStringRef) [self name]);
2293 if (CFStringGetLength(name) == 0)
2295 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2296 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2298 return toupper(character);
2302 - (NSMutableDictionary *) metadata {
2307 if (subscribed_ && lastSeen_ != nil)
2312 - (BOOL) subscribed {
2320 - (NSString *) latest {
2324 - (NSString *) installed {
2328 - (BOOL) uninstalled {
2329 return installed_.empty();
2333 return !version_.end();
2336 - (BOOL) upgradableAndEssential:(BOOL)essential {
2337 _profile(Package$upgradableAndEssential)
2338 pkgCache::VerIterator current(iterator_.CurrentVer());
2340 return essential && essential_;
2342 return !version_.end() && version_ != current;
2346 - (BOOL) essential {
2351 return [database_ cache][iterator_].InstBroken();
2354 - (BOOL) unfiltered {
2355 _profile(Package$unfiltered$obsolete)
2360 _profile(Package$unfiltered$hasSupportingRole)
2361 if (![self hasSupportingRole])
2369 if (![self unfiltered])
2372 NSString *section([self section]);
2374 _profile(Package$visible$isSectionVisible)
2375 if (section != nil && !isSectionVisible(section))
2383 unsigned char current(iterator_->CurrentState);
2384 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2387 - (BOOL) halfConfigured {
2388 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2391 - (BOOL) halfInstalled {
2392 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2396 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2397 return state.Mode != pkgDepCache::ModeKeep;
2400 - (NSString *) mode {
2401 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2403 switch (state.Mode) {
2404 case pkgDepCache::ModeDelete:
2405 if ((state.iFlags & pkgDepCache::Purge) != 0)
2409 case pkgDepCache::ModeKeep:
2410 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2411 return @"REINSTALL";
2412 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2416 case pkgDepCache::ModeInstall:
2417 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2418 return @"REINSTALL";
2419 else*/ switch (state.Status) {
2421 return @"DOWNGRADE";
2427 return @"NEW_INSTALL";
2438 - (NSString *) name {
2439 return name_.empty() ? id_ : name_;
2442 - (UIImage *) icon {
2443 NSString *section = [self simpleSection];
2447 if ([static_cast<id>(icon_) hasPrefix:@"file:///"])
2448 // XXX: correct escaping
2449 icon = [UIImage imageAtPath:[static_cast<id>(icon_) substringFromIndex:7]];
2450 if (icon == nil) if (section != nil)
2451 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2452 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2453 if ([dicon hasPrefix:@"file:///"])
2454 // XXX: correct escaping
2455 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2457 icon = [UIImage applicationImageNamed:@"unknown.png"];
2461 - (NSString *) homepage {
2465 - (NSString *) depiction {
2466 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2469 - (Address *) sponsor {
2470 if (sponsor$_ == nil) {
2471 if (sponsor_.empty())
2473 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2477 - (Address *) author {
2478 if (author$_ == nil) {
2479 if (author_.empty())
2481 author$_ = [[Address addressWithString:author_] retain];
2485 - (NSString *) support {
2486 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2489 - (NSArray *) files {
2490 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2491 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2494 fin.open([path UTF8String]);
2499 while (std::getline(fin, line))
2500 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2505 - (NSArray *) warnings {
2506 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2507 const char *name(iterator_.Name());
2509 size_t length(strlen(name));
2510 if (length < 2) invalid:
2511 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2512 else for (size_t i(0); i != length; ++i)
2514 /* XXX: technically this is not allowed */
2515 (name[i] < 'A' || name[i] > 'Z') &&
2516 (name[i] < 'a' || name[i] > 'z') &&
2517 (name[i] < '0' || name[i] > '9') &&
2518 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2521 if (strcmp(name, "cydia") != 0) {
2524 bool _private = false;
2527 bool repository = [[self section] isEqualToString:@"Repositories"];
2529 if (NSArray *files = [self files])
2530 for (NSString *file in files)
2531 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2533 else if (!user && [file isEqualToString:@"/User"])
2535 else if (!_private && [file isEqualToString:@"/private"])
2537 else if (!stash && [file isEqualToString:@"/var/stash"])
2540 /* XXX: this is not sensitive enough. only some folders are valid. */
2541 if (cydia && !repository)
2542 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2544 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2546 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2548 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2551 return [warnings count] == 0 ? nil : warnings;
2554 - (NSArray *) applications {
2555 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2557 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2559 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2560 if (NSArray *files = [self files])
2561 for (NSString *file in files)
2562 if (application_r(file)) {
2563 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2564 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2565 if ([id isEqualToString:me])
2568 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2570 display = application_r[1];
2572 NSString *bundle([file stringByDeletingLastPathComponent]);
2573 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2574 if (icon == nil || [icon length] == 0)
2576 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2578 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2579 [applications addObject:application];
2581 [application addObject:id];
2582 [application addObject:display];
2583 [application addObject:url];
2586 return [applications count] == 0 ? nil : applications;
2589 - (Source *) source {
2590 if (source_ == nil) {
2591 @synchronized (database_) {
2592 if ([database_ era] != era_ || file_.end())
2593 source_ = (Source *) [NSNull null];
2595 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2599 return source_ == (Source *) [NSNull null] ? nil : source_;
2602 - (NSString *) role {
2606 - (BOOL) matches:(NSString *)text {
2612 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2613 if (range.location != NSNotFound)
2616 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2617 if (range.location != NSNotFound)
2620 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2621 if (range.location != NSNotFound)
2627 - (bool) hasSupportingRole {
2630 if ([role_ isEqualToString:@"enduser"])
2632 if ([Role_ isEqualToString:@"User"])
2634 if ([role_ isEqualToString:@"hacker"])
2636 if ([Role_ isEqualToString:@"Hacker"])
2638 if ([role_ isEqualToString:@"developer"])
2640 if ([Role_ isEqualToString:@"Developer"])
2645 - (BOOL) hasTag:(NSString *)tag {
2646 return tags_ == nil ? NO : [tags_ containsObject:tag];
2649 - (NSString *) primaryPurpose {
2650 for (NSString *tag in tags_)
2651 if ([tag hasPrefix:@"purpose::"])
2652 return [tag substringFromIndex:9];
2656 - (NSArray *) purposes {
2657 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2658 for (NSString *tag in tags_)
2659 if ([tag hasPrefix:@"purpose::"])
2660 [purposes addObject:[tag substringFromIndex:9]];
2661 return [purposes count] == 0 ? nil : purposes;
2664 - (bool) isCommercial {
2665 return [self hasTag:@"cydia::commercial"];
2668 - (CYString &) cyname {
2669 return name_.empty() ? id_ : name_;
2672 - (uint32_t) compareBySection:(NSArray *)sections {
2673 NSString *section([self section]);
2674 for (size_t i(0), e([sections count]); i != e; ++i) {
2675 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2679 return _not(uint32_t);
2682 - (uint32_t) compareForChanges {
2687 uint32_t timestamp : 30;
2688 uint32_t ignored : 1;
2689 uint32_t upgradable : 1;
2693 bool upgradable([self upgradableAndEssential:YES]);
2694 value.bits.upgradable = upgradable ? 1 : 0;
2697 value.bits.timestamp = 0;
2698 value.bits.ignored = [self ignored] ? 0 : 1;
2699 value.bits.upgradable = 1;
2701 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2702 value.bits.ignored = 0;
2703 value.bits.upgradable = 0;
2706 return _not(uint32_t) - value.key;
2710 @synchronized (database_) {
2711 pkgProblemResolver *resolver = [database_ resolver];
2712 resolver->Clear(iterator_);
2714 pkgCacheFile &cache([database_ cache]);
2715 cache->SetReInstall(iterator_, false);
2716 cache->MarkKeep(iterator_, false);
2720 @synchronized (database_) {
2721 pkgProblemResolver *resolver = [database_ resolver];
2722 resolver->Clear(iterator_);
2723 resolver->Protect(iterator_);
2725 pkgCacheFile &cache([database_ cache]);
2726 cache->SetReInstall(iterator_, false);
2727 cache->MarkInstall(iterator_, false);
2729 pkgDepCache::StateCache &state((*cache)[iterator_]);
2730 if (!state.Install())
2731 cache->SetReInstall(iterator_, true);
2735 @synchronized (database_) {
2736 pkgProblemResolver *resolver = [database_ resolver];
2737 resolver->Clear(iterator_);
2738 resolver->Remove(iterator_);
2739 resolver->Protect(iterator_);
2741 pkgCacheFile &cache([database_ cache]);
2742 cache->SetReInstall(iterator_, false);
2743 cache->MarkDelete(iterator_, true);
2746 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2747 _profile(Package$isUnfilteredAndSearchedForBy)
2750 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2751 value &= [self unfiltered];
2754 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2755 value &= [self matches:search];
2762 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2763 if ([search length] == 0)
2766 _profile(Package$isUnfilteredAndSelectedForBy)
2769 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2770 value &= [self unfiltered];
2773 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2774 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2781 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2782 return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]);
2785 - (bool) isVisibleInSection:(NSString *)name {
2786 NSString *section([self section]);
2790 section == nil && [name length] == 0 ||
2791 [name isEqualToString:section]
2792 ) && [self visible];
2795 - (bool) isVisibleInSource:(Source *)source {
2796 return [self source] == source && [self visible];
2801 /* Section Class {{{ */
2802 @interface Section : NSObject {
2807 NSString *localized_;
2810 - (NSComparisonResult) compareByLocalized:(Section *)section;
2811 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2812 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2813 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2814 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2815 - (NSString *) name;
2822 - (void) addToCount;
2824 - (void) setCount:(size_t)count;
2825 - (NSString *) localized;
2829 @implementation Section
2833 if (localized_ != nil)
2834 [localized_ release];
2838 - (NSComparisonResult) compareByLocalized:(Section *)section {
2839 NSString *lhs(localized_);
2840 NSString *rhs([section localized]);
2842 /*if ([lhs length] != 0 && [rhs length] != 0) {
2843 unichar lhc = [lhs characterAtIndex:0];
2844 unichar rhc = [rhs characterAtIndex:0];
2846 if (isalpha(lhc) && !isalpha(rhc))
2847 return NSOrderedAscending;
2848 else if (!isalpha(lhc) && isalpha(rhc))
2849 return NSOrderedDescending;
2852 return [lhs compare:rhs options:LaxCompareOptions_];
2855 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2856 if ((self = [self initWithName:name localize:NO]) != nil) {
2857 if (localized != nil)
2858 localized_ = [localized retain];
2862 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2863 return [self initWithName:name row:0 localize:localize];
2866 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2867 if ((self = [super init]) != nil) {
2868 name_ = [name retain];
2872 localized_ = [LocalizeSection(name_) retain];
2876 /* XXX: localize the index thingees */
2877 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2878 if ((self = [super init]) != nil) {
2879 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2885 - (NSString *) name {
2905 - (void) addToCount {
2909 - (void) setCount:(size_t)count {
2913 - (NSString *) localized {
2920 static NSString *Colon_;
2921 static NSString *Elision_;
2922 static NSString *Error_;
2923 static NSString *Warning_;
2925 /* Database Implementation {{{ */
2926 @implementation Database
2928 + (Database *) sharedInstance {
2929 static Database *instance;
2930 if (instance == nil)
2931 instance = [[Database alloc] init];
2940 // XXX: actually implement this thing
2942 NSRecycleZone(zone_);
2943 // XXX: malloc_destroy_zone(zone_);
2944 apr_pool_destroy(pool_);
2948 - (void) _readCydia:(NSNumber *)fd { _pooled
2949 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2950 std::istream is(&ib);
2953 static Pcre finish_r("^finish:([^:]*)$");
2955 while (std::getline(is, line)) {
2956 const char *data(line.c_str());
2957 size_t size = line.size();
2958 lprintf("C:%s\n", data);
2960 if (finish_r(data, size)) {
2961 NSString *finish = finish_r[1];
2962 int index = [Finishes_ indexOfObject:finish];
2963 if (index != INT_MAX && index > Finish_)
2971 - (void) _readStatus:(NSNumber *)fd { _pooled
2972 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2973 std::istream is(&ib);
2976 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2977 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2979 while (std::getline(is, line)) {
2980 const char *data(line.c_str());
2981 size_t size(line.size());
2982 lprintf("S:%s\n", data);
2984 if (conffile_r(data, size)) {
2985 [delegate_ setConfigurationData:conffile_r[1]];
2986 } else if (strncmp(data, "status: ", 8) == 0) {
2987 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2988 [delegate_ setProgressTitle:string];
2989 } else if (pmstatus_r(data, size)) {
2990 std::string type([pmstatus_r[1] UTF8String]);
2991 NSString *id = pmstatus_r[2];
2993 float percent([pmstatus_r[3] floatValue]);
2994 [delegate_ setProgressPercent:(percent / 100)];
2996 NSString *string = pmstatus_r[4];
2998 if (type == "pmerror")
2999 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3000 withObject:[NSArray arrayWithObjects:string, id, nil]
3003 else if (type == "pmstatus") {
3004 [delegate_ setProgressTitle:string];
3005 } else if (type == "pmconffile")
3006 [delegate_ setConfigurationData:string];
3008 lprintf("E:unknown pmstatus\n");
3010 lprintf("E:unknown status\n");
3016 - (void) _readOutput:(NSNumber *)fd { _pooled
3017 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3018 std::istream is(&ib);
3021 while (std::getline(is, line)) {
3022 lprintf("O:%s\n", line.c_str());
3023 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3033 - (Package *) packageWithName:(NSString *)name {
3034 @synchronized (self) {
3035 if (static_cast<pkgDepCache *>(cache_) == NULL)
3037 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3038 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3042 if ((self = [super init]) != nil) {
3049 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3050 apr_pool_create(&pool_, NULL);
3052 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
3056 _assert(pipe(fds) != -1);
3059 _config->Set("APT::Keep-Fds::", cydiafd_);
3060 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3063 detachNewThreadSelector:@selector(_readCydia:)
3065 withObject:[NSNumber numberWithInt:fds[0]]
3068 _assert(pipe(fds) != -1);
3072 detachNewThreadSelector:@selector(_readStatus:)
3074 withObject:[NSNumber numberWithInt:fds[0]]
3077 _assert(pipe(fds) != -1);
3078 _assert(dup2(fds[0], 0) != -1);
3079 _assert(close(fds[0]) != -1);
3081 input_ = fdopen(fds[1], "a");
3083 _assert(pipe(fds) != -1);
3084 _assert(dup2(fds[1], 1) != -1);
3085 _assert(close(fds[1]) != -1);
3088 detachNewThreadSelector:@selector(_readOutput:)
3090 withObject:[NSNumber numberWithInt:fds[0]]
3095 - (pkgCacheFile &) cache {
3099 - (pkgDepCache::Policy *) policy {
3103 - (pkgRecords *) records {
3107 - (pkgProblemResolver *) resolver {
3111 - (pkgAcquire &) fetcher {
3115 - (pkgSourceList &) list {
3119 - (NSArray *) packages {
3120 return (NSArray *) packages_;
3123 - (NSArray *) sources {
3124 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3125 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3126 [sources addObject:i->second];
3130 - (NSArray *) issues {
3131 if (cache_->BrokenCount() == 0)
3134 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3136 for (Package *package in [self packages]) {
3137 if (![package broken])
3139 pkgCache::PkgIterator pkg([package iterator]);
3141 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3142 [entry addObject:[package name]];
3143 [issues addObject:entry];
3145 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3149 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3150 pkgCache::DepIterator start;
3151 pkgCache::DepIterator end;
3152 dep.GlobOr(start, end); // ++dep
3154 if (!cache_->IsImportantDep(end))
3156 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3159 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3160 [entry addObject:failure];
3161 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3163 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3164 if (Package *package = [self packageWithName:name])
3165 name = [package name];
3166 [failure addObject:name];
3168 pkgCache::PkgIterator target(start.TargetPkg());
3169 if (target->ProvidesList != 0)
3170 [failure addObject:@"?"];
3172 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3174 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3175 else if (!cache_[target].CandidateVerIter(cache_).end())
3176 [failure addObject:@"-"];
3177 else if (target->ProvidesList == 0)
3178 [failure addObject:@"!"];
3180 [failure addObject:@"%"];
3184 if (start.TargetVer() != 0)
3185 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3196 - (bool) popErrorWithTitle:(NSString *)title {
3198 std::string message;
3200 while (!_error->empty()) {
3202 bool warning(!_error->PopMessage(error));
3206 size_t size(error.size());
3207 if (size == 0 || error[size - 1] != '\n')
3209 error.resize(size - 1);
3211 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3213 if (!message.empty())
3218 if (fatal && !message.empty())
3219 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3224 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3225 return [self popErrorWithTitle:title] || !success;
3228 - (void) reloadData { CYPoolStart() {
3229 @synchronized (self) {
3232 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3233 CFArrayRemoveAllValues(packages_);
3260 apr_pool_clear(pool_);
3261 NSRecycleZone(zone_);
3263 int chk(creat("/tmp/cydia.chk", 0644));
3267 NSString *title(UCLocalize("DATABASE"));
3270 if (!cache_.Open(progress_, true)) { pop:
3272 bool warning(!_error->PopMessage(error));
3273 lprintf("cache_.Open():[%s]\n", error.c_str());
3275 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3276 [delegate_ repairWithSelector:@selector(configure)];
3277 else if (error == "The package lists or status file could not be parsed or opened.")
3278 [delegate_ repairWithSelector:@selector(update)];
3279 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3280 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3281 // else if (error == "The list of sources could not be read.")
3283 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3292 unlink("/tmp/cydia.chk");
3294 now_ = [[NSDate date] retain];
3296 policy_ = new pkgDepCache::Policy();
3297 records_ = new pkgRecords(cache_);
3298 resolver_ = new pkgProblemResolver(cache_);
3299 fetcher_ = new pkgAcquire(&status_);
3302 list_ = new pkgSourceList();
3303 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3306 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3307 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3311 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3314 if (cache_->BrokenCount() != 0) {
3315 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3318 if (cache_->BrokenCount() != 0) {
3319 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3323 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3327 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3328 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3329 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3330 // XXX: this could be more intelligent
3331 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3332 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3334 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3339 /*std::vector<Package *> packages;
3340 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3341 [packages_ release];
3346 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3347 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3348 //packages.push_back(package);
3349 CFArrayAppendValue(packages_, [package retain]);
3353 /*if (packages.empty())
3354 packages_ = [[NSArray alloc] init];
3356 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3359 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3360 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3361 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3369 /*if (!packages.empty())
3370 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3371 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3373 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3375 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3377 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3381 } } CYPoolEnd() _trace(); }
3384 @synchronized (self) {
3386 resolver_ = new pkgProblemResolver(cache_);
3388 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3389 if (!cache_[iterator].Keep()) {
3390 cache_->MarkKeep(iterator, false);
3391 cache_->SetReInstall(iterator, false);
3396 - (void) configure {
3397 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3398 system([dpkg UTF8String]);
3402 // XXX: I don't remember this condition
3407 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3409 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3411 if ([self popErrorWithTitle:title])
3415 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3418 public pkgArchiveCleaner
3421 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3426 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3433 fetcher_->Shutdown();
3435 pkgRecords records(cache_);
3437 lock_ = new FileFd();
3438 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3440 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3442 if ([self popErrorWithTitle:title])
3446 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3449 manager_ = (_system->CreatePM(cache_));
3450 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3457 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3459 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3461 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3463 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3464 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3467 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3472 bool failed = false;
3473 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3474 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3476 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3479 std::string uri = (*item)->DescURI();
3480 std::string error = (*item)->ErrorText;
3482 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3485 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3486 withObject:[NSArray arrayWithObjects:
3487 [NSString stringWithUTF8String:error.c_str()],
3499 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3501 if (_error->PendingError()) {
3506 if (result == pkgPackageManager::Failed) {
3511 if (result != pkgPackageManager::Completed) {
3516 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3518 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3520 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3521 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3524 if (![before isEqualToArray:after])
3529 NSString *title(UCLocalize("UPGRADE"));
3530 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3536 [self updateWithStatus:status_];
3539 - (void) updateWithStatus:(Status &)status {
3540 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3541 NSString *title(UCLocalize("REFRESHING_DATA"));
3544 if (!list.ReadMainList())
3545 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3548 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3549 if ([self popErrorWithTitle:title])
3552 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3553 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3554 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3556 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3560 - (void) setDelegate:(id)delegate {
3561 delegate_ = delegate;
3562 status_.setDelegate(delegate);
3563 progress_.setDelegate(delegate);
3566 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3567 SourceMap::const_iterator i(sources_.find(file->ID));
3568 return i == sources_.end() ? nil : i->second;
3574 /* Confirmation Controller {{{ */
3575 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3576 if (!iterator.end())
3577 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3578 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3580 pkgCache::PkgIterator package(dep.TargetPkg());
3583 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3591 /* Web Scripting {{{ */
3592 @interface CydiaObject : NSObject {
3594 _transient id delegate_;
3597 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3600 @implementation CydiaObject
3603 [indirect_ release];
3607 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3608 if ((self = [super init]) != nil) {
3609 indirect_ = [indirect retain];
3613 - (void) setDelegate:(id)delegate {
3614 delegate_ = delegate;
3617 + (NSArray *) _attributeKeys {
3618 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3621 - (NSArray *) attributeKeys {
3622 return [[self class] _attributeKeys];
3625 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3626 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3629 - (NSString *) device {
3630 return [[UIDevice currentDevice] uniqueIdentifier];
3633 #if 0 // XXX: implement!
3634 - (NSString *) mac {
3635 if (![indirect_ promptForSensitive:@"Mac Address"])
3639 - (NSString *) serial {
3640 if (![indirect_ promptForSensitive:@"Serial #"])
3644 - (NSString *) firewire {
3645 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3649 - (NSString *) imei {
3650 if (![indirect_ promptForSensitive:@"IMEI"])
3655 + (NSString *) webScriptNameForSelector:(SEL)selector {
3656 if (selector == @selector(close))
3658 else if (selector == @selector(getInstalledPackages))
3659 return @"getInstalledPackages";
3660 else if (selector == @selector(getPackageById:))
3661 return @"getPackageById";
3662 else if (selector == @selector(installPackages:))
3663 return @"installPackages";
3664 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3665 return @"setButtonImage";
3666 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3667 return @"setButtonTitle";
3668 else if (selector == @selector(setPopupHook:))
3669 return @"setPopupHook";
3670 else if (selector == @selector(setSpecial:))
3671 return @"setSpecial";
3672 else if (selector == @selector(setToken:))
3674 else if (selector == @selector(setViewportWidth:))
3675 return @"setViewportWidth";
3676 else if (selector == @selector(supports:))
3678 else if (selector == @selector(stringWithFormat:arguments:))
3680 else if (selector == @selector(localizedStringForKey:value:table:))
3682 else if (selector == @selector(du:))
3684 else if (selector == @selector(statfs:))
3690 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3691 return [self webScriptNameForSelector:selector] == nil;
3694 - (BOOL) supports:(NSString *)feature {
3695 return [feature isEqualToString:@"window.open"];
3698 - (NSArray *) getInstalledPackages {
3699 NSArray *packages([[Database sharedInstance] packages]);
3700 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3701 for (Package *package in packages)
3702 if ([package installed] != nil)
3703 [installed addObject:package];
3707 - (Package *) getPackageById:(NSString *)id {
3708 Package *package([[Database sharedInstance] packageWithName:id]);
3713 - (NSArray *) statfs:(NSString *)path {
3716 if (path == nil || statfs([path UTF8String], &stat) == -1)
3719 return [NSArray arrayWithObjects:
3720 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3721 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3722 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3726 - (NSNumber *) du:(NSString *)path {
3727 NSNumber *value(nil);
3730 _assert(pipe(fds) != -1);
3732 pid_t pid(ExecFork());
3734 _assert(dup2(fds[1], 1) != -1);
3735 _assert(close(fds[0]) != -1);
3736 _assert(close(fds[1]) != -1);
3737 /* XXX: this should probably not use du */
3738 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3743 _assert(close(fds[1]) != -1);
3745 if (FILE *du = fdopen(fds[0], "r")) {
3747 while (fgets(line, sizeof(line), du) != NULL) {
3748 size_t length(strlen(line));
3749 while (length != 0 && line[length - 1] == '\n')
3750 line[--length] = '\0';
3751 if (char *tab = strchr(line, '\t')) {
3753 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3758 } else _assert(close(fds[0]));
3762 if (waitpid(pid, &status, 0) == -1)
3765 else _assert(false);
3774 - (void) installPackages:(NSArray *)packages {
3775 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3778 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3779 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3782 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3783 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3786 - (void) setSpecial:(id)function {
3787 [indirect_ setSpecial:function];
3790 - (void) setToken:(NSString *)token {
3793 Token_ = [token retain];
3795 [Metadata_ setObject:Token_ forKey:@"Token"];
3799 - (void) setPopupHook:(id)function {
3800 [indirect_ setPopupHook:function];
3803 - (void) setViewportWidth:(float)width {
3804 [indirect_ setViewportWidth:width];
3807 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3808 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3809 unsigned count([arguments count]);
3811 for (unsigned i(0); i != count; ++i)
3812 values[i] = [arguments objectAtIndex:i];
3813 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3816 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3817 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3819 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3821 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3827 /* Cydia Browser Controller {{{ */
3828 @interface CYBrowserController : BrowserController {
3829 CydiaObject *cydia_;
3834 @implementation CYBrowserController
3841 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3844 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3845 [super webView:view didClearWindowObject:window forFrame:frame];
3847 WebDataSource *source([frame dataSource]);
3848 NSURLResponse *response([source response]);
3849 NSURL *url([response URL]);
3850 NSString *scheme([url scheme]);
3852 NSHTTPURLResponse *http;
3853 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3854 http = (NSHTTPURLResponse *) response;
3858 NSDictionary *headers([http allHeaderFields]);
3859 NSString *host([url host]);
3860 [self setHeaders:headers forHost:host];
3863 [host isEqualToString:@"cydia.saurik.com"] ||
3864 [host hasSuffix:@".cydia.saurik.com"] ||
3865 [scheme isEqualToString:@"file"]
3867 [window setValue:cydia_ forKey:@"cydia"];
3870 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3871 if (System_ != NULL)
3872 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3873 if (Machine_ != NULL)
3874 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3876 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3878 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3881 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3882 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3883 [self _setMoreHeaders:copy];
3887 - (void) setDelegate:(id)delegate {
3888 [super setDelegate:delegate];
3889 [cydia_ setDelegate:delegate];
3893 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3894 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3896 WebView *webview([[webview_ _documentView] webView]);
3898 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3900 NSString *application = package == nil ? @"Cydia" : [NSString
3901 stringWithFormat:@"Cydia/%@",
3906 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3908 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3909 if (Product_ != nil)
3910 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3912 [webview setApplicationNameForUserAgent:application];
3919 /* Confirmation {{{ */
3920 @protocol ConfirmationControllerDelegate
3921 - (void) cancelAndClear:(bool)clear;
3922 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3926 @interface ConfirmationController : CYBrowserController {
3927 _transient Database *database_;
3928 UIAlertView *essential_;
3935 - (id) initWithDatabase:(Database *)database;
3939 @implementation ConfirmationController
3946 if (essential_ != nil)
3947 [essential_ release];
3951 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3952 NSString *context([alert context]);
3954 if ([context isEqualToString:@"remove"]) {
3955 if (button == [alert cancelButtonIndex]) {
3956 [self dismissModalViewControllerAnimated:YES];
3957 } else if (button == [alert firstOtherButtonIndex]) {
3960 [delegate_ confirmWithNavigationController:[self navigationController]];
3963 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3964 } else if ([context isEqualToString:@"unable"]) {
3965 [self dismissModalViewControllerAnimated:YES];
3966 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3968 [super alertView:alert clickedButtonAtIndex:button];
3972 - (void) _doContinue {
3973 [self dismissModalViewControllerAnimated:YES];
3974 [delegate_ cancelAndClear:NO];
3977 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
3978 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
3982 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3983 [super webView:view didClearWindowObject:window forFrame:frame];
3984 [window setValue:changes_ forKey:@"changes"];
3985 [window setValue:issues_ forKey:@"issues"];
3986 [window setValue:sizes_ forKey:@"sizes"];
3987 [window setValue:self forKey:@"queue"];
3990 - (id) initWithDatabase:(Database *)database {
3991 if ((self = [super init]) != nil) {
3992 database_ = database;
3994 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
3996 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3997 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3998 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3999 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4000 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4004 pkgDepCache::Policy *policy([database_ policy]);
4006 pkgCacheFile &cache([database_ cache]);
4007 NSArray *packages = [database_ packages];
4008 for (Package *package in packages) {
4009 pkgCache::PkgIterator iterator = [package iterator];
4010 pkgDepCache::StateCache &state(cache[iterator]);
4012 NSString *name([package name]);
4014 if (state.NewInstall())
4015 [installing addObject:name];
4016 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4017 [reinstalling addObject:name];
4018 else if (state.Upgrade())
4019 [upgrading addObject:name];
4020 else if (state.Downgrade())
4021 [downgrading addObject:name];
4022 else if (state.Delete()) {
4023 if ([package essential])
4025 [removing addObject:name];
4028 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4029 substrate_ |= DepSubstrate(iterator.CurrentVer());
4034 else if (Advanced_) {
4035 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4037 essential_ = [[UIAlertView alloc]
4038 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4039 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4041 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4042 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4045 [essential_ setContext:@"remove"];
4047 essential_ = [[UIAlertView alloc]
4048 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4049 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4051 cancelButtonTitle:UCLocalize("OKAY")
4052 otherButtonTitles:nil
4055 [essential_ setContext:@"unable"];
4058 changes_ = [[NSArray alloc] initWithObjects:
4066 issues_ = [database_ issues];
4068 issues_ = [issues_ retain];
4070 sizes_ = [[NSArray alloc] initWithObjects:
4071 SizeString([database_ fetcher].FetchNeeded()),
4072 SizeString([database_ fetcher].PartialPresent()),
4075 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4077 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4078 initWithTitle:UCLocalize("CANCEL")
4079 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4080 style:UIBarButtonItemStylePlain
4082 action:@selector(cancelButtonClicked)
4087 - (void) applyRightButton {
4088 #if !AlwaysReload && !IgnoreInstall
4089 if (issues_ == nil && ![self isLoading])
4090 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4091 initWithTitle:UCLocalize("CONFIRM")
4092 style:UIBarButtonItemStylePlain
4094 action:@selector(confirmButtonClicked)
4097 [super applyRightButton];
4099 [[self navigationItem] setRightBarButtonItem:nil];
4103 - (void) cancelButtonClicked {
4104 [self dismissModalViewControllerAnimated:YES];
4105 [delegate_ cancelAndClear:YES];
4109 - (void) confirmButtonClicked {
4113 if (essential_ != nil)
4118 [delegate_ confirmWithNavigationController:[self navigationController]];
4126 /* Progress Data {{{ */
4127 @interface ProgressData : NSObject {
4129 // XXX: should these really both be _transient?
4130 _transient id target_;
4131 _transient id object_;
4134 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4141 @implementation ProgressData
4143 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4144 if ((self = [super init]) != nil) {
4145 selector_ = selector;
4165 /* Progress Controller {{{ */
4166 @interface ProgressController : CYViewController <
4167 ConfigurationDelegate,
4170 _transient Database *database_;
4171 UIProgressBar *progress_;
4172 UITextView *output_;
4173 UITextLabel *status_;
4174 UIPushButton *close_;
4176 SHA1SumValue springlist_;
4177 SHA1SumValue notifyconf_;
4181 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4183 - (void) _retachThread;
4184 - (void) _detachNewThreadData:(ProgressData *)data;
4185 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4191 @protocol ProgressControllerDelegate
4192 - (void) progressControllerIsComplete:(ProgressController *)sender;
4195 @implementation ProgressController
4198 [database_ setDelegate:nil];
4199 [progress_ release];
4208 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4209 if ((self = [super init]) != nil) {
4210 database_ = database;
4211 [database_ setDelegate:self];
4212 delegate_ = delegate;
4214 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4216 progress_ = [[UIProgressBar alloc] init];
4217 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4218 [progress_ setStyle:0];
4220 status_ = [[UITextLabel alloc] init];
4221 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4222 [status_ setColor:[UIColor whiteColor]];
4223 [status_ setBackgroundColor:[UIColor clearColor]];
4224 [status_ setCentersHorizontally:YES];
4225 //[status_ setFont:font];
4227 output_ = [[UITextView alloc] init];
4229 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4230 //[output_ setTextFont:@"Courier New"];
4231 [output_ setFont:[[output_ font] fontWithSize:12]];
4232 [output_ setTextColor:[UIColor whiteColor]];
4233 [output_ setBackgroundColor:[UIColor clearColor]];
4234 [output_ setMarginTop:0];
4235 [output_ setAllowsRubberBanding:YES];
4236 [output_ setEditable:NO];
4237 [[self view] addSubview:output_];
4239 close_ = [[UIPushButton alloc] init];
4240 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4241 [close_ setAutosizesToFit:NO];
4242 [close_ setDrawsShadow:YES];
4243 [close_ setStretchBackground:YES];
4244 [close_ setEnabled:YES];
4245 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4246 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4247 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4248 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4252 - (void) positionViews {
4253 CGRect bounds = [[self view] bounds];
4254 CGSize prgsize = [UIProgressBar defaultSize];
4257 (bounds.size.width - prgsize.width) / 2,
4258 bounds.size.height - prgsize.height - 20
4261 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4263 [progress_ setFrame:prgrect];
4264 [status_ setFrame:CGRectMake(
4266 bounds.size.height - prgsize.height - 50,
4267 bounds.size.width - 20,
4270 [output_ setFrame:CGRectMake(
4273 bounds.size.width - 20,
4274 bounds.size.height - 62
4276 [close_ setFrame:CGRectMake(
4277 (bounds.size.width - closewidth) / 2,
4278 bounds.size.height - prgsize.height - 50,
4284 - (void) viewWillAppear:(BOOL)animated {
4285 [super viewDidAppear:animated];
4286 [[self navigationItem] setHidesBackButton:YES];
4287 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4289 [self positionViews];
4292 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4293 [self positionViews];
4296 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4297 NSString *context([alert context]);
4299 if ([context isEqualToString:@"conffile"]) {
4300 FILE *input = [database_ input];
4301 if (button == [alert cancelButtonIndex])
4302 fprintf(input, "N\n");
4303 else if (button == [alert firstOtherButtonIndex])
4304 fprintf(input, "Y\n");
4309 - (void) closeButtonPushed {
4312 UpdateExternalStatus(0);
4316 [self dismissModalViewControllerAnimated:YES];
4320 [delegate_ terminateWithSuccess];
4321 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4322 [delegate_ suspendWithAnimation:YES];
4324 [delegate_ suspend];*/
4328 system("launchctl stop com.apple.SpringBoard");
4332 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4341 - (void) _retachThread {
4342 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4344 [[self view] addSubview:close_];
4345 [progress_ removeFromSuperview];
4346 [status_ removeFromSuperview];
4348 [database_ popErrorWithTitle:title_];
4349 [delegate_ progressControllerIsComplete:self];
4353 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4356 MMap mmap(file, MMap::ReadOnly);
4358 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4359 if (!(notifyconf_ == sha1.Result()))
4366 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4369 MMap mmap(file, MMap::ReadOnly);
4371 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4372 if (!(springlist_ == sha1.Result()))
4378 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4379 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4380 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4381 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4382 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4385 system("su -c /usr/bin/uicache mobile");
4387 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4389 [delegate_ setStatusBarShowsProgress:NO];
4392 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4393 [[data target] performSelector:[data selector] withObject:[data object]];
4394 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4397 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4398 UpdateExternalStatus(1);
4405 title_ = [title retain];
4407 [[self navigationItem] setTitle:title_];
4409 [status_ setText:nil];
4410 [output_ setText:@""];
4411 [progress_ setProgress:0];
4413 [close_ removeFromSuperview];
4414 [[self view] addSubview:progress_];
4415 [[self view] addSubview:status_];
4417 [delegate_ setStatusBarShowsProgress:YES];
4422 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4425 MMap mmap(file, MMap::ReadOnly);
4427 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4428 notifyconf_ = sha1.Result();
4434 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4437 MMap mmap(file, MMap::ReadOnly);
4439 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4440 springlist_ = sha1.Result();
4445 detachNewThreadSelector:@selector(_detachNewThreadData:)
4447 withObject:[[[ProgressData alloc]
4448 initWithSelector:selector
4455 - (void) repairWithSelector:(SEL)selector {
4457 detachNewThreadSelector:selector
4460 title:UCLocalize("REPAIRING")
4464 - (void) setConfigurationData:(NSString *)data {
4466 performSelectorOnMainThread:@selector(_setConfigurationData:)
4472 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4473 CYActionSheet *sheet([[[CYActionSheet alloc]
4475 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4476 defaultButtonIndex:0
4479 [sheet setMessage:error];
4480 [sheet yieldToPopupAlertAnimated:YES];
4484 - (void) setProgressTitle:(NSString *)title {
4486 performSelectorOnMainThread:@selector(_setProgressTitle:)
4492 - (void) setProgressPercent:(float)percent {
4494 performSelectorOnMainThread:@selector(_setProgressPercent:)
4495 withObject:[NSNumber numberWithFloat:percent]
4500 - (void) startProgress {
4503 - (void) addProgressOutput:(NSString *)output {
4505 performSelectorOnMainThread:@selector(_addProgressOutput:)
4511 - (bool) isCancelling:(size_t)received {
4515 - (void) _setConfigurationData:(NSString *)data {
4516 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4518 if (!conffile_r(data)) {
4519 lprintf("E:invalid conffile\n");
4523 NSString *ofile = conffile_r[1];
4524 //NSString *nfile = conffile_r[2];
4526 UIAlertView *alert = [[[UIAlertView alloc]
4527 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4528 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4530 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4531 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4532 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4536 [alert setContext:@"conffile"];
4540 - (void) _setProgressTitle:(NSString *)title {
4541 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4542 for (size_t i(0), e([words count]); i != e; ++i) {
4543 NSString *word([words objectAtIndex:i]);
4544 if (Package *package = [database_ packageWithName:word])
4545 [words replaceObjectAtIndex:i withObject:[package name]];
4548 [status_ setText:[words componentsJoinedByString:@" "]];
4551 - (void) _setProgressPercent:(NSNumber *)percent {
4552 [progress_ setProgress:[percent floatValue]];
4555 - (void) _addProgressOutput:(NSString *)output {
4556 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4557 CGSize size = [output_ contentSize];
4558 CGRect rect = {{0, size.height}, {size.width, 0}};
4559 [output_ scrollRectToVisible:rect animated:YES];
4562 - (BOOL) isRunning {
4569 /* Cell Content View {{{ */
4570 @protocol ContentDelegate
4571 - (void) drawContentRect:(CGRect)rect;
4574 @interface ContentView : UIView {
4575 _transient id<ContentDelegate> delegate_;
4580 @implementation ContentView
4582 - (id) initWithFrame:(CGRect)frame {
4583 if ((self = [super initWithFrame:frame]) != nil) {
4584 [self setNeedsDisplayOnBoundsChange:YES];
4588 - (void) setDelegate:(id<ContentDelegate>)delegate {
4589 delegate_ = delegate;
4592 - (void) drawRect:(CGRect)rect {
4593 [super drawRect:rect];
4594 [delegate_ drawContentRect:rect];
4599 /* Cydia TableView Cell {{{ */
4600 @interface CYTableViewCell : UITableViewCell {
4601 ContentView *content_;
4607 @implementation CYTableViewCell
4614 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4615 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4617 if (view == content_) {
4618 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4619 highlighted_ = highlighted;
4622 [super _updateHighlightColorsForView:view highlighted:highlighted];
4625 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4626 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4627 highlighted_ = selected;
4629 [super setSelected:selected animated:animated];
4630 [content_ setNeedsDisplay];
4635 /* Package Cell {{{ */
4636 @interface PackageCell : CYTableViewCell <
4641 NSString *description_;
4649 - (PackageCell *) init;
4650 - (void) setPackage:(Package *)package;
4652 + (int) heightForPackage:(Package *)package;
4653 - (void) drawContentRect:(CGRect)rect;
4657 @implementation PackageCell
4659 - (void) clearPackage {
4670 if (description_ != nil) {
4671 [description_ release];
4675 if (source_ != nil) {
4680 if (badge_ != nil) {
4685 if (placard_ != nil) {
4695 [self clearPackage];
4699 - (PackageCell *) init {
4700 CGRect frame(CGRectMake(0, 0, 320, 74));
4701 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4702 UIView *content([self contentView]);
4703 CGRect bounds([content bounds]);
4705 content_ = [[ContentView alloc] initWithFrame:bounds];
4706 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4707 [content addSubview:content_];
4709 [content_ setDelegate:self];
4710 [content_ setOpaque:YES];
4714 - (void) _setBackgroundColor {
4716 if (NSString *mode = [package_ mode]) {
4717 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4718 color = remove ? RemovingColor_ : InstallingColor_;
4720 color = [UIColor whiteColor];
4722 [content_ setBackgroundColor:color];
4723 [self setNeedsDisplay];
4726 - (void) setPackage:(Package *)package {
4727 [self clearPackage];
4730 Source *source = [package source];
4732 icon_ = [[package icon] retain];
4733 name_ = [[package name] retain];
4736 description_ = [package longDescription];
4737 if (description_ == nil)
4738 description_ = [package shortDescription];
4739 if (description_ != nil)
4740 description_ = [description_ retain];
4742 commercial_ = [package isCommercial];
4744 package_ = [package retain];
4746 NSString *label = nil;
4747 bool trusted = false;
4749 if (source != nil) {
4750 label = [source label];
4751 trusted = [source trusted];
4752 } else if ([[package id] isEqualToString:@"firmware"])
4753 label = UCLocalize("APPLE");
4755 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4757 NSString *from(label);
4759 NSString *section = [package simpleSection];
4760 if (section != nil && ![section isEqualToString:label]) {
4761 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4762 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4765 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4766 source_ = [from retain];
4768 if (NSString *purpose = [package primaryPurpose])
4769 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4770 badge_ = [badge_ retain];
4772 if ([package installed] != nil)
4773 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4774 placard_ = [placard_ retain];
4776 [self _setBackgroundColor];
4777 [content_ setNeedsDisplay];
4780 - (void) drawContentRect:(CGRect)rect {
4781 bool highlighted(highlighted_);
4782 float width([self bounds].size.width);
4785 CGContextRef context(UIGraphicsGetCurrentContext());
4786 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4787 CGContextFillRect(context, rect);
4792 rect.size = [icon_ size];
4794 rect.size.width /= 2;
4795 rect.size.height /= 2;
4797 rect.origin.x = 25 - rect.size.width / 2;
4798 rect.origin.y = 25 - rect.size.height / 2;
4800 [icon_ drawInRect:rect];
4803 if (badge_ != nil) {
4804 CGSize size = [badge_ size];
4806 [badge_ drawAtPoint:CGPointMake(
4807 36 - size.width / 2,
4808 36 - size.height / 2
4816 UISetColor(commercial_ ? Purple_ : Black_);
4817 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4818 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4821 UISetColor(commercial_ ? Purplish_ : Gray_);
4822 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4824 if (placard_ != nil)
4825 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4828 + (int) heightForPackage:(Package *)package {
4834 /* Section Cell {{{ */
4835 @interface SectionCell : CYTableViewCell <
4847 - (void) setSection:(Section *)section editing:(BOOL)editing;
4851 @implementation SectionCell
4853 - (void) clearSection {
4854 if (basic_ != nil) {
4859 if (section_ != nil) {
4869 if (count_ != nil) {
4876 [self clearSection];
4882 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4883 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4884 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4885 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4886 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4888 UIView *content([self contentView]);
4889 CGRect bounds([content bounds]);
4891 content_ = [[ContentView alloc] initWithFrame:bounds];
4892 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4893 [content addSubview:content_];
4894 [content_ setBackgroundColor:[UIColor whiteColor]];
4896 [content_ setDelegate:self];
4900 - (void) onSwitch:(id)sender {
4901 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4902 if (metadata == nil) {
4903 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4904 [Sections_ setObject:metadata forKey:basic_];
4908 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4911 - (void) setSection:(Section *)section editing:(BOOL)editing {
4912 if (editing != editing_) {
4914 [switch_ removeFromSuperview];
4916 [self addSubview:switch_];
4920 [self clearSection];
4922 if (section == nil) {
4923 name_ = [UCLocalize("ALL_PACKAGES") retain];
4926 basic_ = [section name];
4928 basic_ = [basic_ retain];
4930 section_ = [section localized];
4931 if (section_ != nil)
4932 section_ = [section_ retain];
4934 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4935 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4938 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4941 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4942 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
4944 [content_ setNeedsDisplay];
4947 - (void) setFrame:(CGRect)frame {
4948 [super setFrame:frame];
4950 CGRect rect([switch_ frame]);
4951 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4954 - (void) drawContentRect:(CGRect)rect {
4955 bool highlighted(highlighted_);
4957 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4962 float width(rect.size.width);
4968 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4970 CGSize size = [count_ sizeWithFont:Font14_];
4974 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4980 /* File Table {{{ */
4981 @interface FileTable : CYViewController <
4982 UITableViewDataSource,
4985 _transient Database *database_;
4988 NSMutableArray *files_;
4992 - (id) initWithDatabase:(Database *)database;
4993 - (void) setPackage:(Package *)package;
4997 @implementation FileTable
5000 if (package_ != nil)
5009 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5010 return files_ == nil ? 0 : [files_ count];
5013 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5017 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5018 static NSString *reuseIdentifier = @"Cell";
5020 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5022 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5023 [cell setFont:[UIFont systemFontOfSize:16]];
5025 [cell setText:[files_ objectAtIndex:indexPath.row]];
5026 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5031 - (id) initWithDatabase:(Database *)database {
5032 if ((self = [super init]) != nil) {
5033 database_ = database;
5035 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5037 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5039 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5040 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5041 [list_ setRowHeight:24.0f];
5042 [[self view] addSubview:list_];
5044 [list_ setDataSource:self];
5045 [list_ setDelegate:self];
5049 - (void) setPackage:(Package *)package {
5050 if (package_ != nil) {
5051 [package_ autorelease];
5060 [files_ removeAllObjects];
5062 if (package != nil) {
5063 package_ = [package retain];
5064 name_ = [[package id] retain];
5066 if (NSArray *files = [package files])
5067 [files_ addObjectsFromArray:files];
5069 if ([files_ count] != 0) {
5070 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5071 [files_ removeObjectAtIndex:0];
5072 [files_ sortUsingSelector:@selector(compareByPath:)];
5074 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5075 [stack addObject:@"/"];
5077 for (int i(0), e([files_ count]); i != e; ++i) {
5078 NSString *file = [files_ objectAtIndex:i];
5079 while (![file hasPrefix:[stack lastObject]])
5080 [stack removeLastObject];
5081 NSString *directory = [stack lastObject];
5082 [stack addObject:[file stringByAppendingString:@"/"]];
5083 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5084 ([stack count] - 2) * 3, "",
5085 [file substringFromIndex:[directory length]]
5094 - (void) reloadData {
5095 [self setPackage:[database_ packageWithName:name_]];
5100 /* Package Controller {{{ */
5101 @interface PackageController : CYBrowserController <
5102 UIActionSheetDelegate
5104 _transient Database *database_;
5108 NSMutableArray *buttons_;
5109 UIBarButtonItem *button_;
5112 - (id) initWithDatabase:(Database *)database;
5113 - (void) setPackage:(Package *)package;
5117 @implementation PackageController
5120 if (package_ != nil)
5134 if ([self retainCount] == 1)
5135 [delegate_ setPackageController:self];
5139 /* XXX: this is not safe at all... localization of /fail/ */
5140 - (void) _clickButtonWithName:(NSString *)name {
5141 if ([name isEqualToString:UCLocalize("CLEAR")])
5142 [delegate_ clearPackage:package_];
5143 else if ([name isEqualToString:UCLocalize("INSTALL")])
5144 [delegate_ installPackage:package_];
5145 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5146 [delegate_ installPackage:package_];
5147 else if ([name isEqualToString:UCLocalize("REMOVE")])
5148 [delegate_ removePackage:package_];
5149 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5150 [delegate_ installPackage:package_];
5151 else _assert(false);
5154 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5155 NSString *context([sheet context]);
5157 if ([context isEqualToString:@"modify"]) {
5158 if (button != [sheet cancelButtonIndex]) {
5159 NSString *buttonName = [buttons_ objectAtIndex:button];
5160 [self _clickButtonWithName:buttonName];
5163 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5167 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5168 [super webView:view didClearWindowObject:window forFrame:frame];
5169 [window setValue:package_ forKey:@"package"];
5172 - (bool) _allowJavaScriptPanel {
5177 - (void) _customButtonClicked {
5178 int count([buttons_ count]);
5183 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5185 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5186 [buttons addObjectsFromArray:buttons_];
5188 UIActionSheet *sheet = [[[UIActionSheet alloc]
5191 cancelButtonTitle:nil
5192 destructiveButtonTitle:nil
5193 otherButtonTitles:nil
5196 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5198 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5199 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5201 [sheet setContext:@"modify"];
5203 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5207 // We don't want to allow non-commercial packages to do custom things to the install button,
5208 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5209 - (void) customButtonClicked {
5211 [super customButtonClicked];
5213 [self _customButtonClicked];
5216 - (void) reloadButtonClicked {
5217 // Don't reload a package view by clicking the button.
5220 - (void) applyLoadingTitle {
5221 // Don't show "Loading" as the title. Ever.
5224 - (UIBarButtonItem *) rightButton {
5229 - (id) initWithDatabase:(Database *)database {
5230 if ((self = [super init]) != nil) {
5231 database_ = database;
5232 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5233 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5237 - (void) setPackage:(Package *)package {
5238 if (package_ != nil) {
5239 [package_ autorelease];
5248 [buttons_ removeAllObjects];
5250 if (package != nil) {
5253 package_ = [package retain];
5254 name_ = [[package id] retain];
5255 commercial_ = [package isCommercial];
5257 if ([package_ mode] != nil)
5258 [buttons_ addObject:UCLocalize("CLEAR")];
5259 if ([package_ source] == nil);
5260 else if ([package_ upgradableAndEssential:NO])
5261 [buttons_ addObject:UCLocalize("UPGRADE")];
5262 else if ([package_ uninstalled])
5263 [buttons_ addObject:UCLocalize("INSTALL")];
5265 [buttons_ addObject:UCLocalize("REINSTALL")];
5266 if (![package_ uninstalled])
5267 [buttons_ addObject:UCLocalize("REMOVE")];
5274 switch ([buttons_ count]) {
5275 case 0: title = nil; break;
5276 case 1: title = [buttons_ objectAtIndex:0]; break;
5277 default: title = UCLocalize("MODIFY"); break;
5280 button_ = [[UIBarButtonItem alloc]
5282 style:UIBarButtonItemStylePlain
5284 action:@selector(customButtonClicked)
5290 - (bool) isLoading {
5291 return commercial_ ? [super isLoading] : false;
5294 - (void) reloadData {
5295 [self setPackage:[database_ packageWithName:name_]];
5300 /* Package Table {{{ */
5301 @interface PackageTable : UIView <
5302 UITableViewDataSource,
5305 _transient Database *database_;
5306 NSMutableArray *packages_;
5307 NSMutableArray *sections_;
5309 NSMutableArray *index_;
5310 NSMutableDictionary *indices_;
5311 // XXX: this target_ seems to be delegate_. :(
5312 _transient id target_;
5314 // XXX: why do we even have this delegate_?
5315 _transient id delegate_;
5318 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5320 - (void) setDelegate:(id)delegate;
5322 - (void) reloadData;
5323 - (void) resetCursor;
5325 - (UITableView *) list;
5327 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5329 - (void) deselectWithAnimation:(BOOL)animated;
5333 @implementation PackageTable
5336 [packages_ release];
5337 [sections_ release];
5345 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5346 NSInteger count([sections_ count]);
5347 return count == 0 ? 1 : count;
5350 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5351 if ([sections_ count] == 0)
5353 return [[sections_ objectAtIndex:section] name];
5356 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5357 if ([sections_ count] == 0)
5359 return [[sections_ objectAtIndex:section] count];
5362 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5363 Section *section([sections_ objectAtIndex:[path section]]);
5364 NSInteger row([path row]);
5365 Package *package([packages_ objectAtIndex:([section row] + row)]);
5369 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5370 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5372 cell = [[[PackageCell alloc] init] autorelease];
5373 [cell setPackage:[self packageAtIndexPath:path]];
5377 - (void) deselectWithAnimation:(BOOL)animated {
5378 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5381 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5382 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5385 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5386 Package *package([self packageAtIndexPath:path]);
5387 package = [database_ packageWithName:[package id]];
5388 [target_ performSelector:action_ withObject:package];
5392 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5393 return [packages_ count] > 20 ? index_ : nil;
5396 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5400 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5401 if ((self = [super initWithFrame:frame]) != nil) {
5402 database_ = database;
5407 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5408 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5410 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5411 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5413 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5414 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5415 [list_ setRowHeight:73.0f];
5416 [self addSubview:list_];
5418 [list_ setDataSource:self];
5419 [list_ setDelegate:self];
5423 - (void) setDelegate:(id)delegate {
5424 delegate_ = delegate;
5427 - (bool) hasPackage:(Package *)package {
5431 - (void) reloadData {
5432 NSArray *packages = [database_ packages];
5434 [packages_ removeAllObjects];
5435 [sections_ removeAllObjects];
5437 _profile(PackageTable$reloadData$Filter)
5438 for (Package *package in packages)
5439 if ([self hasPackage:package])
5440 [packages_ addObject:package];
5443 [index_ removeAllObjects];
5444 [indices_ removeAllObjects];
5446 Section *section = nil;
5448 _profile(PackageTable$reloadData$Section)
5449 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5453 _profile(PackageTable$reloadData$Section$Package)
5454 package = [packages_ objectAtIndex:offset];
5455 index = [package index];
5458 if (section == nil || [section index] != index) {
5459 _profile(PackageTable$reloadData$Section$Allocate)
5460 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5463 [index_ addObject:[section name]];
5464 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5466 _profile(PackageTable$reloadData$Section$Add)
5467 [sections_ addObject:section];
5471 [section addToCount];
5475 _profile(PackageTable$reloadData$List)
5480 - (void) resetCursor {
5481 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5484 - (UITableView *) list {
5488 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5489 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5494 /* Filtered Package Table {{{ */
5495 @interface FilteredPackageTable : PackageTable {
5501 - (void) setObject:(id)object;
5502 - (void) setObject:(id)object forFilter:(SEL)filter;
5504 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5508 @implementation FilteredPackageTable
5516 - (void) setFilter:(SEL)filter {
5519 /* XXX: this is an unsafe optimization of doomy hell */
5520 Method method(class_getInstanceMethod([Package class], filter));
5521 _assert(method != NULL);
5522 imp_ = method_getImplementation(method);
5523 _assert(imp_ != NULL);
5526 - (void) setObject:(id)object {
5532 object_ = [object retain];
5535 - (void) setObject:(id)object forFilter:(SEL)filter {
5536 [self setFilter:filter];
5537 [self setObject:object];
5540 - (bool) hasPackage:(Package *)package {
5541 _profile(FilteredPackageTable$hasPackage)
5542 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5546 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5547 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5548 [self setFilter:filter];
5549 object_ = [object retain];
5557 /* Filtered Package Controller {{{ */
5558 @interface FilteredPackageController : CYViewController {
5559 _transient Database *database_;
5560 FilteredPackageTable *packages_;
5564 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5568 @implementation FilteredPackageController
5571 [packages_ release];
5577 - (void) viewDidAppear:(BOOL)animated {
5578 [super viewDidAppear:animated];
5579 [packages_ deselectWithAnimation:animated];
5582 - (void) didSelectPackage:(Package *)package {
5583 PackageController *view([delegate_ packageController]);
5584 [view setPackage:package];
5585 [view setDelegate:delegate_];
5586 [[self navigationController] pushViewController:view animated:YES];
5589 - (NSString *) title { return title_; }
5591 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5592 if ((self = [super init]) != nil) {
5593 database_ = database;
5594 title_ = [title copy];
5595 [[self navigationItem] setTitle:title_];
5597 packages_ = [[FilteredPackageTable alloc]
5598 initWithFrame:[[self view] bounds]
5601 action:@selector(didSelectPackage:)
5606 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5607 [[self view] addSubview:packages_];
5611 - (void) reloadData {
5612 [packages_ reloadData];
5615 - (void) setDelegate:(id)delegate {
5616 [super setDelegate:delegate];
5617 [packages_ setDelegate:delegate];
5624 /* Add Source Controller {{{ */
5625 @interface AddSourceController : CYViewController {
5626 _transient Database *database_;
5629 - (id) initWithDatabase:(Database *)database;
5633 @implementation AddSourceController
5635 - (id) initWithDatabase:(Database *)database {
5636 if ((self = [super init]) != nil) {
5637 database_ = database;
5643 /* Source Cell {{{ */
5644 @interface SourceCell : CYTableViewCell <
5649 NSString *description_;
5653 - (void) setSource:(Source *)source;
5657 @implementation SourceCell
5659 - (void) clearSource {
5662 [description_ release];
5671 - (void) setSource:(Source *)source {
5675 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5677 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5678 icon_ = [icon_ retain];
5680 origin_ = [[source name] retain];
5681 label_ = [[source uri] retain];
5682 description_ = [[source description] retain];
5684 [content_ setNeedsDisplay];
5692 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5693 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5694 UIView *content([self contentView]);
5695 CGRect bounds([content bounds]);
5697 content_ = [[ContentView alloc] initWithFrame:bounds];
5698 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5699 [content_ setBackgroundColor:[UIColor whiteColor]];
5700 [content addSubview:content_];
5702 [content_ setDelegate:self];
5703 [content_ setOpaque:YES];
5707 - (void) drawContentRect:(CGRect)rect {
5708 bool highlighted(highlighted_);
5709 float width(rect.size.width);
5712 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5719 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5723 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5727 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5732 /* Source Table {{{ */
5733 @interface SourceTable : CYViewController <
5734 UITableViewDataSource,
5737 _transient Database *database_;
5739 NSMutableArray *sources_;
5743 UIProgressHUD *hud_;
5746 //NSURLConnection *installer_;
5747 NSURLConnection *trivial_;
5748 NSURLConnection *trivial_bz2_;
5749 NSURLConnection *trivial_gz_;
5750 //NSURLConnection *automatic_;
5755 - (id) initWithDatabase:(Database *)database;
5757 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5761 @implementation SourceTable
5763 - (void) _releaseConnection:(NSURLConnection *)connection {
5764 if (connection != nil) {
5765 [connection cancel];
5766 //[connection setDelegate:nil];
5767 [connection release];
5779 //[self _releaseConnection:installer_];
5780 [self _releaseConnection:trivial_];
5781 [self _releaseConnection:trivial_gz_];
5782 [self _releaseConnection:trivial_bz2_];
5783 //[self _releaseConnection:automatic_];
5790 - (void) viewDidAppear:(BOOL)animated {
5791 [super viewDidAppear:animated];
5792 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5795 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5796 return offset_ == 0 ? 1 : 2;
5799 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5800 switch (section + (offset_ == 0 ? 1 : 0)) {
5801 case 0: return UCLocalize("ENTERED_BY_USER");
5802 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5808 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5809 int count = [sources_ count];
5811 case 0: return (offset_ == 0 ? count : offset_);
5812 case 1: return count - offset_;
5818 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5820 switch (indexPath.section) {
5821 case 0: idx = indexPath.row; break;
5822 case 1: idx = indexPath.row + offset_; break;
5826 return [sources_ objectAtIndex:idx];
5829 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5830 Source *source = [self sourceAtIndexPath:indexPath];
5831 return [source description] == nil ? 56 : 73;
5834 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5835 static NSString *cellIdentifier = @"SourceCell";
5837 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5838 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5839 [cell setSource:[self sourceAtIndexPath:indexPath]];
5844 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5845 return UITableViewCellAccessoryDisclosureIndicator;
5848 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5849 Source *source = [self sourceAtIndexPath:indexPath];
5851 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5852 initWithDatabase:database_
5853 title:[source label]
5854 filter:@selector(isVisibleInSource:)
5858 [packages setDelegate:delegate_];
5860 [[self navigationController] pushViewController:packages animated:YES];
5863 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5864 Source *source = [self sourceAtIndexPath:indexPath];
5865 return [source record] != nil;
5868 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5869 Source *source = [self sourceAtIndexPath:indexPath];
5870 [Sources_ removeObjectForKey:[source key]];
5871 [delegate_ syncData];
5875 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5878 @"./", @"Distribution",
5879 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5881 [delegate_ syncData];
5884 - (NSString *) getWarning {
5885 NSString *href(href_);
5886 NSRange colon([href rangeOfString:@"://"]);
5887 if (colon.location != NSNotFound)
5888 href = [href substringFromIndex:(colon.location + 3)];
5889 href = [href stringByAddingPercentEscapes];
5890 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5891 href = [href stringByCachingURLWithCurrentCDN];
5893 NSURL *url([NSURL URLWithString:href]);
5895 NSStringEncoding encoding;
5896 NSError *error(nil);
5898 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5899 return [warning length] == 0 ? nil : warning;
5903 - (void) _endConnection:(NSURLConnection *)connection {
5904 // XXX: the memory management in this method is horribly awkward
5906 NSURLConnection **field = NULL;
5907 if (connection == trivial_)
5909 else if (connection == trivial_bz2_)
5910 field = &trivial_bz2_;
5911 else if (connection == trivial_gz_)
5912 field = &trivial_gz_;
5913 _assert(field != NULL);
5914 [connection release];
5919 trivial_bz2_ == nil &&
5925 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5928 UIAlertView *alert = [[[UIAlertView alloc]
5929 initWithTitle:UCLocalize("SOURCE_WARNING")
5932 cancelButtonTitle:UCLocalize("CANCEL")
5933 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5936 [alert setContext:@"warning"];
5937 [alert setNumberOfRows:1];
5941 } else if (error_ != nil) {
5942 UIAlertView *alert = [[[UIAlertView alloc]
5943 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5944 message:[error_ localizedDescription]
5946 cancelButtonTitle:UCLocalize("OK")
5947 otherButtonTitles:nil
5950 [alert setContext:@"urlerror"];
5953 UIAlertView *alert = [[[UIAlertView alloc]
5954 initWithTitle:UCLocalize("NOT_REPOSITORY")
5955 message:UCLocalize("NOT_REPOSITORY_EX")
5957 cancelButtonTitle:UCLocalize("OK")
5958 otherButtonTitles:nil
5961 [alert setContext:@"trivial"];
5965 [delegate_ setStatusBarShowsProgress:NO];
5966 [delegate_ removeProgressHUD:hud_];
5976 if (error_ != nil) {
5983 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5984 switch ([response statusCode]) {
5990 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5991 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5993 error_ = [error retain];
5994 [self _endConnection:connection];
5997 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5998 [self _endConnection:connection];
6001 - (NSString *) title { return UCLocalize("SOURCES"); }
6003 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6004 NSMutableURLRequest *request = [NSMutableURLRequest
6005 requestWithURL:[NSURL URLWithString:href]
6006 cachePolicy:NSURLRequestUseProtocolCachePolicy
6007 timeoutInterval:120.0
6010 [request setHTTPMethod:method];
6012 if (Machine_ != NULL)
6013 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6014 if (UniqueID_ != nil)
6015 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6017 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6019 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6022 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6023 NSString *context([alert context]);
6025 if ([context isEqualToString:@"source"]) {
6028 NSString *href = [[alert textField] text];
6030 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6032 if (![href hasSuffix:@"/"])
6033 href_ = [href stringByAppendingString:@"/"];
6036 href_ = [href_ retain];
6038 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6039 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6040 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6041 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6045 // XXX: this is stupid
6046 hud_ = [[delegate_ addProgressHUD] retain];
6047 [hud_ setText:UCLocalize("VERIFYING_URL")];
6056 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6057 } else if ([context isEqualToString:@"trivial"])
6058 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6059 else if ([context isEqualToString:@"urlerror"])
6060 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6061 else if ([context isEqualToString:@"warning"]) {
6076 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6080 - (id) initWithDatabase:(Database *)database {
6081 if ((self = [super init]) != nil) {
6082 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6083 [self updateButtonsForEditingStatus:NO animated:NO];
6085 database_ = database;
6086 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6088 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6089 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6090 [[self view] addSubview:list_];
6092 [list_ setDataSource:self];
6093 [list_ setDelegate:self];
6099 - (void) reloadData {
6101 if (!list.ReadMainList())
6104 [sources_ removeAllObjects];
6105 [sources_ addObjectsFromArray:[database_ sources]];
6107 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6110 int count([sources_ count]);
6112 for (int i = 0; i != count; i++) {
6113 if ([[sources_ objectAtIndex:i] record] == nil)
6118 [list_ setEditing:NO];
6119 [self updateButtonsForEditingStatus:NO animated:NO];
6123 - (void) addButtonClicked {
6124 /*[book_ pushPage:[[[AddSourceController alloc]
6129 UIAlertView *alert = [[[UIAlertView alloc]
6130 initWithTitle:UCLocalize("ENTER_APT_URL")
6133 cancelButtonTitle:UCLocalize("CANCEL")
6134 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6137 [alert setContext:@"source"];
6138 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6140 [alert setNumberOfRows:1];
6141 [alert addTextFieldWithValue:@"http://" label:@""];
6143 UITextInputTraits *traits = [[alert textField] textInputTraits];
6144 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6145 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6146 [traits setKeyboardType:UIKeyboardTypeURL];
6147 // XXX: UIReturnKeyDone
6148 [traits setReturnKeyType:UIReturnKeyNext];
6153 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6154 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6155 initWithTitle:UCLocalize("ADD")
6156 style:UIBarButtonItemStylePlain
6158 action:@selector(addButtonClicked)
6159 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6161 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6162 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6163 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6165 action:@selector(editButtonClicked)
6166 ] autorelease] animated:animated];
6168 if (IsWildcat_ && !editing)
6169 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6170 initWithTitle:UCLocalize("SETTINGS")
6171 style:UIBarButtonItemStylePlain
6173 action:@selector(settingsButtonClicked)
6177 - (void) settingsButtonClicked {
6178 [delegate_ showSettings];
6181 - (void) editButtonClicked {
6182 [list_ setEditing:![list_ isEditing] animated:YES];
6184 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6190 /* Installed Controller {{{ */
6191 @interface InstalledController : FilteredPackageController {
6195 - (id) initWithDatabase:(Database *)database;
6197 - (void) updateRoleButton;
6198 - (void) queueStatusDidChange;
6202 @implementation InstalledController
6208 - (NSString *) title { return UCLocalize("INSTALLED"); }
6210 - (id) initWithDatabase:(Database *)database {
6211 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
6212 [self updateRoleButton];
6213 [self queueStatusDidChange];
6218 - (void) queueButtonClicked {
6223 - (void) queueStatusDidChange {
6227 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6228 initWithTitle:UCLocalize("QUEUE")
6229 style:UIBarButtonItemStyleDone
6231 action:@selector(queueButtonClicked)
6234 [[self navigationItem] setLeftBarButtonItem:nil];
6240 - (void) reloadData {
6241 [packages_ reloadData];
6244 - (void) updateRoleButton {
6245 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6246 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6247 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6248 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6250 action:@selector(roleButtonClicked)
6254 - (void) roleButtonClicked {
6255 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6256 [packages_ reloadData];
6259 [self updateRoleButton];
6262 - (void) setDelegate:(id)delegate {
6263 [super setDelegate:delegate];
6264 [packages_ setDelegate:delegate];
6270 /* Home Controller {{{ */
6271 @interface HomeController : CYBrowserController {
6276 @implementation HomeController
6278 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6279 [super _setMoreHeaders:request];
6282 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6283 if (UniqueID_ != nil)
6284 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6286 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6289 - (void) aboutButtonClicked {
6290 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6292 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6293 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6294 [alert setCancelButtonIndex:0];
6297 @"Copyright (C) 2008-2010\n"
6298 "Jay Freeman (saurik)\n"
6299 "saurik@saurik.com\n"
6300 "http://www.saurik.com/"
6306 - (void) viewWillAppear:(BOOL)animated {
6307 [super viewWillAppear:animated];
6308 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6311 - (void) viewWillDisappear:(BOOL)animated {
6312 [super viewWillDisappear:animated];
6313 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6317 if ((self = [super init]) != nil) {
6318 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6319 initWithTitle:UCLocalize("ABOUT")
6320 style:UIBarButtonItemStylePlain
6322 action:@selector(aboutButtonClicked)
6329 /* Manage Controller {{{ */
6330 @interface ManageController : CYBrowserController {
6333 - (void) queueStatusDidChange;
6336 @implementation ManageController
6339 if ((self = [super init]) != nil) {
6340 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6342 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6343 initWithTitle:UCLocalize("SETTINGS")
6344 style:UIBarButtonItemStylePlain
6346 action:@selector(settingsButtonClicked)
6349 [self queueStatusDidChange];
6353 - (void) settingsButtonClicked {
6354 [delegate_ showSettings];
6358 - (void) queueButtonClicked {
6362 - (void) applyLoadingTitle {
6363 // No "Loading" title.
6366 - (void) applyRightButton {
6371 - (void) queueStatusDidChange {
6373 if (!IsWildcat_ && Queuing_) {
6374 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6375 initWithTitle:UCLocalize("QUEUE")
6376 style:UIBarButtonItemStyleDone
6378 action:@selector(queueButtonClicked)
6381 [[self navigationItem] setRightBarButtonItem:nil];
6386 - (bool) isLoading {
6393 /* Refresh Bar {{{ */
6394 @interface RefreshBar : UINavigationBar {
6395 UIProgressIndicator *indicator_;
6396 UITextLabel *prompt_;
6397 UIProgressBar *progress_;
6398 UINavigationButton *cancel_;
6403 @implementation RefreshBar
6406 [indicator_ release];
6408 [progress_ release];
6413 - (void) positionViews {
6414 CGRect frame = [cancel_ frame];
6415 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6416 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6417 [cancel_ setFrame:frame];
6419 CGSize prgsize = {75, 100};
6421 [self frame].size.width - prgsize.width - 10,
6422 ([self frame].size.height - prgsize.height) / 2
6424 [progress_ setFrame:prgrect];
6426 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6427 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6428 CGRect indrect = {{indoffset, indoffset}, indsize};
6429 [indicator_ setFrame:indrect];
6431 CGSize prmsize = {215, indsize.height + 4};
6433 indoffset * 2 + indsize.width,
6434 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6436 [prompt_ setFrame:prmrect];
6439 - (void)setFrame:(CGRect)frame {
6440 [super setFrame:frame];
6442 [self positionViews];
6445 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6446 if ((self = [super initWithFrame:frame])) {
6447 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6449 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6450 [self setBarStyle:UIBarStyleBlack];
6452 UIBarStyle barstyle([self _barStyle:NO]);
6453 bool ugly(barstyle == UIBarStyleDefault);
6455 UIProgressIndicatorStyle style = ugly ?
6456 UIProgressIndicatorStyleMediumBrown :
6457 UIProgressIndicatorStyleMediumWhite;
6459 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6460 [indicator_ setStyle:style];
6461 [indicator_ startAnimation];
6462 [self addSubview:indicator_];
6464 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6465 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6466 [prompt_ setBackgroundColor:[UIColor clearColor]];
6467 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6468 [self addSubview:prompt_];
6470 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6471 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6472 [progress_ setStyle:0];
6473 [self addSubview:progress_];
6475 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6476 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6477 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6478 [cancel_ setBarStyle:barstyle];
6480 [self positionViews];
6485 [cancel_ removeFromSuperview];
6489 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6490 [progress_ setProgress:0];
6491 [self addSubview:cancel_];
6495 [cancel_ removeFromSuperview];
6498 - (void) setPrompt:(NSString *)prompt {
6499 [prompt_ setText:prompt];
6502 - (void) setProgress:(float)progress {
6503 [progress_ setProgress:progress];
6509 @class CYNavigationController;
6511 /* Cydia Tab Bar Controller {{{ */
6512 @interface CYTabBarController : UITabBarController {
6513 _transient Database *database_;
6518 @implementation CYTabBarController
6520 /* XXX: some logic should probably go here related to
6521 freeing the view controllers on tab change */
6523 - (void) reloadData {
6524 size_t count([[self viewControllers] count]);
6525 for (size_t i(0); i != count; ++i) {
6526 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6531 - (id) initWithDatabase:(Database *)database {
6532 if ((self = [super init]) != nil) {
6533 database_ = database;
6540 /* Cydia Navigation Controller {{{ */
6541 @interface CYNavigationController : UINavigationController {
6542 _transient Database *database_;
6543 _transient id<UINavigationControllerDelegate> delegate_;
6546 - (id) initWithDatabase:(Database *)database;
6547 - (void) reloadData;
6552 @implementation CYNavigationController
6554 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6555 // Inherit autorotation settings for modal parents.
6556 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6557 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6559 return [super shouldAutorotateToInterfaceOrientation:orientation];
6567 - (void) reloadData {
6568 size_t count([[self viewControllers] count]);
6569 for (size_t i(0); i != count; ++i) {
6570 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6575 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6576 delegate_ = delegate;
6579 - (id) initWithDatabase:(Database *)database {
6580 if ((self = [super init]) != nil) {
6581 database_ = database;
6587 /* Cydia:// Protocol {{{ */
6588 @interface CydiaURLProtocol : NSURLProtocol {
6593 @implementation CydiaURLProtocol
6595 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6596 NSURL *url([request URL]);
6599 NSString *scheme([[url scheme] lowercaseString]);
6600 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6605 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6609 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6610 id<NSURLProtocolClient> client([self client]);
6612 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6614 NSData *data(UIImagePNGRepresentation(icon));
6616 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6617 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6618 [client URLProtocol:self didLoadData:data];
6619 [client URLProtocolDidFinishLoading:self];
6623 - (void) startLoading {
6624 id<NSURLProtocolClient> client([self client]);
6625 NSURLRequest *request([self request]);
6627 NSURL *url([request URL]);
6628 NSString *href([url absoluteString]);
6630 NSString *path([href substringFromIndex:8]);
6631 NSRange slash([path rangeOfString:@"/"]);
6634 if (slash.location == NSNotFound) {
6638 command = [path substringToIndex:slash.location];
6639 path = [path substringFromIndex:(slash.location + 1)];
6642 Database *database([Database sharedInstance]);
6644 if ([command isEqualToString:@"package-icon"]) {
6647 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6648 Package *package([database packageWithName:path]);
6651 UIImage *icon([package icon]);
6652 [self _returnPNGWithImage:icon forRequest:request];
6653 } else if ([command isEqualToString:@"source-icon"]) {
6656 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6657 NSString *source(Simplify(path));
6658 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6660 icon = [UIImage applicationImageNamed:@"unknown.png"];
6661 [self _returnPNGWithImage:icon forRequest:request];
6662 } else if ([command isEqualToString:@"uikit-image"]) {
6665 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6666 UIImage *icon(_UIImageWithName(path));
6667 [self _returnPNGWithImage:icon forRequest:request];
6668 } else if ([command isEqualToString:@"section-icon"]) {
6671 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6672 NSString *section(Simplify(path));
6673 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6675 icon = [UIImage applicationImageNamed:@"unknown.png"];
6676 [self _returnPNGWithImage:icon forRequest:request];
6678 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6682 - (void) stopLoading {
6688 /* Sections Controller {{{ */
6689 @interface SectionsController : CYViewController <
6690 UITableViewDataSource,
6693 _transient Database *database_;
6694 NSMutableArray *sections_;
6695 NSMutableArray *filtered_;
6701 - (id) initWithDatabase:(Database *)database;
6702 - (void) reloadData;
6705 - (void) editButtonClicked;
6709 @implementation SectionsController
6712 [list_ setDataSource:nil];
6713 [list_ setDelegate:nil];
6715 [sections_ release];
6716 [filtered_ release];
6718 [accessory_ release];
6722 - (void) viewDidAppear:(BOOL)animated {
6723 [super viewDidAppear:animated];
6724 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6727 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6728 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6732 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6733 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6736 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6740 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6741 static NSString *reuseIdentifier = @"SectionCell";
6743 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6745 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6747 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6752 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6756 Section *section = [self sectionAtIndexPath:indexPath];
6757 NSString *name = [section name];
6760 if ([indexPath row] == 0) {
6763 title = UCLocalize("ALL_PACKAGES");
6766 name = [NSString stringWithString:name];
6767 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6770 title = UCLocalize("NO_SECTION");
6774 FilteredPackageController *table = [[[FilteredPackageController alloc]
6775 initWithDatabase:database_
6777 filter:@selector(isVisibleInSection:)
6781 [table setDelegate:delegate_];
6783 [[self navigationController] pushViewController:table animated:YES];
6786 - (NSString *) title { return UCLocalize("SECTIONS"); }
6788 - (id) initWithDatabase:(Database *)database {
6789 if ((self = [super init]) != nil) {
6790 database_ = database;
6792 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6794 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6795 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6797 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6798 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6799 [list_ setRowHeight:45.0f];
6800 [[self view] addSubview:list_];
6802 [list_ setDataSource:self];
6803 [list_ setDelegate:self];
6809 - (void) reloadData {
6810 NSArray *packages = [database_ packages];
6812 [sections_ removeAllObjects];
6813 [filtered_ removeAllObjects];
6815 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6818 for (Package *package in packages) {
6819 NSString *name([package section]);
6820 NSString *key(name == nil ? @"" : name);
6824 _profile(SectionsView$reloadData$Section)
6825 section = [sections objectForKey:key];
6826 if (section == nil) {
6827 _profile(SectionsView$reloadData$Section$Allocate)
6828 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6829 [sections setObject:section forKey:key];
6834 [section addToCount];
6836 _profile(SectionsView$reloadData$Filter)
6837 if (![package valid] || ![package visible])
6845 [sections_ addObjectsFromArray:[sections allValues]];
6847 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6849 for (Section *section in sections_) {
6850 size_t count([section row]);
6854 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6855 [section setCount:count];
6856 [filtered_ addObject:section];
6859 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6860 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
6861 style:UIBarButtonItemStylePlain
6863 action:@selector(editButtonClicked)
6864 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6870 - (void) resetView {
6872 [self editButtonClicked];
6875 - (void) editButtonClicked {
6876 if ((editing_ = !editing_))
6879 [delegate_ updateData];
6881 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6882 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6883 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6886 - (UIView *) accessoryView {
6892 /* Changes Controller {{{ */
6893 @interface ChangesController : CYViewController <
6894 UITableViewDataSource,
6897 _transient Database *database_;
6898 CFMutableArrayRef packages_;
6899 NSMutableArray *sections_;
6902 BOOL hasSentFirstLoad_;
6905 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6906 - (void) reloadData;
6910 @implementation ChangesController
6913 [list_ setDelegate:nil];
6914 [list_ setDataSource:nil];
6916 CFRelease(packages_);
6918 [sections_ release];
6923 - (void) viewDidAppear:(BOOL)animated {
6924 [super viewDidAppear:animated];
6925 if (!hasSentFirstLoad_) {
6926 hasSentFirstLoad_ = YES;
6927 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6929 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6933 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6934 NSInteger count([sections_ count]);
6935 return count == 0 ? 1 : count;
6938 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6939 if ([sections_ count] == 0)
6941 return [[sections_ objectAtIndex:section] name];
6944 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6945 if ([sections_ count] == 0)
6947 return [[sections_ objectAtIndex:section] count];
6950 - (Package *) packageAtIndex:(NSUInteger)index {
6951 return (Package *) CFArrayGetValueAtIndex(packages_, index);
6954 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6955 Section *section([sections_ objectAtIndex:[path section]]);
6956 NSInteger row([path row]);
6957 return [self packageAtIndex:([section row] + row)];
6960 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6961 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6963 cell = [[[PackageCell alloc] init] autorelease];
6964 [cell setPackage:[self packageAtIndexPath:path]];
6968 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
6969 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
6972 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6973 Package *package([self packageAtIndexPath:path]);
6974 PackageController *view([delegate_ packageController]);
6975 [view setDelegate:delegate_];
6976 [view setPackage:package];
6977 [[self navigationController] pushViewController:view animated:YES];
6981 - (void) refreshButtonClicked {
6982 [delegate_ beginUpdate];
6983 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
6986 - (void) upgradeButtonClicked {
6987 [delegate_ distUpgrade];
6990 - (NSString *) title { return UCLocalize("CHANGES"); }
6992 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
6993 if ((self = [super init]) != nil) {
6994 database_ = database;
6995 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
6997 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
6999 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7001 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7002 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7003 [list_ setRowHeight:73.0f];
7004 [[self view] addSubview:list_];
7006 [list_ setDataSource:self];
7007 [list_ setDelegate:self];
7009 delegate_ = delegate;
7013 - (void) _reloadPackages:(NSArray *)packages {
7015 for (Package *package in packages)
7016 if ([package upgradableAndEssential:YES] || [package visible])
7017 CFArrayAppendValue(packages_, package);
7020 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7024 - (void) reloadData {
7025 NSArray *packages = [database_ packages];
7027 CFArrayRemoveAllValues(packages_);
7029 [sections_ removeAllObjects];
7032 UIProgressHUD *hud([delegate_ addProgressHUD]);
7033 [hud setText:UCLocalize("LOADING")];
7034 //NSLog(@"HUD:%@::%@", delegate_, hud);
7035 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7036 [delegate_ removeProgressHUD:hud];
7038 [self _reloadPackages:packages];
7041 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7042 Section *ignored = nil;
7043 Section *section = nil;
7047 bool unseens = false;
7049 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7051 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7052 Package *package = [self packageAtIndex:offset];
7054 BOOL uae = [package upgradableAndEssential:YES];
7060 _profile(ChangesController$reloadData$Remember)
7061 seen = [package seen];
7064 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7069 name = UCLocalize("UNKNOWN");
7071 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7075 _profile(ChangesController$reloadData$Allocate)
7076 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7077 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7078 [sections_ addObject:section];
7082 [section addToCount];
7083 } else if ([package ignored]) {
7084 if (ignored == nil) {
7085 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7087 [ignored addToCount];
7090 [upgradable addToCount];
7095 CFRelease(formatter);
7098 Section *last = [sections_ lastObject];
7099 size_t count = [last count];
7100 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7101 [sections_ removeLastObject];
7104 if ([ignored count] != 0)
7105 [sections_ insertObject:ignored atIndex:0];
7107 [sections_ insertObject:upgradable atIndex:0];
7112 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7113 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7114 style:UIBarButtonItemStylePlain
7116 action:@selector(upgradeButtonClicked)
7119 if (![delegate_ updating])
7120 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7121 initWithTitle:UCLocalize("REFRESH")
7122 style:UIBarButtonItemStylePlain
7124 action:@selector(refreshButtonClicked)
7130 /* Search Controller {{{ */
7131 @interface SearchController : FilteredPackageController <
7134 UISearchBar *search_;
7137 - (id) initWithDatabase:(Database *)database;
7138 - (void) reloadData;
7142 @implementation SearchController
7149 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7150 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7151 [search_ resignFirstResponder];
7155 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7156 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7160 - (NSString *) title { return nil; }
7162 - (id) initWithDatabase:(Database *)database {
7163 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7166 - (void)viewDidAppear:(BOOL)animated {
7167 [super viewDidAppear:animated];
7169 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7170 [search_ layoutSubviews];
7171 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7172 UITextField *textField = [search_ searchField];
7173 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7174 [search_ setDelegate:self];
7175 [textField setEnablesReturnKeyAutomatically:NO];
7176 [[self navigationItem] setTitleView:textField];
7180 - (void) _reloadData {
7183 - (void) reloadData {
7184 _profile(SearchController$reloadData)
7185 [packages_ reloadData];
7188 [packages_ resetCursor];
7191 - (void) didSelectPackage:(Package *)package {
7192 [search_ resignFirstResponder];
7193 [super didSelectPackage:package];
7198 /* Settings Controller {{{ */
7199 @interface SettingsController : CYViewController <
7200 UITableViewDataSource,
7203 _transient Database *database_;
7206 UITableView *table_;
7207 UISwitch *subscribedSwitch_;
7208 UISwitch *ignoredSwitch_;
7209 UITableViewCell *subscribedCell_;
7210 UITableViewCell *ignoredCell_;
7213 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7217 @implementation SettingsController
7221 if (package_ != nil)
7224 [subscribedSwitch_ release];
7225 [ignoredSwitch_ release];
7226 [subscribedCell_ release];
7227 [ignoredCell_ release];
7232 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7233 if (package_ == nil)
7239 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7240 if (package_ == nil)
7246 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7247 return UCLocalize("SHOW_ALL_CHANGES_EX");
7250 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7251 if (package_ == nil)
7254 NSMutableDictionary *metadata([package_ metadata]);
7257 if (NSNumber *number = [metadata objectForKey:key])
7258 before = [number boolValue];
7262 if (value != before) {
7263 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7265 [delegate_ updateData];
7269 - (void) onSubscribed:(id)control {
7270 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7273 - (void) onIgnored:(id)control {
7274 // TODO: set Held state - possibly call out to dpkg, etc.
7277 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7278 if (package_ == nil)
7281 switch ([indexPath row]) {
7282 case 0: return subscribedCell_;
7283 case 1: return ignoredCell_;
7291 - (NSString *) title { return UCLocalize("SETTINGS"); }
7293 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7294 if ((self = [super init])) {
7295 database_ = database;
7296 name_ = [package retain];
7298 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7300 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7301 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7302 [[self view] addSubview:table_];
7304 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7305 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7306 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7308 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7309 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7310 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7312 subscribedCell_ = [[UITableViewCell alloc] init];
7313 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7314 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7315 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7317 ignoredCell_ = [[UITableViewCell alloc] init];
7318 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7319 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7320 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7322 [table_ setDataSource:self];
7323 [table_ setDelegate:self];
7328 - (void) reloadData {
7329 if (package_ != nil)
7330 [package_ autorelease];
7331 package_ = [database_ packageWithName:name_];
7332 if (package_ != nil) {
7334 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7335 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7338 [table_ reloadData];
7343 /* Signature Controller {{{ */
7344 @interface SignatureController : CYBrowserController {
7345 _transient Database *database_;
7349 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7353 @implementation SignatureController
7360 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7362 [super webView:view didClearWindowObject:window forFrame:frame];
7365 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7366 if ((self = [super init]) != nil) {
7367 database_ = database;
7368 package_ = [package retain];
7373 - (void) reloadData {
7374 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7380 /* Role Controller {{{ */
7381 @interface RoleController : CYViewController <
7382 UITableViewDataSource,
7385 _transient Database *database_;
7386 // XXX: ok, "roledelegate_"?...
7387 _transient id roledelegate_;
7388 UITableView *table_;
7389 UISegmentedControl *segment_;
7393 - (void) showDoneButton;
7394 - (void) resizeSegmentedControl;
7398 @implementation RoleController
7402 [container_ release];
7407 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7408 if ((self = [super init])) {
7409 database_ = database;
7410 roledelegate_ = delegate;
7412 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7414 NSArray *items = [NSArray arrayWithObjects:
7416 UCLocalize("HACKER"),
7417 UCLocalize("DEVELOPER"),
7419 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7420 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7421 [container_ addSubview:segment_];
7424 if ([Role_ isEqualToString:@"User"]) index = 0;
7425 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7426 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7428 [segment_ setSelectedSegmentIndex:index];
7429 [self showDoneButton];
7432 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7433 [self resizeSegmentedControl];
7435 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7436 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7437 [table_ setDelegate:self];
7438 [table_ setDataSource:self];
7439 [[self view] addSubview:table_];
7440 [table_ reloadData];
7444 - (void) resizeSegmentedControl {
7445 CGFloat width = [[self view] frame].size.width;
7446 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7449 - (void) viewWillAppear:(BOOL)animated {
7450 [super viewWillAppear:animated];
7452 [self resizeSegmentedControl];
7455 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7456 [self resizeSegmentedControl];
7459 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7460 [self resizeSegmentedControl];
7464 NSString *role(nil);
7466 switch ([segment_ selectedSegmentIndex]) {
7467 case 0: role = @"User"; break;
7468 case 1: role = @"Hacker"; break;
7469 case 2: role = @"Developer"; break;
7474 if (![role isEqualToString:Role_]) {
7475 bool rolling(Role_ == nil);
7478 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7482 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7487 [roledelegate_ loadData];
7489 [roledelegate_ updateData];
7493 - (void) segmentChanged:(UISegmentedControl *)control {
7494 [self showDoneButton];
7497 - (void) saveAndClose {
7500 [[self navigationItem] setRightBarButtonItem:nil];
7501 [[self navigationController] dismissModalViewControllerAnimated:YES];
7504 - (void) doneButtonClicked {
7505 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7506 [spinner startAnimating];
7507 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7508 [[self navigationItem] setRightBarButtonItem:spinItem];
7510 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7513 - (void) showDoneButton {
7514 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7515 initWithTitle:UCLocalize("DONE")
7516 style:UIBarButtonItemStyleDone
7518 action:@selector(doneButtonClicked)
7519 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
7522 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7523 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7527 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7531 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7532 return nil; // This method is required by the protocol.
7535 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7537 return UCLocalize("ROLE_EX");
7539 return [NSString stringWithFormat:
7540 @"%@: %@\n%@: %@\n%@: %@",
7541 UCLocalize("USER"), UCLocalize("USER_EX"),
7542 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7543 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7548 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7549 return section == 3 ? 44.0f : 0;
7552 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7553 return section == 3 ? container_ : nil;
7558 /* Stash Controller {{{ */
7559 @interface CYStashController : CYViewController {
7560 // XXX: just delete these things
7561 _transient UIActivityIndicatorView *spinner_;
7562 _transient UILabel *status_;
7563 _transient UILabel *caption_;
7567 @implementation CYStashController
7569 if ((self = [super init])) {
7570 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7572 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
7573 CGRect spinrect = [spinner_ frame];
7574 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7575 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7576 [spinner_ setFrame:spinrect];
7577 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7578 [[self view] addSubview:spinner_];
7579 [spinner_ startAnimating];
7582 captrect.size.width = [[self view] frame].size.width;
7583 captrect.size.height = 40.0f;
7584 captrect.origin.x = 0;
7585 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7586 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
7587 [caption_ setText:@"Initializing Filesystem"];
7588 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7589 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7590 [caption_ setTextColor:[UIColor whiteColor]];
7591 [caption_ setBackgroundColor:[UIColor clearColor]];
7592 [caption_ setShadowColor:[UIColor blackColor]];
7593 [caption_ setTextAlignment:UITextAlignmentCenter];
7594 [[self view] addSubview:caption_];
7597 statusrect.size.width = [[self view] frame].size.width;
7598 statusrect.size.height = 30.0f;
7599 statusrect.origin.x = 0;
7600 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7601 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
7602 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7603 [status_ setText:@"(Cydia will exit when complete.)"];
7604 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7605 [status_ setTextColor:[UIColor whiteColor]];
7606 [status_ setBackgroundColor:[UIColor clearColor]];
7607 [status_ setShadowColor:[UIColor blackColor]];
7608 [status_ setTextAlignment:UITextAlignmentCenter];
7609 [[self view] addSubview:status_];
7613 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7614 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7619 /* Cydia Container {{{ */
7620 @interface CYContainer : UIViewController <ProgressDelegate> {
7621 _transient Database *database_;
7622 RefreshBar *refreshbar_;
7626 // XXX: ok, "updatedelegate_"?...
7627 _transient NSObject<CydiaDelegate> *updatedelegate_;
7628 // XXX: can't we query for this variable when we need it?
7629 _transient UITabBarController *root_;
7632 - (void) setTabBarController:(UITabBarController *)controller;
7634 - (void) dropBar:(BOOL)animated;
7635 - (void) beginUpdate;
7636 - (void) raiseBar:(BOOL)animated;
7641 @implementation CYContainer
7643 - (BOOL) _reallyWantsFullScreenLayout {
7647 // NOTE: UIWindow only sends the top controller these messages,
7648 // So we have to forward them on.
7650 - (void) viewDidAppear:(BOOL)animated {
7651 [super viewDidAppear:animated];
7652 [root_ viewDidAppear:animated];
7655 - (void) viewWillAppear:(BOOL)animated {
7656 [super viewWillAppear:animated];
7657 [root_ viewWillAppear:animated];
7660 - (void) viewDidDisappear:(BOOL)animated {
7661 [super viewDidDisappear:animated];
7662 [root_ viewDidDisappear:animated];
7665 - (void) viewWillDisappear:(BOOL)animated {
7666 [super viewWillDisappear:animated];
7667 [root_ viewWillDisappear:animated];
7670 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7671 return ![updatedelegate_ hudIsShowing] && (IsWildcat_ || orientation == UIInterfaceOrientationPortrait);
7674 - (void) setTabBarController:(UITabBarController *)controller {
7676 [[self view] addSubview:[root_ view]];
7679 - (void) setUpdate:(NSDate *)date {
7683 - (void) beginUpdate {
7685 [refreshbar_ start];
7690 detachNewThreadSelector:@selector(performUpdate)
7696 - (void) performUpdate { _pooled
7698 status.setDelegate(self);
7699 [database_ updateWithStatus:status];
7702 performSelectorOnMainThread:@selector(completeUpdate)
7708 - (void) completeUpdate {
7713 [self raiseBar:YES];
7715 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7718 - (void) cancelUpdate {
7720 [self raiseBar:YES];
7722 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7725 - (void) cancelPressed {
7726 [self cancelUpdate];
7733 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7734 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7737 - (void) startProgress {
7740 - (void) setProgressTitle:(NSString *)title {
7742 performSelectorOnMainThread:@selector(_setProgressTitle:)
7748 - (bool) isCancelling:(size_t)received {
7752 - (void) setProgressPercent:(float)percent {
7754 performSelectorOnMainThread:@selector(_setProgressPercent:)
7755 withObject:[NSNumber numberWithFloat:percent]
7760 - (void) addProgressOutput:(NSString *)output {
7762 performSelectorOnMainThread:@selector(_addProgressOutput:)
7768 - (void) _setProgressTitle:(NSString *)title {
7769 [refreshbar_ setPrompt:title];
7772 - (void) _setProgressPercent:(NSNumber *)percent {
7773 [refreshbar_ setProgress:[percent floatValue]];
7776 - (void) _addProgressOutput:(NSString *)output {
7779 - (void) setUpdateDelegate:(id)delegate {
7780 updatedelegate_ = delegate;
7783 - (CGFloat) statusBarHeight {
7784 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7785 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7787 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7791 - (void) dropBar:(BOOL)animated {
7796 [[self view] addSubview:refreshbar_];
7798 CGFloat sboffset = [self statusBarHeight];
7800 CGRect barframe = [refreshbar_ frame];
7801 barframe.origin.y = sboffset;
7802 [refreshbar_ setFrame:barframe];
7805 [UIView beginAnimations:nil context:NULL];
7806 CGRect viewframe = [[root_ view] frame];
7807 viewframe.origin.y += barframe.size.height + sboffset;
7808 viewframe.size.height -= barframe.size.height + sboffset;
7809 [[root_ view] setFrame:viewframe];
7811 [UIView commitAnimations];
7813 // Ensure bar has the proper width for our view, it might have changed
7814 barframe.size.width = viewframe.size.width;
7815 [refreshbar_ setFrame:barframe];
7817 // XXX: fix Apple's layout bug
7818 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7821 - (void) raiseBar:(BOOL)animated {
7826 [refreshbar_ removeFromSuperview];
7828 CGFloat sboffset = [self statusBarHeight];
7831 [UIView beginAnimations:nil context:NULL];
7832 CGRect barframe = [refreshbar_ frame];
7833 CGRect viewframe = [[root_ view] frame];
7834 viewframe.origin.y -= barframe.size.height + sboffset;
7835 viewframe.size.height += barframe.size.height + sboffset;
7836 [[root_ view] setFrame:viewframe];
7838 [UIView commitAnimations];
7840 // XXX: fix Apple's layout bug
7841 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7844 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7845 // XXX: fix Apple's layout bug
7846 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7849 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7855 // XXX: fix Apple's layout bug
7856 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7859 - (void) statusBarFrameChanged:(NSNotification *)notification {
7867 [refreshbar_ release];
7868 [[NSNotificationCenter defaultCenter] removeObserver:self];
7872 - (id) initWithDatabase:(Database *)database {
7873 if ((self = [super init]) != nil) {
7874 database_ = database;
7876 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7877 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7879 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7896 @interface Cydia : UIApplication <
7897 ConfirmationControllerDelegate,
7898 ProgressControllerDelegate,
7900 UINavigationControllerDelegate,
7901 UITabBarControllerDelegate
7903 // XXX: evaluate all fields for _transient
7906 CYContainer *container_;
7907 CYTabBarController *tabbar_;
7909 NSMutableArray *essential_;
7910 NSMutableArray *broken_;
7912 Database *database_;
7916 UIKeyboard *keyboard_;
7919 SectionsController *sections_;
7920 ChangesController *changes_;
7921 ManageController *manage_;
7922 SearchController *search_;
7923 SourceTable *sources_;
7924 InstalledController *installed_;
7927 CYStashController *stash_;
7932 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7933 - (void) setPage:(CYViewController *)page;
7938 static _finline void _setHomePage(Cydia *self) {
7939 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7942 @implementation Cydia
7944 - (void) beginUpdate {
7945 [container_ beginUpdate];
7949 return [container_ updating];
7952 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7957 if ([broken_ count] != 0) {
7958 int count = [broken_ count];
7960 UIAlertView *alert = [[[UIAlertView alloc]
7961 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7962 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7964 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7965 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
7968 [alert setContext:@"fixhalf"];
7970 } else if (!Ignored_ && [essential_ count] != 0) {
7971 int count = [essential_ count];
7973 UIAlertView *alert = [[[UIAlertView alloc]
7974 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7975 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
7977 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
7978 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
7981 [alert setContext:@"upgrade"];
7986 - (void) _saveConfig {
7989 NSString *error(nil);
7990 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7992 NSError *error(nil);
7993 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7994 NSLog(@"failure to save metadata data: %@", error);
7997 NSLog(@"failure to serialize metadata: %@", error);
8005 - (void) _updateData {
8008 /* XXX: this is just stupid */
8009 if (tag_ != 1 && sections_ != nil)
8010 [sections_ reloadData];
8011 if (tag_ != 2 && changes_ != nil)
8012 [changes_ reloadData];
8013 if (tag_ != 4 && search_ != nil)
8014 [search_ reloadData];
8016 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8019 - (int)indexOfTabWithTag:(int)tag {
8021 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8022 if ([[controller tabBarItem] tag] == tag)
8030 - (void) _refreshIfPossible {
8031 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8033 bool recently = false;
8034 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8035 if (update != nil) {
8036 NSTimeInterval interval([update timeIntervalSinceNow]);
8037 if (interval <= 0 && interval > -(15*60))
8041 // Don't automatic refresh if:
8042 // - We already refreshed recently.
8043 // - We already auto-refreshed this launch.
8044 // - Auto-refresh is disabled.
8045 if (recently || loaded_ || ManualRefresh) {
8046 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8048 // If we are cancelling due to ManualRefresh or a recent refresh
8049 // we need to make sure it knows it's already loaded.
8053 // We are going to load, so remember that.
8057 SCNetworkReachabilityFlags flags; {
8058 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8059 SCNetworkReachabilityGetFlags(reachability, &flags);
8060 CFRelease(reachability);
8063 // XXX: this elaborate mess is what Apple is using to determine this? :(
8064 // XXX: do we care if the user has to intervene? maybe that's ok?
8066 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8067 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8068 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8069 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8070 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8071 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8075 // If we can reach the server, auto-refresh!
8077 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8082 - (void) refreshIfPossible {
8083 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8086 - (void) _reloadData {
8087 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8088 [hud setText:UCLocalize("RELOADING_DATA")];
8090 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8093 [self removeProgressHUD:hud];
8097 [essential_ removeAllObjects];
8098 [broken_ removeAllObjects];
8100 NSArray *packages([database_ packages]);
8101 for (Package *package in packages) {
8103 [broken_ addObject:package];
8104 if ([package upgradableAndEssential:NO]) {
8105 if ([package essential])
8106 [essential_ addObject:package];
8111 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8113 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8114 [changesItem setBadgeValue:badge];
8115 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8117 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8118 [self setApplicationBadge:badge];
8120 [self setApplicationBadgeString:badge];
8122 [changesItem setBadgeValue:nil];
8123 [changesItem setAnimatedBadge:NO];
8125 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8126 [self removeApplicationBadge];
8127 else // XXX: maybe use setApplicationBadgeString also?
8128 [self setApplicationIconBadgeNumber:0];
8133 [self refreshIfPossible];
8136 - (void) updateData {
8145 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8146 _assert(file != NULL);
8148 for (NSString *key in [Sources_ allKeys]) {
8149 NSDictionary *source([Sources_ objectForKey:key]);
8151 fprintf(file, "%s %s %s\n",
8152 [[source objectForKey:@"Type"] UTF8String],
8153 [[source objectForKey:@"URI"] UTF8String],
8154 [[source objectForKey:@"Distribution"] UTF8String]
8162 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8163 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8165 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8166 [container_ presentModalViewController:navigation animated:YES];
8169 detachNewThreadSelector:@selector(update_)
8172 title:UCLocalize("UPDATING_SOURCES")
8176 - (void) reloadData {
8177 @synchronized (self) {
8183 pkgProblemResolver *resolver = [database_ resolver];
8185 resolver->InstallProtect();
8186 if (!resolver->Resolve(true))
8190 - (CGRect) popUpBounds {
8191 return [[tabbar_ view] bounds];
8195 if (![database_ prepare])
8198 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8199 [page setDelegate:self];
8200 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8201 [confirm_ setDelegate:self];
8204 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8205 [container_ presentModalViewController:confirm_ animated:YES];
8211 @synchronized (self) {
8216 - (void) clearPackage:(Package *)package {
8217 @synchronized (self) {
8224 - (void) installPackages:(NSArray *)packages {
8225 @synchronized (self) {
8226 for (Package *package in packages)
8233 - (void) installPackage:(Package *)package {
8234 @synchronized (self) {
8241 - (void) removePackage:(Package *)package {
8242 @synchronized (self) {
8249 - (void) distUpgrade {
8250 @synchronized (self) {
8251 if (![database_ upgrade])
8258 @synchronized (self) {
8263 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8264 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8266 if (navigation != nil) {
8267 [navigation pushViewController:progress animated:YES];
8269 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8271 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8272 [container_ presentModalViewController:navigation animated:YES];
8276 detachNewThreadSelector:@selector(perform)
8279 title:UCLocalize("RUNNING")
8283 - (void) progressControllerIsComplete:(ProgressController *)progress {
8287 - (void) setPage:(CYViewController *)page {
8288 [page setDelegate:self];
8290 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8291 [navController setViewControllers:[NSArray arrayWithObject:page]];
8292 for (CYNavigationController *page in [tabbar_ viewControllers])
8293 if (page != navController)
8294 [page setViewControllers:nil];
8297 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8298 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8299 [browser loadURL:url];
8303 - (SectionsController *) sectionsController {
8304 if (sections_ == nil)
8305 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8309 - (ChangesController *) changesController {
8310 if (changes_ == nil)
8311 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8315 - (ManageController *) manageController {
8316 if (manage_ == nil) {
8317 manage_ = (ManageController *) [[self
8318 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8319 withClass:[ManageController class]
8322 queueDelegate_ = manage_;
8327 - (SearchController *) searchController {
8329 search_ = [[SearchController alloc] initWithDatabase:database_];
8333 - (SourceTable *) sourcesController {
8334 if (sources_ == nil)
8335 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8339 - (InstalledController *) installedController {
8340 if (installed_ == nil) {
8341 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8343 queueDelegate_ = installed_;
8348 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8349 int tag = [[viewController tabBarItem] tag];
8351 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8353 } else if (tag_ == 1) {
8354 [[self sectionsController] resetView];
8358 case kCydiaTag: _setHomePage(self); break;
8360 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8361 case kChangesTag: [self setPage:[self changesController]]; break;
8362 case kManageTag: [self setPage:[self manageController]]; break;
8363 case kInstalledTag: [self setPage:[self installedController]]; break;
8364 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8365 case kSearchTag: [self setPage:[self searchController]]; break;
8373 - (void) showSettings {
8374 RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease];
8375 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8377 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8378 [container_ presentModalViewController:nav animated:YES];
8381 - (void) setPackageController:(PackageController *)view {
8383 [view setPackage:nil];
8387 - (PackageController *) _packageController {
8388 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8391 - (PackageController *) packageController {
8392 return [self _packageController];
8395 // Returns the navigation controller for the queuing badge.
8396 - (id) queueBadgeController {
8397 int index = [self indexOfTabWithTag:kManageTag];
8399 index = [self indexOfTabWithTag:kInstalledTag];
8401 return [[tabbar_ viewControllers] objectAtIndex:index];
8404 - (void) cancelAndClear:(bool)clear {
8405 @synchronized (self) {
8411 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
8415 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8419 [queueDelegate_ queueStatusDidChange];
8423 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8424 NSString *context([alert context]);
8426 if ([context isEqualToString:@"fixhalf"]) {
8427 if (button == [alert firstOtherButtonIndex]) {
8428 @synchronized (self) {
8429 for (Package *broken in broken_) {
8432 NSString *id = [broken id];
8433 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8434 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8435 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8436 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8442 } else if (button == [alert cancelButtonIndex]) {
8443 [broken_ removeAllObjects];
8447 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8448 } else if ([context isEqualToString:@"upgrade"]) {
8449 if (button == [alert firstOtherButtonIndex]) {
8450 @synchronized (self) {
8451 for (Package *essential in essential_)
8452 [essential install];
8457 } else if (button == [alert firstOtherButtonIndex] + 1) {
8459 } else if (button == [alert cancelButtonIndex]) {
8463 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8467 - (void) system:(NSString *)command { _pooled
8468 system([command UTF8String]);
8471 - (void) applicationWillSuspend {
8473 [super applicationWillSuspend];
8476 - (BOOL) hudIsShowing {
8480 - (void) applicationSuspend:(__GSEvent *)event {
8481 // Use external process status API internally.
8482 // This is probably a really bad idea.
8483 uint64_t status = 0;
8485 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8486 notify_get_state(notify_token, &status);
8487 notify_cancel(notify_token);
8490 if (![self hudIsShowing] && status == 0)
8491 [super applicationSuspend:event];
8494 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8495 if (![self hudIsShowing])
8496 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8499 - (void) _setSuspended:(BOOL)value {
8500 if (![self hudIsShowing])
8501 [super _setSuspended:value];
8504 - (UIProgressHUD *) addProgressHUD {
8505 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8506 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8508 [window_ setUserInteractionEnabled:NO];
8511 UIViewController *target = container_;
8512 while ([target modalViewController] != nil) target = [target modalViewController];
8513 [[target view] addSubview:hud];
8519 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8521 [hud removeFromSuperview];
8522 [window_ setUserInteractionEnabled:YES];
8526 - (CYViewController *) pageForPackage:(NSString *)name {
8527 if (Package *package = [database_ packageWithName:name]) {
8528 PackageController *view([self packageController]);
8529 [view setPackage:package];
8532 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8533 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8534 return [self _pageForURL:url withClass:[CYBrowserController class]];
8538 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8542 NSString *href([url absoluteString]);
8543 if ([href hasPrefix:@"apptapp://package/"])
8544 return [self pageForPackage:[href substringFromIndex:18]];
8546 NSString *scheme([[url scheme] lowercaseString]);
8547 if (![scheme isEqualToString:@"cydia"])
8549 NSString *path([url absoluteString]);
8550 if ([path length] < 8)
8552 path = [path substringFromIndex:8];
8553 if (![path hasPrefix:@"/"])
8554 path = [@"/" stringByAppendingString:path];
8556 if ([path isEqualToString:@"/add-source"])
8557 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8558 else if ([path isEqualToString:@"/storage"])
8559 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8560 else if ([path isEqualToString:@"/sources"])
8561 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8562 else if ([path isEqualToString:@"/packages"])
8563 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8564 else if ([path hasPrefix:@"/url/"])
8565 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8566 else if ([path hasPrefix:@"/launch/"])
8567 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8568 else if ([path hasPrefix:@"/package-settings/"])
8569 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8570 else if ([path hasPrefix:@"/package-signature/"])
8571 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8572 else if ([path hasPrefix:@"/package/"])
8573 return [self pageForPackage:[path substringFromIndex:9]];
8574 else if ([path hasPrefix:@"/files/"]) {
8575 NSString *name = [path substringFromIndex:7];
8577 if (Package *package = [database_ packageWithName:name]) {
8578 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8579 [files setPackage:package];
8587 - (void) applicationOpenURL:(NSURL *)url {
8588 [super applicationOpenURL:url];
8590 if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
8591 [self setPage:page];
8593 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8597 - (void) applicationWillResignActive:(UIApplication *)application {
8598 // Stop refreshing if you get a phone call or lock the device.
8599 if ([container_ updating])
8600 [container_ cancelUpdate];
8602 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8603 [super applicationWillResignActive:application];
8606 - (void) addStashController {
8607 stash_ = [[CYStashController alloc] init];
8608 [window_ addSubview:[stash_ view]];
8611 - (void) removeStashController {
8612 [[stash_ view] removeFromSuperview];
8617 [self setIdleTimerDisabled:YES];
8619 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8620 [self setStatusBarShowsProgress:YES];
8621 UpdateExternalStatus(1);
8623 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8625 UpdateExternalStatus(0);
8626 [self setStatusBarShowsProgress:NO];
8628 [self removeStashController];
8630 if (ExecFork() == 0) {
8631 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8632 perror("launchctl stop");
8636 - (void) setupTabBarController {
8637 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8638 [tabbar_ setDelegate:self];
8640 NSMutableArray *items([NSMutableArray arrayWithObjects:
8641 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8642 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8643 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8644 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8648 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8649 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8651 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8654 NSMutableArray *controllers([NSMutableArray array]);
8656 for (UITabBarItem *item in items) {
8657 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8658 [controller setTabBarItem:item];
8659 [controllers addObject:controller];
8662 [tabbar_ setViewControllers:controllers];
8665 - (void) applicationDidFinishLaunching:(id)unused {
8666 [CYBrowserController _initialize];
8668 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8670 Font12_ = [[UIFont systemFontOfSize:12] retain];
8671 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8672 Font14_ = [[UIFont systemFontOfSize:14] retain];
8673 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8674 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8678 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8679 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8681 UIScreen *screen([UIScreen mainScreen]);
8683 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8684 [window_ orderFront:self];
8685 [window_ makeKey:self];
8686 [window_ setHidden:NO];
8689 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8690 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8691 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8692 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8693 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8694 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8695 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8696 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8697 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8700 [self addStashController];
8701 // XXX: this would be much cleaner as a yieldToSelector:
8702 // that way the removeStashController could happen right here inline
8703 // we also could no longer require the useless stash_ field anymore
8704 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8708 database_ = [Database sharedInstance];
8710 [self setupTabBarController];
8712 container_ = [[CYContainer alloc] initWithDatabase:database_];
8713 [container_ setUpdateDelegate:self];
8714 [container_ setTabBarController:tabbar_];
8715 [window_ addSubview:[container_ view]];
8717 // Show pinstripes while loading data.
8718 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8720 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8727 [self showSettings];
8731 [window_ setUserInteractionEnabled:NO];
8733 UIView *container = [[[UIView alloc] init] autorelease];
8734 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8736 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
8737 [spinner startAnimating];
8738 [container addSubview:spinner];
8740 UILabel *label = [[[UILabel alloc] init] autorelease];
8741 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8742 [label setBackgroundColor:[UIColor clearColor]];
8743 [label setTextColor:[UIColor blackColor]];
8744 [label setShadowColor:[UIColor whiteColor]];
8745 [label setShadowOffset:CGSizeMake(0, 1)];
8746 [label setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
8747 [container addSubview:label];
8749 CGSize viewsize = [[tabbar_ view] frame].size;
8750 CGSize spinnersize = [spinner bounds].size;
8751 CGSize textsize = [[label text] sizeWithFont:[label font]];
8752 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8754 CGRect containrect = {
8755 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8756 CGSizeMake(bothwidth, spinnersize.height)
8759 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8767 [container setFrame:containrect];
8768 [spinner setFrame:spinrect];
8769 [label setFrame:textrect];
8770 [[container_ view] addSubview:container];
8775 // Show the home page
8776 [tabbar_ setSelectedIndex:0];
8778 [window_ setUserInteractionEnabled:YES];
8780 // XXX: does this actually slow anything down?
8781 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8782 [container removeFromSuperview];
8785 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8786 if (item != nil && IsWildcat_) {
8787 [sheet showFromBarButtonItem:item animated:YES];
8789 [sheet showInView:window_];
8796 id Alloc_(id self, SEL selector) {
8797 id object = alloc_(self, selector);
8798 lprintf("[%s]A-%p\n", self->isa->name, object);
8803 id Dealloc_(id self, SEL selector) {
8804 id object = dealloc_(self, selector);
8805 lprintf("[%s]D-%p\n", self->isa->name, object);
8809 Class $WebDefaultUIKitDelegate;
8811 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8812 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8813 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8814 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8817 static NSNumber *shouldPlayKeyboardSounds;
8821 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8823 case 1104: // Keyboard Button Clicked
8824 case 1105: // Keyboard Delete Repeated
8825 if (shouldPlayKeyboardSounds == nil) {
8826 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8827 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8830 if (![shouldPlayKeyboardSounds boolValue])
8834 _UIHardware$_playSystemSound$(self, _cmd, sound);
8838 int main(int argc, char *argv[]) { _pooled
8841 if (Class $UIDevice = objc_getClass("UIDevice")) {
8842 UIDevice *device([$UIDevice currentDevice]);
8843 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8847 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8849 /* Library Hacks {{{ */
8850 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8852 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8853 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8854 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8855 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8856 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8859 $UIHardware = objc_getClass("UIHardware");
8860 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8861 if (UIHardware$_playSystemSound$ != NULL) {
8862 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8863 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8866 /* Set Locale {{{ */
8867 Locale_ = CFLocaleCopyCurrent();
8868 Languages_ = [NSLocale preferredLanguages];
8869 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8870 //NSLog(@"%@", [Languages_ description]);
8873 if (Languages_ == nil || [Languages_ count] == 0)
8874 // XXX: consider just setting to C and then falling through?
8877 lang = [[Languages_ objectAtIndex:0] UTF8String];
8878 setenv("LANG", lang, true);
8881 //std::setlocale(LC_ALL, lang);
8882 NSLog(@"Setting Language: %s", lang);
8885 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8887 /* Parse Arguments {{{ */
8888 bool substrate(false);
8894 for (int argi(1); argi != argc; ++argi)
8895 if (strcmp(argv[argi], "--") == 0) {
8897 argv[argi] = argv[0];
8903 for (int argi(1); argi != arge; ++argi)
8904 if (strcmp(args[argi], "--substrate") == 0)
8907 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8911 App_ = [[NSBundle mainBundle] bundlePath];
8912 Home_ = NSHomeDirectory();
8918 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8919 alloc_ = alloc->method_imp;
8920 alloc->method_imp = (IMP) &Alloc_;*/
8922 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8923 dealloc_ = dealloc->method_imp;
8924 dealloc->method_imp = (IMP) &Dealloc_;*/
8926 /* System Information {{{ */
8930 size = sizeof(maxproc);
8931 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8932 perror("sysctlbyname(\"kern.maxproc\", ?)");
8933 else if (maxproc < 64) {
8935 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8936 perror("sysctlbyname(\"kern.maxproc\", #)");
8939 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8940 char *osversion = new char[size];
8941 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8942 perror("sysctlbyname(\"kern.osversion\", ?)");
8944 System_ = [NSString stringWithUTF8String:osversion];
8946 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8947 char *machine = new char[size];
8948 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8949 perror("sysctlbyname(\"hw.machine\", ?)");
8953 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8954 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8955 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8956 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8960 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8961 NSData *data((NSData *) ecid);
8962 size_t length([data length]);
8963 uint8_t bytes[length];
8964 [data getBytes:bytes];
8965 char string[length * 2 + 1];
8966 for (size_t i(0); i != length; ++i)
8967 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8968 ChipID_ = [NSString stringWithUTF8String:string];
8972 IOObjectRelease(service);
8976 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8978 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
8979 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
8980 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
8982 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
8983 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
8984 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
8986 if (mcc != NULL && mnc != NULL)
8987 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
8994 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8995 Build_ = [system objectForKey:@"ProductBuildVersion"];
8996 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8997 Product_ = [info objectForKey:@"SafariProductVersion"];
8998 Safari_ = [info objectForKey:@"CFBundleVersion"];
9001 /* Load Database {{{ */
9003 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9005 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9007 if (Metadata_ == NULL)
9008 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9010 Settings_ = [Metadata_ objectForKey:@"Settings"];
9012 Packages_ = [Metadata_ objectForKey:@"Packages"];
9013 Sections_ = [Metadata_ objectForKey:@"Sections"];
9014 Sources_ = [Metadata_ objectForKey:@"Sources"];
9016 Token_ = [Metadata_ objectForKey:@"Token"];
9019 if (Settings_ != nil)
9020 Role_ = [Settings_ objectForKey:@"Role"];
9022 if (Packages_ == nil) {
9023 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
9024 [Metadata_ setObject:Packages_ forKey:@"Packages"];
9027 if (Sections_ == nil) {
9028 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9029 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9032 if (Sources_ == nil) {
9033 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9034 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9038 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9040 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9041 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9042 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9043 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9044 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9045 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9047 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9049 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9050 unlink("/tmp/.cydia.fw");
9052 } else if (access("/User", F_OK) != 0 || version < 2) {
9055 system("/usr/libexec/cydia/firmware.sh");
9059 _assert([[NSFileManager defaultManager]
9060 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9061 withIntermediateDirectories:YES
9066 if (access("/tmp/cydia.chk", F_OK) == 0) {
9067 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9068 _assert(errno == ENOENT);
9069 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9070 _assert(errno == ENOENT);
9073 /* APT Initialization {{{ */
9074 _assert(pkgInitConfig(*_config));
9075 _assert(pkgInitSystem(*_config, _system));
9078 _config->Set("APT::Acquire::Translation", lang);
9080 // XXX: this timeout might be important :(
9081 //_config->Set("Acquire::http::Timeout", 15);
9083 _config->Set("Acquire::http::MaxParallel", 3);
9085 /* Color Choices {{{ */
9086 space_ = CGColorSpaceCreateDeviceRGB();
9088 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9089 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9090 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9091 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9092 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9093 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9094 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9095 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9096 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9098 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9099 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9101 /* UIKit Configuration {{{ */
9102 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9103 if ($GSFontSetUseLegacyFontMetrics != NULL)
9104 $GSFontSetUseLegacyFontMetrics(YES);
9106 // XXX: I have a feeling this was important
9107 //UIKeyboardDisableAutomaticAppearance();
9110 Colon_ = UCLocalize("COLON_DELIMITED");
9111 Elision_ = UCLocalize("ELISION");
9112 Error_ = UCLocalize("ERROR");
9113 Warning_ = UCLocalize("WARNING");
9116 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9118 CGColorSpaceRelease(space_);