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 <ext/hash_map>
123 #include "UICaboodle/BrowserView.h"
125 #include "substrate.h"
132 #define _timestamp ({ \
134 gettimeofday(&tv, NULL); \
135 tv.tv_sec * 1000000 + tv.tv_usec; \
138 typedef std::vector<class ProfileTime *> TimeList;
148 ProfileTime(const char *name) :
152 times_.push_back(this);
155 void AddTime(uint64_t time) {
162 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
174 ProfileTimer(ProfileTime &time) :
181 time_.AddTime(_timestamp - start_);
186 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
188 std::cerr << "========" << std::endl;
191 #define _profile(name) { \
192 static ProfileTime name(#name); \
193 ProfileTimer _ ## name(name);
198 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
200 #define CYPoolStart() \
201 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
203 #define CYPoolEnd() \
207 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
209 void NSLogPoint(const char *fix, const CGPoint &point) {
210 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
213 void NSLogRect(const char *fix, const CGRect &rect) {
214 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
217 static _finline NSString *CydiaURL(NSString *path) {
219 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
220 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
221 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
222 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
223 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
224 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
227 static _finline void UpdateExternalStatus(uint64_t newStatus) {
229 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
230 notify_set_state(notify_token, newStatus);
231 notify_cancel(notify_token);
233 notify_post("com.saurik.Cydia.status");
236 /* [NSObject yieldToSelector:(withObject:)] {{{*/
237 @interface NSObject (Cydia)
238 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
239 - (id) yieldToSelector:(SEL)selector;
242 @implementation NSObject (Cydia)
247 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
248 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
249 id object([[context objectAtIndex:1] nonretainedObjectValue]);
250 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
252 /* XXX: deal with exceptions */
253 id value([self performSelector:selector withObject:object]);
255 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
256 [context removeAllObjects];
257 if ([signature methodReturnLength] != 0 && value != nil)
258 [context addObject:value];
263 performSelectorOnMainThread:@selector(doNothing)
269 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
270 /*return [self performSelector:selector withObject:object];*/
272 volatile bool stopped(false);
274 NSMutableArray *context([NSMutableArray arrayWithObjects:
275 [NSValue valueWithPointer:selector],
276 [NSValue valueWithNonretainedObject:object],
277 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
280 NSThread *thread([[[NSThread alloc]
282 selector:@selector(_yieldToContext:)
288 NSRunLoop *loop([NSRunLoop currentRunLoop]);
289 NSDate *future([NSDate distantFuture]);
291 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
293 return [context count] == 0 ? nil : [context objectAtIndex:0];
296 - (id) yieldToSelector:(SEL)selector {
297 return [self yieldToSelector:selector withObject:nil];
303 /* Cydia Action Sheet {{{ */
304 @interface CYActionSheet : UIAlertView {
308 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
311 @implementation CYActionSheet
313 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
314 if ((self = [super init])) {
315 [self setTitle:title];
316 [self setDelegate:self];
317 for (NSString *button in buttons) [self addButtonWithTitle:button];
318 [self setCancelButtonIndex:index];
322 - (void) _updateFrameForDisplay {
323 [super _updateFrameForDisplay];
324 if ([self cancelButtonIndex] == -1) {
325 NSArray *buttons = [self buttons];
326 if ([buttons count]) {
327 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
328 for (UIThreePartButton *button in buttons)
329 [button setBackground:background forState:0];
334 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
335 button_ = buttonIndex + 1;
339 [self dismissWithClickedButtonIndex:-1 animated:YES];
342 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
343 [self setRunsModal:YES];
352 /* NSForcedOrderingSearch doesn't work on the iPhone */
353 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
354 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
355 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
357 /* Information Dictionaries {{{ */
358 @interface NSMutableArray (Cydia)
359 - (void) addInfoDictionary:(NSDictionary *)info;
362 @implementation NSMutableArray (Cydia)
364 - (void) addInfoDictionary:(NSDictionary *)info {
365 [self addObject:info];
370 @interface NSMutableDictionary (Cydia)
371 - (void) addInfoDictionary:(NSDictionary *)info;
374 @implementation NSMutableDictionary (Cydia)
376 - (void) addInfoDictionary:(NSDictionary *)info {
377 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
383 #define lprintf(args...) fprintf(stderr, args)
386 #define TraceLogging (1 && !ForRelease)
387 #define HistogramInsertionSort (0 && !ForRelease)
388 #define ProfileTimes (0 && !ForRelease)
389 #define ForSaurik (0 && !ForRelease)
390 #define LogBrowser (0 && !ForRelease)
391 #define TrackResize (0 && !ForRelease)
392 #define ManualRefresh (1 && !ForRelease)
393 #define ShowInternals (0 && !ForRelease)
394 #define IgnoreInstall (0 && !ForRelease)
395 #define AlwaysReload (0 && !ForRelease)
399 #define _trace(args...)
404 #define _profile(name) {
407 #define PrintTimes() do {} while (false)
411 typedef uint32_t (*SKRadixFunction)(id, void *);
413 @interface NSMutableArray (Radix)
414 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
415 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
423 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
424 struct RadixItem_ *lhs(swap), *rhs(swap + count);
426 static const size_t width = 32;
427 static const size_t bits = 11;
428 static const size_t slots = 1 << bits;
429 static const size_t passes = (width + (bits - 1)) / bits;
431 size_t *hist(new size_t[slots]);
433 for (size_t pass(0); pass != passes; ++pass) {
434 memset(hist, 0, sizeof(size_t) * slots);
436 for (size_t i(0); i != count; ++i) {
437 uint32_t key(lhs[i].key);
439 key &= _not(uint32_t) >> width - bits;
444 for (size_t i(0); i != slots; ++i) {
445 size_t local(offset);
450 for (size_t i(0); i != count; ++i) {
451 uint32_t key(lhs[i].key);
453 key &= _not(uint32_t) >> width - bits;
454 rhs[hist[key]++] = lhs[i];
457 RadixItem_ *tmp(lhs);
464 const void **values(new const void *[count]);
465 for (size_t i(0); i != count; ++i)
466 values[i] = [self objectAtIndex:lhs[i].index];
467 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
473 @implementation NSMutableArray (Radix)
475 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
476 size_t count([self count]);
481 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
482 [invocation setSelector:selector];
483 [invocation setArgument:&object atIndex:2];
485 /* XXX: this is an unsafe optimization of doomy hell */
486 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
487 _assert(method != NULL);
488 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
489 _assert(imp != NULL);
492 struct RadixItem_ *swap(new RadixItem_[count * 2]);
494 for (size_t i(0); i != count; ++i) {
495 RadixItem_ &item(swap[i]);
498 id object([self objectAtIndex:i]);
501 [invocation setTarget:object];
503 [invocation getReturnValue:&item.key];
505 item.key = imp(object, selector, object);
509 RadixSort_(self, count, swap);
512 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
513 size_t count([self count]);
514 struct RadixItem_ *swap(new RadixItem_[count * 2]);
516 for (size_t i(0); i != count; ++i) {
517 RadixItem_ &item(swap[i]);
520 id object([self objectAtIndex:i]);
521 item.key = function(object, argument);
524 RadixSort_(self, count, swap);
529 /* Insertion Sort {{{ */
531 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
532 const char *ptr = (const char *)list;
534 CFIndex half = count / 2;
535 const char *probe = ptr + elementSize * half;
536 CFComparisonResult cr = comparator(element, probe, context);
537 if (0 == cr) return (probe - (const char *)list) / elementSize;
538 ptr = (cr < 0) ? ptr : probe + elementSize;
539 count = (cr < 0) ? half : (half + (count & 1) - 1);
541 return (ptr - (const char *)list) / elementSize;
544 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
545 const char *ptr = (const char *)list;
547 CFIndex half = count / 2;
548 const char *probe = ptr + elementSize * half;
549 CFComparisonResult cr = comparator(element, probe, context);
550 if (0 == cr) return (probe - (const char *)list) / elementSize;
551 ptr = (cr < 0) ? ptr : probe + elementSize;
552 count = (cr < 0) ? half : (half + (count & 1) - 1);
554 return (ptr - (const char *)list) / elementSize;
557 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
558 if (range.length == 0)
560 const void **values(new const void *[range.length]);
561 CFArrayGetValues(array, range, values);
563 #if HistogramInsertionSort
564 uint32_t total(0), *offsets(new uint32_t[range.length]);
567 for (CFIndex index(1); index != range.length; ++index) {
568 const void *value(values[index]);
569 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
570 CFIndex correct(index);
571 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
574 if (correct != index) {
575 size_t offset(index - correct);
576 #if HistogramInsertionSort
580 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
582 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
583 values[correct] = value;
587 CFArrayReplaceValues(array, range, values, range.length);
590 #if HistogramInsertionSort
591 for (CFIndex index(0); index != range.length; ++index)
592 if (offsets[index] != 0)
593 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
594 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
601 /* Apple Bug Fixes {{{ */
602 @implementation UIWebDocumentView (Cydia)
604 - (void) _setScrollerOffset:(CGPoint)offset {
605 UIScroller *scroller([self _scroller]);
607 CGSize size([scroller contentSize]);
608 CGSize bounds([scroller bounds].size);
611 max.x = size.width - bounds.width;
612 max.y = size.height - bounds.height;
620 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
621 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
623 [scroller setOffset:offset];
629 @implementation WebScriptObject (NSFastEnumeration)
631 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
632 size_t length([self count] - state->state);
635 else if (length > count)
637 for (size_t i(0); i != length; ++i)
638 objects[i] = [self objectAtIndex:state->state++];
639 state->itemsPtr = objects;
640 state->mutationsPtr = (unsigned long *) self;
646 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
647 size_t length([self length] - state->state);
650 else if (length > count)
652 for (size_t i(0); i != length; ++i)
653 objects[i] = [self item:state->state++];
654 state->itemsPtr = objects;
655 state->mutationsPtr = (unsigned long *) self;
659 /* Cydia NSString Additions {{{ */
660 @interface NSString (Cydia)
661 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
662 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
663 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
664 - (NSComparisonResult) compareByPath:(NSString *)other;
665 - (NSString *) stringByCachingURLWithCurrentCDN;
666 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
669 @implementation NSString (Cydia)
671 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
672 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
675 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
676 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
677 memcpy(data, bytes, length);
678 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
681 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
682 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
685 - (NSComparisonResult) compareByPath:(NSString *)other {
686 NSString *prefix = [self commonPrefixWithString:other options:0];
687 size_t length = [prefix length];
689 NSRange lrange = NSMakeRange(length, [self length] - length);
690 NSRange rrange = NSMakeRange(length, [other length] - length);
692 lrange = [self rangeOfString:@"/" options:0 range:lrange];
693 rrange = [other rangeOfString:@"/" options:0 range:rrange];
695 NSComparisonResult value;
697 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
698 value = NSOrderedSame;
699 else if (lrange.location == NSNotFound)
700 value = NSOrderedAscending;
701 else if (rrange.location == NSNotFound)
702 value = NSOrderedDescending;
704 value = NSOrderedSame;
706 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
707 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
708 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
709 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
711 NSComparisonResult result = [lpath compare:rpath];
712 return result == NSOrderedSame ? value : result;
715 - (NSString *) stringByCachingURLWithCurrentCDN {
717 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
718 withString:@"://cache.cydia.saurik.com/"
722 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
723 return [(id)CFURLCreateStringByAddingPercentEscapes(
728 kCFStringEncodingUTF8
735 /* C++ NSString Wrapper Cache {{{ */
742 _finline void clear_() {
743 if (cache_ != NULL) {
750 _finline bool empty() const {
754 _finline size_t size() const {
758 _finline char *data() const {
762 _finline void clear() {
767 _finline CYString() :
774 _finline ~CYString() {
778 void operator =(const CYString &rhs) {
782 if (rhs.cache_ == nil)
785 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
788 void set(apr_pool_t *pool, const char *data, size_t size) {
794 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
795 memcpy(temp, data, size);
802 _finline void set(apr_pool_t *pool, const char *data) {
803 set(pool, data, data == NULL ? 0 : strlen(data));
806 _finline void set(apr_pool_t *pool, const std::string &rhs) {
807 set(pool, rhs.data(), rhs.size());
810 bool operator ==(const CYString &rhs) const {
811 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
814 operator CFStringRef() {
815 if (cache_ == NULL) {
818 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
820 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
824 _finline operator id() {
825 return (NSString *) static_cast<CFStringRef>(*this);
829 /* C++ NSString Algorithm Adapters {{{ */
831 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
834 struct NSStringMapHash :
835 std::unary_function<NSString *, size_t>
837 _finline size_t operator ()(NSString *value) const {
838 return CFStringHashNSString((CFStringRef) value);
842 struct NSStringMapLess :
843 std::binary_function<NSString *, NSString *, bool>
845 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
846 return [lhs compare:rhs] == NSOrderedAscending;
850 struct NSStringMapEqual :
851 std::binary_function<NSString *, NSString *, bool>
853 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
854 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
855 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
856 //[lhs isEqualToString:rhs];
861 /* Perl-Compatible RegEx {{{ */
871 Pcre(const char *regex) :
876 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
879 lprintf("%d:%s\n", offset, error);
883 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
884 matches_ = new int[(capture_ + 1) * 3];
892 NSString *operator [](size_t match) {
893 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
896 bool operator ()(NSString *data) {
897 // XXX: length is for characters, not for bytes
898 return operator ()([data UTF8String], [data length]);
901 bool operator ()(const char *data, size_t size) {
903 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
907 /* Mime Addresses {{{ */
908 @interface Address : NSObject {
914 - (NSString *) address;
916 - (void) setAddress:(NSString *)address;
918 + (Address *) addressWithString:(NSString *)string;
919 - (Address *) initWithString:(NSString *)string;
922 @implementation Address
931 - (NSString *) name {
935 - (NSString *) address {
939 - (void) setAddress:(NSString *)address {
941 [address_ autorelease];
945 address_ = [address retain];
948 + (Address *) addressWithString:(NSString *)string {
949 return [[[Address alloc] initWithString:string] autorelease];
952 + (NSArray *) _attributeKeys {
953 return [NSArray arrayWithObjects:@"address", @"name", nil];
956 - (NSArray *) attributeKeys {
957 return [[self class] _attributeKeys];
960 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
961 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
964 - (Address *) initWithString:(NSString *)string {
965 if ((self = [super init]) != nil) {
966 const char *data = [string UTF8String];
967 size_t size = [string length];
969 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
971 if (address_r(data, size)) {
972 name_ = [address_r[1] retain];
973 address_ = [address_r[2] retain];
975 name_ = [string retain];
983 /* CoreGraphics Primitives {{{ */
994 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
997 Set(space, red, green, blue, alpha);
1002 CGColorRelease(color_);
1009 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1011 float color[] = {red, green, blue, alpha};
1012 color_ = CGColorCreate(space, (CGFloat *) color);
1015 operator CGColorRef() {
1021 /* Random Global Variables {{{ */
1022 static const int PulseInterval_ = 50000;
1023 static const int ButtonBarWidth_ = 60;
1024 static const int ButtonBarHeight_ = 48;
1025 static const float KeyboardTime_ = 0.3f;
1028 static NSArray *Finishes_;
1030 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1031 #define NotifyConfig_ "/etc/notify.conf"
1033 static bool Queuing_;
1035 static CYColor Blue_;
1036 static CYColor Blueish_;
1037 static CYColor Black_;
1038 static CYColor Off_;
1039 static CYColor White_;
1040 static CYColor Gray_;
1041 static CYColor Green_;
1042 static CYColor Purple_;
1043 static CYColor Purplish_;
1045 static UIColor *InstallingColor_;
1046 static UIColor *RemovingColor_;
1048 static NSString *App_;
1049 static NSString *Home_;
1051 static BOOL Advanced_;
1052 static BOOL Ignored_;
1054 static UIFont *Font12_;
1055 static UIFont *Font12Bold_;
1056 static UIFont *Font14_;
1057 static UIFont *Font18Bold_;
1058 static UIFont *Font22Bold_;
1060 static const char *Machine_ = NULL;
1061 static NSString *System_ = nil;
1062 static NSString *SerialNumber_ = nil;
1063 static NSString *ChipID_ = nil;
1064 static NSString *Token_ = nil;
1065 static NSString *UniqueID_ = nil;
1066 static NSString *PLMN_ = nil;
1067 static NSString *Build_ = nil;
1068 static NSString *Product_ = nil;
1069 static NSString *Safari_ = nil;
1071 static CFLocaleRef Locale_;
1072 static NSArray *Languages_;
1073 static CGColorSpaceRef space_;
1075 static NSDictionary *SectionMap_;
1076 static NSMutableDictionary *Metadata_;
1077 static _transient NSMutableDictionary *Settings_;
1078 static _transient NSString *Role_;
1079 static _transient NSMutableDictionary *Packages_;
1080 static _transient NSMutableDictionary *Sections_;
1081 static _transient NSMutableDictionary *Sources_;
1082 static bool Changed_;
1083 static NSDate *now_;
1085 static bool IsWildcat_;
1088 /* Display Helpers {{{ */
1089 inline float Interpolate(float begin, float end, float fraction) {
1090 return (end - begin) * fraction + begin;
1093 /* XXX: localize this! */
1094 NSString *SizeString(double size) {
1095 bool negative = size < 0;
1100 while (size > 1024) {
1105 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1107 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1110 static _finline CFStringRef CFCString(const char *value) {
1111 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1114 const char *StripVersion_(const char *version) {
1115 const char *colon(strchr(version, ':'));
1117 version = colon + 1;
1121 CFStringRef StripVersion(const char *version) {
1122 const char *colon(strchr(version, ':'));
1124 version = colon + 1;
1125 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1127 return CFCString(version);
1130 NSString *LocalizeSection(NSString *section) {
1131 static Pcre title_r("^(.*?) \\((.*)\\)$");
1132 if (title_r(section)) {
1133 NSString *parent(title_r[1]);
1134 NSString *child(title_r[2]);
1136 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1137 LocalizeSection(parent),
1138 LocalizeSection(child)
1142 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1145 NSString *Simplify(NSString *title) {
1146 const char *data = [title UTF8String];
1147 size_t size = [title length];
1149 static Pcre square_r("^\\[(.*)\\]$");
1150 if (square_r(data, size))
1151 return Simplify(square_r[1]);
1153 static Pcre paren_r("^\\((.*)\\)$");
1154 if (paren_r(data, size))
1155 return Simplify(paren_r[1]);
1157 static Pcre title_r("^(.*?) \\((.*)\\)$");
1158 if (title_r(data, size))
1159 return Simplify(title_r[1]);
1165 NSString *GetLastUpdate() {
1166 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1169 return UCLocalize("NEVER_OR_UNKNOWN");
1171 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1172 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1174 CFRelease(formatter);
1176 return [(NSString *) formatted autorelease];
1179 bool isSectionVisible(NSString *section) {
1180 NSDictionary *metadata([Sections_ objectForKey:section]);
1181 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1182 return hidden == nil || ![hidden boolValue];
1187 /* Delegate Prototypes {{{ */
1191 @interface NSObject (ProgressDelegate)
1194 @protocol ProgressDelegate
1195 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1196 - (void) setProgressTitle:(NSString *)title;
1197 - (void) setProgressPercent:(float)percent;
1198 - (void) startProgress;
1199 - (void) addProgressOutput:(NSString *)output;
1200 - (bool) isCancelling:(size_t)received;
1203 @protocol ConfigurationDelegate
1204 - (void) repairWithSelector:(SEL)selector;
1205 - (void) setConfigurationData:(NSString *)data;
1208 @class PackageController;
1210 @protocol CydiaDelegate
1211 - (void) setPackageController:(PackageController *)view;
1212 - (void) clearPackage:(Package *)package;
1213 - (void) installPackage:(Package *)package;
1214 - (void) installPackages:(NSArray *)packages;
1215 - (void) removePackage:(Package *)package;
1216 - (void) beginUpdate;
1218 - (void) distUpgrade;
1220 - (void) updateData;
1222 - (void) showSettings;
1223 - (UIProgressHUD *) addProgressHUD;
1224 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1225 - (CYViewController *) pageForPackage:(NSString *)name;
1226 - (PackageController *) packageController;
1227 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1231 /* Status Delegation {{{ */
1233 public pkgAcquireStatus
1236 _transient NSObject<ProgressDelegate> *delegate_;
1244 void setDelegate(id delegate) {
1245 delegate_ = delegate;
1248 NSObject<ProgressDelegate> *getDelegate() const {
1252 virtual bool MediaChange(std::string media, std::string drive) {
1256 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1259 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1260 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1261 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1264 virtual void Done(pkgAcquire::ItemDesc &item) {
1267 virtual void Fail(pkgAcquire::ItemDesc &item) {
1269 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1270 item.Owner->Status == pkgAcquire::Item::StatDone
1274 std::string &error(item.Owner->ErrorText);
1278 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1279 NSArray *fields([description componentsSeparatedByString:@" "]);
1280 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1282 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1283 withObject:[NSArray arrayWithObjects:
1284 [NSString stringWithUTF8String:error.c_str()],
1291 virtual bool Pulse(pkgAcquire *Owner) {
1292 bool value = pkgAcquireStatus::Pulse(Owner);
1295 double(CurrentBytes + CurrentItems) /
1296 double(TotalBytes + TotalItems)
1299 [delegate_ setProgressPercent:percent];
1300 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1303 virtual void Start() {
1304 [delegate_ startProgress];
1307 virtual void Stop() {
1311 /* Progress Delegation {{{ */
1316 _transient id<ProgressDelegate> delegate_;
1320 virtual void Update() {
1321 /*if (abs(Percent - percent_) > 2)
1322 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1326 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1327 [delegate_ setProgressPercent:(Percent / 100)];*/
1337 void setDelegate(id delegate) {
1338 delegate_ = delegate;
1341 id getDelegate() const {
1345 virtual void Done() {
1347 //[delegate_ setProgressPercent:1];
1352 /* Database Interface {{{ */
1353 typedef std::map< unsigned long, _H<Source> > SourceMap;
1355 @interface Database : NSObject {
1361 pkgCacheFile cache_;
1362 pkgDepCache::Policy *policy_;
1363 pkgRecords *records_;
1364 pkgProblemResolver *resolver_;
1365 pkgAcquire *fetcher_;
1367 SPtr<pkgPackageManager> manager_;
1368 pkgSourceList *list_;
1371 NSMutableArray *packages_;
1373 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1382 + (Database *) sharedInstance;
1385 - (void) _readCydia:(NSNumber *)fd;
1386 - (void) _readStatus:(NSNumber *)fd;
1387 - (void) _readOutput:(NSNumber *)fd;
1391 - (Package *) packageWithName:(NSString *)name;
1393 - (pkgCacheFile &) cache;
1394 - (pkgDepCache::Policy *) policy;
1395 - (pkgRecords *) records;
1396 - (pkgProblemResolver *) resolver;
1397 - (pkgAcquire &) fetcher;
1398 - (pkgSourceList &) list;
1399 - (NSArray *) packages;
1400 - (NSArray *) sources;
1401 - (void) reloadData;
1409 - (void) setVisible;
1411 - (void) updateWithStatus:(Status &)status;
1413 - (void) setDelegate:(id)delegate;
1414 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1417 /* Delegate Helpers {{{ */
1418 @implementation NSObject (ProgressDelegate)
1420 - (void) _setProgressErrorPackage:(NSArray *)args {
1421 [self performSelector:@selector(setProgressError:forPackage:)
1422 withObject:[args objectAtIndex:0]
1423 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1427 - (void) _setProgressErrorTitle:(NSArray *)args {
1428 [self performSelector:@selector(setProgressError:withTitle:)
1429 withObject:[args objectAtIndex:0]
1430 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1434 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1435 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1436 withObject:[NSArray arrayWithObjects:error, title, nil]
1441 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1442 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1444 [self performSelector:@selector(setProgressError:withTitle:)
1446 withObject:(package == nil ? id : [package name])
1453 /* Source Class {{{ */
1454 @interface Source : NSObject {
1455 CYString depiction_;
1456 CYString description_;
1462 CYString distribution_;
1467 NSString *authority_;
1469 CYString defaultIcon_;
1471 NSDictionary *record_;
1475 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1477 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1479 - (NSString *) depictionForPackage:(NSString *)package;
1480 - (NSString *) supportForPackage:(NSString *)package;
1482 - (NSDictionary *) record;
1486 - (NSString *) distribution;
1487 - (NSString *) type;
1489 - (NSString *) host;
1491 - (NSString *) name;
1492 - (NSString *) description;
1493 - (NSString *) label;
1494 - (NSString *) origin;
1495 - (NSString *) version;
1497 - (NSString *) defaultIcon;
1501 @implementation Source
1505 distribution_.clear();
1508 description_.clear();
1514 defaultIcon_.clear();
1516 if (record_ != nil) {
1526 if (authority_ != nil) {
1527 [authority_ release];
1537 + (NSArray *) _attributeKeys {
1538 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1541 - (NSArray *) attributeKeys {
1542 return [[self class] _attributeKeys];
1545 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1546 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1549 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1552 trusted_ = index->IsTrusted();
1554 uri_.set(pool, index->GetURI());
1555 distribution_.set(pool, index->GetDist());
1556 type_.set(pool, index->GetType());
1558 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1559 if (dindex != NULL) {
1561 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1564 pkgTagFile tags(&fd);
1566 pkgTagSection section;
1573 {"default-icon", &defaultIcon_},
1574 {"depiction", &depiction_},
1575 {"description", &description_},
1577 {"origin", &origin_},
1578 {"support", &support_},
1579 {"version", &version_},
1582 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1583 const char *start, *end;
1585 if (section.Find(names[i].name_, start, end)) {
1586 CYString &value(*names[i].value_);
1587 value.set(pool, start, end - start);
1593 record_ = [Sources_ objectForKey:[self key]];
1595 record_ = [record_ retain];
1597 NSURL *url([NSURL URLWithString:uri_]);
1601 host_ = [[host_ lowercaseString] retain];
1606 authority_ = [url path];
1608 if (authority_ != nil)
1609 authority_ = [authority_ retain];
1612 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1613 if ((self = [super init]) != nil) {
1614 [self setMetaIndex:index inPool:pool];
1618 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1619 NSDictionary *lhr = [self record];
1620 NSDictionary *rhr = [source record];
1623 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1625 NSString *lhs = [self name];
1626 NSString *rhs = [source name];
1628 if ([lhs length] != 0 && [rhs length] != 0) {
1629 unichar lhc = [lhs characterAtIndex:0];
1630 unichar rhc = [rhs characterAtIndex:0];
1632 if (isalpha(lhc) && !isalpha(rhc))
1633 return NSOrderedAscending;
1634 else if (!isalpha(lhc) && isalpha(rhc))
1635 return NSOrderedDescending;
1638 return [lhs compare:rhs options:LaxCompareOptions_];
1641 - (NSString *) depictionForPackage:(NSString *)package {
1642 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1645 - (NSString *) supportForPackage:(NSString *)package {
1646 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1649 - (NSDictionary *) record {
1657 - (NSString *) uri {
1661 - (NSString *) distribution {
1662 return distribution_;
1665 - (NSString *) type {
1669 - (NSString *) key {
1670 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1673 - (NSString *) host {
1677 - (NSString *) name {
1678 return origin_.empty() ? authority_ : origin_;
1681 - (NSString *) description {
1682 return description_;
1685 - (NSString *) label {
1686 return label_.empty() ? authority_ : label_;
1689 - (NSString *) origin {
1693 - (NSString *) version {
1697 - (NSString *) defaultIcon {
1698 return defaultIcon_;
1703 /* Relationship Class {{{ */
1704 @interface Relationship : NSObject {
1709 - (NSString *) type;
1711 - (NSString *) name;
1715 @implementation Relationship
1723 - (NSString *) type {
1731 - (NSString *) name {
1738 /* Package Class {{{ */
1739 @interface Package : NSObject {
1743 pkgCache::VerIterator version_;
1744 pkgCache::PkgIterator iterator_;
1745 _transient Database *database_;
1746 pkgCache::VerFileIterator file_;
1753 NSString *section$_;
1760 CYString installed_;
1766 CYString depiction_;
1777 NSMutableArray *tags_;
1780 NSArray *relationships_;
1782 NSMutableDictionary *metadata_;
1783 _transient NSDate *firstSeen_;
1784 _transient NSDate *lastSeen_;
1788 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1789 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1791 - (pkgCache::PkgIterator) iterator;
1794 - (NSString *) section;
1795 - (NSString *) simpleSection;
1797 - (NSString *) longSection;
1798 - (NSString *) shortSection;
1802 - (Address *) maintainer;
1804 - (NSString *) longDescription;
1805 - (NSString *) shortDescription;
1808 - (NSMutableDictionary *) metadata;
1810 - (BOOL) subscribed;
1813 - (NSString *) latest;
1814 - (NSString *) installed;
1815 - (BOOL) uninstalled;
1818 - (BOOL) upgradableAndEssential:(BOOL)essential;
1821 - (BOOL) unfiltered;
1825 - (BOOL) halfConfigured;
1826 - (BOOL) halfInstalled;
1828 - (NSString *) mode;
1830 - (void) setVisible;
1833 - (NSString *) name;
1835 - (NSString *) homepage;
1836 - (NSString *) depiction;
1837 - (Address *) author;
1839 - (NSString *) support;
1841 - (NSArray *) files;
1842 - (NSArray *) relationships;
1843 - (NSArray *) warnings;
1844 - (NSArray *) applications;
1846 - (Source *) source;
1847 - (NSString *) role;
1849 - (BOOL) matches:(NSString *)text;
1851 - (bool) hasSupportingRole;
1852 - (BOOL) hasTag:(NSString *)tag;
1853 - (NSString *) primaryPurpose;
1854 - (NSArray *) purposes;
1855 - (bool) isCommercial;
1857 - (CYString &) cyname;
1859 - (uint32_t) compareBySection:(NSArray *)sections;
1861 - (uint32_t) compareForChanges;
1866 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1867 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1868 - (bool) isInstalledAndVisible:(NSNumber *)number;
1869 - (bool) isVisibleInSection:(NSString *)section;
1870 - (bool) isVisibleInSource:(Source *)source;
1874 uint32_t PackageChangesRadix(Package *self, void *) {
1879 uint32_t timestamp : 30;
1880 uint32_t ignored : 1;
1881 uint32_t upgradable : 1;
1885 bool upgradable([self upgradableAndEssential:YES]);
1886 value.bits.upgradable = upgradable ? 1 : 0;
1889 value.bits.timestamp = 0;
1890 value.bits.ignored = [self ignored] ? 0 : 1;
1891 value.bits.upgradable = 1;
1893 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1894 value.bits.ignored = 0;
1895 value.bits.upgradable = 0;
1898 return _not(uint32_t) - value.key;
1901 _finline static void Stifle(uint8_t &value) {
1904 uint32_t PackagePrefixRadix(Package *self, void *context) {
1905 size_t offset(reinterpret_cast<size_t>(context));
1906 CYString &name([self cyname]);
1908 size_t size(name.size());
1911 char *text(name.data());
1914 if (!isdigit(text[0]))
1918 while (size != digits && isdigit(text[digits]))
1928 if (offset == 0 && zeros != 0) {
1929 memset(data, '0', zeros);
1930 memcpy(data + zeros, text, 4 - zeros);
1932 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1933 if (size <= offset - zeros)
1936 text += offset - zeros;
1937 size -= offset - zeros;
1940 memcpy(data, text, 4);
1942 memcpy(data, text, size);
1943 memset(data + size, 0, 4 - size);
1946 for (size_t i(0); i != 4; ++i)
1947 if (isalpha(data[i]))
1952 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1954 /* XXX: ntohl may be more honest */
1955 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1958 CYString &(*PackageName)(Package *self, SEL sel);
1960 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1961 _profile(PackageNameCompare)
1962 CYString &lhi(PackageName(lhs, @selector(cyname)));
1963 CYString &rhi(PackageName(rhs, @selector(cyname)));
1964 CFStringRef lhn(lhi), rhn(rhi);
1967 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1968 else if (rhn == NULL)
1969 return NSOrderedDescending;
1971 _profile(PackageNameCompare$NumbersLast)
1972 if (!lhi.empty() && !rhi.empty()) {
1973 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1974 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1975 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1976 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1977 return lha ? NSOrderedAscending : NSOrderedDescending;
1981 CFIndex length = CFStringGetLength(lhn);
1983 _profile(PackageNameCompare$Compare)
1984 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1989 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1990 return PackageNameCompare(*lhs, *rhs, context);
1993 struct PackageNameOrdering :
1994 std::binary_function<Package *, Package *, bool>
1996 _finline bool operator ()(Package *lhs, Package *rhs) const {
1997 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2001 @implementation Package
2003 - (NSString *) description {
2004 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2010 if (section$_ != nil)
2011 [section$_ release];
2016 if (sponsor$_ != nil)
2017 [sponsor$_ release];
2018 if (author$_ != nil)
2025 if (relationships_ != nil)
2026 [relationships_ release];
2027 if (metadata_ != nil)
2028 [metadata_ release];
2033 + (NSString *) webScriptNameForSelector:(SEL)selector {
2034 if (selector == @selector(hasTag:))
2040 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2041 return [self webScriptNameForSelector:selector] == nil;
2044 + (NSArray *) _attributeKeys {
2045 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];
2048 - (NSArray *) attributeKeys {
2049 return [[self class] _attributeKeys];
2052 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2053 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2063 _profile(Package$parse)
2064 pkgRecords::Parser *parser;
2066 _profile(Package$parse$Lookup)
2067 parser = &[database_ records]->Lookup(file_);
2072 _profile(Package$parse$Find)
2078 {"depiction", &depiction_},
2079 {"homepage", &homepage_},
2080 {"website", &website},
2082 {"support", &support_},
2083 {"sponsor", &sponsor_},
2084 {"author", &author_},
2087 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2088 const char *start, *end;
2090 if (parser->Find(names[i].name_, start, end)) {
2091 CYString &value(*names[i].value_);
2092 _profile(Package$parse$Value)
2093 value.set(pool_, start, end - start);
2099 _profile(Package$parse$Tagline)
2100 const char *start, *end;
2101 if (parser->ShortDesc(start, end)) {
2102 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2105 while (stop != start && stop[-1] == '\r')
2107 tagline_.set(pool_, start, stop - start);
2111 _profile(Package$parse$Retain)
2112 if (homepage_.empty())
2113 homepage_ = website;
2114 if (homepage_ == depiction_)
2120 - (void) setVisible {
2121 visible_ = required_ && [self unfiltered];
2124 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2125 if ((self = [super init]) != nil) {
2126 _profile(Package$initWithVersion)
2127 era_ = [database era];
2131 iterator_ = version.ParentPkg();
2132 database_ = database;
2134 _profile(Package$initWithVersion$Latest)
2135 latest_ = (NSString *) StripVersion(version_.VerStr());
2138 pkgCache::VerIterator current;
2139 _profile(Package$initWithVersion$Versions)
2140 current = iterator_.CurrentVer();
2142 installed_.set(pool_, StripVersion_(current.VerStr()));
2144 if (!version_.end())
2145 file_ = version_.FileList();
2147 pkgCache &cache([database_ cache]);
2148 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2152 _profile(Package$initWithVersion$Name)
2153 id_.set(pool_, iterator_.Name());
2154 name_.set(pool, iterator_.Display());
2157 _profile(Package$lowercaseString)
2158 char *data(id_.data());
2159 for (size_t i(0), e(id_.size()); i != e; ++i)
2160 // XXX: do not use tolower() as this is not locale-specific? :(
2165 _profile(Package$initWithVersion$Source)
2166 source_ = [database_ getSource:file_.File()];
2175 _profile(Package$initWithVersion$Tags)
2176 pkgCache::TagIterator tag(iterator_.TagList());
2178 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2180 const char *name(tag.Name());
2181 [tags_ addObject:(NSString *)CFCString(name)];
2182 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2183 role_ = (NSString *) CFCString(name + 6);
2184 if (required_ && strncmp(name, "require::", 9) == 0 && (
2189 } while (!tag.end());
2193 bool changed(false);
2195 _profile(Package$initWithVersion$Metadata)
2196 metadata_ = [Packages_ objectForKey:id_];
2198 if (metadata_ == nil) {
2201 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2202 firstSeen_, @"FirstSeen",
2203 latest_, @"LastVersion",
2208 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2209 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2211 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2212 subscribed_ = [subscribed boolValue];
2214 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2216 if (firstSeen_ == nil) {
2217 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2218 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2222 if (version == nil) {
2223 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2225 } else if (![version isEqualToString:latest_]) {
2226 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2228 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2233 metadata_ = [metadata_ retain];
2236 [Packages_ setObject:metadata_ forKey:id_];
2241 _profile(Package$initWithVersion$Section)
2242 section_.set(pool_, iterator_.Section());
2245 obsolete_ = [self hasTag:@"cydia::obsolete"];
2246 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2251 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2252 pkgCache::VerIterator version;
2254 _profile(Package$packageWithIterator$GetCandidateVer)
2255 version = [database policy]->GetCandidateVer(iterator);
2261 return [[[Package alloc]
2262 initWithVersion:version
2269 - (pkgCache::PkgIterator) iterator {
2273 - (NSString *) section {
2274 if (section$_ == nil) {
2275 if (section_.empty())
2278 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2279 NSString *name(section_);
2282 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2283 if (NSString *rename = [value objectForKey:@"Rename"]) {
2288 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2292 - (NSString *) simpleSection {
2293 if (NSString *section = [self section])
2294 return Simplify(section);
2299 - (NSString *) longSection {
2300 return LocalizeSection([self section]);
2303 - (NSString *) shortSection {
2304 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2307 - (NSString *) uri {
2310 pkgIndexFile *index;
2311 pkgCache::PkgFileIterator file(file_.File());
2312 if (![database_ list].FindIndex(file, index))
2314 return [NSString stringWithUTF8String:iterator_->Path];
2315 //return [NSString stringWithUTF8String:file.Site()];
2316 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2320 - (Address *) maintainer {
2323 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2324 const std::string &maintainer(parser->Maintainer());
2325 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2329 return version_.end() ? 0 : version_->InstalledSize;
2332 - (NSString *) longDescription {
2333 @synchronized (database_) {
2334 if ([database_ era] != era_ || file_.end())
2337 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2338 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2340 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2341 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2342 if ([lines count] < 2)
2345 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2346 for (size_t i(1), e([lines count]); i != e; ++i) {
2347 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2348 [trimmed addObject:trim];
2351 return [trimmed componentsJoinedByString:@"\n"];
2354 - (NSString *) shortDescription {
2359 _profile(Package$index)
2360 CFStringRef name((CFStringRef) [self name]);
2361 if (CFStringGetLength(name) == 0)
2363 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2364 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2366 return toupper(character);
2370 - (NSMutableDictionary *) metadata {
2375 if (subscribed_ && lastSeen_ != nil)
2380 - (BOOL) subscribed {
2385 NSDictionary *metadata([self metadata]);
2386 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2387 return [ignored boolValue];
2392 - (NSString *) latest {
2396 - (NSString *) installed {
2400 - (BOOL) uninstalled {
2401 return installed_.empty();
2405 return !version_.end();
2408 - (BOOL) upgradableAndEssential:(BOOL)essential {
2409 _profile(Package$upgradableAndEssential)
2410 pkgCache::VerIterator current(iterator_.CurrentVer());
2412 return essential && essential_ && visible_;
2414 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2418 - (BOOL) essential {
2423 return [database_ cache][iterator_].InstBroken();
2426 - (BOOL) unfiltered {
2427 NSString *section([self section]);
2428 return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
2436 unsigned char current(iterator_->CurrentState);
2437 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2440 - (BOOL) halfConfigured {
2441 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2444 - (BOOL) halfInstalled {
2445 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2449 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2450 return state.Mode != pkgDepCache::ModeKeep;
2453 - (NSString *) mode {
2454 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2456 switch (state.Mode) {
2457 case pkgDepCache::ModeDelete:
2458 if ((state.iFlags & pkgDepCache::Purge) != 0)
2462 case pkgDepCache::ModeKeep:
2463 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2464 return @"REINSTALL";
2465 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2469 case pkgDepCache::ModeInstall:
2470 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2471 return @"REINSTALL";
2472 else*/ switch (state.Status) {
2474 return @"DOWNGRADE";
2480 return @"NEW_INSTALL";
2491 - (NSString *) name {
2492 return name_.empty() ? id_ : name_;
2495 - (UIImage *) icon {
2496 NSString *section = [self simpleSection];
2500 if ([static_cast<id>(icon_) hasPrefix:@"file:///"])
2501 // XXX: correct escaping
2502 icon = [UIImage imageAtPath:[static_cast<id>(icon_) substringFromIndex:7]];
2503 if (icon == nil) if (section != nil)
2504 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2505 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2506 if ([dicon hasPrefix:@"file:///"])
2507 // XXX: correct escaping
2508 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2510 icon = [UIImage applicationImageNamed:@"unknown.png"];
2514 - (NSString *) homepage {
2518 - (NSString *) depiction {
2519 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2522 - (Address *) sponsor {
2523 if (sponsor$_ == nil) {
2524 if (sponsor_.empty())
2526 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2530 - (Address *) author {
2531 if (author$_ == nil) {
2532 if (author_.empty())
2534 author$_ = [[Address addressWithString:author_] retain];
2538 - (NSString *) support {
2539 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2542 - (NSArray *) files {
2543 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2544 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2547 fin.open([path UTF8String]);
2552 while (std::getline(fin, line))
2553 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2558 - (NSArray *) relationships {
2559 return relationships_;
2562 - (NSArray *) warnings {
2563 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2564 const char *name(iterator_.Name());
2566 size_t length(strlen(name));
2567 if (length < 2) invalid:
2568 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2569 else for (size_t i(0); i != length; ++i)
2571 /* XXX: technically this is not allowed */
2572 (name[i] < 'A' || name[i] > 'Z') &&
2573 (name[i] < 'a' || name[i] > 'z') &&
2574 (name[i] < '0' || name[i] > '9') &&
2575 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2578 if (strcmp(name, "cydia") != 0) {
2581 bool _private = false;
2584 bool repository = [[self section] isEqualToString:@"Repositories"];
2586 if (NSArray *files = [self files])
2587 for (NSString *file in files)
2588 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2590 else if (!user && [file isEqualToString:@"/User"])
2592 else if (!_private && [file isEqualToString:@"/private"])
2594 else if (!stash && [file isEqualToString:@"/var/stash"])
2597 /* XXX: this is not sensitive enough. only some folders are valid. */
2598 if (cydia && !repository)
2599 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2601 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2603 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2605 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2608 return [warnings count] == 0 ? nil : warnings;
2611 - (NSArray *) applications {
2612 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2614 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2616 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2617 if (NSArray *files = [self files])
2618 for (NSString *file in files)
2619 if (application_r(file)) {
2620 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2621 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2622 if ([id isEqualToString:me])
2625 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2627 display = application_r[1];
2629 NSString *bundle([file stringByDeletingLastPathComponent]);
2630 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2631 if (icon == nil || [icon length] == 0)
2633 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2635 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2636 [applications addObject:application];
2638 [application addObject:id];
2639 [application addObject:display];
2640 [application addObject:url];
2643 return [applications count] == 0 ? nil : applications;
2646 - (Source *) source {
2648 @synchronized (database_) {
2649 if ([database_ era] != era_ || file_.end())
2652 source_ = [database_ getSource:file_.File()];
2664 - (NSString *) role {
2668 - (BOOL) matches:(NSString *)text {
2674 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2675 if (range.location != NSNotFound)
2678 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2679 if (range.location != NSNotFound)
2682 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2683 if (range.location != NSNotFound)
2689 - (bool) hasSupportingRole {
2692 if ([role_ isEqualToString:@"enduser"])
2694 if ([Role_ isEqualToString:@"User"])
2696 if ([role_ isEqualToString:@"hacker"])
2698 if ([Role_ isEqualToString:@"Hacker"])
2700 if ([role_ isEqualToString:@"developer"])
2702 if ([Role_ isEqualToString:@"Developer"])
2707 - (BOOL) hasTag:(NSString *)tag {
2708 return tags_ == nil ? NO : [tags_ containsObject:tag];
2711 - (NSString *) primaryPurpose {
2712 for (NSString *tag in tags_)
2713 if ([tag hasPrefix:@"purpose::"])
2714 return [tag substringFromIndex:9];
2718 - (NSArray *) purposes {
2719 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2720 for (NSString *tag in tags_)
2721 if ([tag hasPrefix:@"purpose::"])
2722 [purposes addObject:[tag substringFromIndex:9]];
2723 return [purposes count] == 0 ? nil : purposes;
2726 - (bool) isCommercial {
2727 return [self hasTag:@"cydia::commercial"];
2730 - (CYString &) cyname {
2731 return name_.empty() ? id_ : name_;
2734 - (uint32_t) compareBySection:(NSArray *)sections {
2735 NSString *section([self section]);
2736 for (size_t i(0), e([sections count]); i != e; ++i) {
2737 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2741 return _not(uint32_t);
2744 - (uint32_t) compareForChanges {
2749 uint32_t timestamp : 30;
2750 uint32_t ignored : 1;
2751 uint32_t upgradable : 1;
2755 bool upgradable([self upgradableAndEssential:YES]);
2756 value.bits.upgradable = upgradable ? 1 : 0;
2759 value.bits.timestamp = 0;
2760 value.bits.ignored = [self ignored] ? 0 : 1;
2761 value.bits.upgradable = 1;
2763 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2764 value.bits.ignored = 0;
2765 value.bits.upgradable = 0;
2768 return _not(uint32_t) - value.key;
2772 pkgProblemResolver *resolver = [database_ resolver];
2773 resolver->Clear(iterator_);
2774 resolver->Protect(iterator_);
2778 pkgProblemResolver *resolver = [database_ resolver];
2779 resolver->Clear(iterator_);
2780 resolver->Protect(iterator_);
2781 pkgCacheFile &cache([database_ cache]);
2782 cache->MarkInstall(iterator_, false);
2783 pkgDepCache::StateCache &state((*cache)[iterator_]);
2784 if (!state.Install())
2785 cache->SetReInstall(iterator_, true);
2789 pkgProblemResolver *resolver = [database_ resolver];
2790 resolver->Clear(iterator_);
2791 resolver->Protect(iterator_);
2792 resolver->Remove(iterator_);
2793 [database_ cache]->MarkDelete(iterator_, true);
2796 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2797 _profile(Package$isUnfilteredAndSearchedForBy)
2800 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2801 value &= [self unfiltered];
2804 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2805 value &= [self matches:search];
2812 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2813 if ([search length] == 0)
2816 _profile(Package$isUnfilteredAndSelectedForBy)
2819 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2820 value &= [self unfiltered];
2823 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2824 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2831 - (bool) isInstalledAndVisible:(NSNumber *)number {
2832 return (![number boolValue] || [self visible]) && ![self uninstalled];
2835 - (bool) isVisibleInSection:(NSString *)name {
2836 NSString *section = [self section];
2841 section == nil && [name length] == 0 ||
2842 [name isEqualToString:section]
2846 - (bool) isVisibleInSource:(Source *)source {
2847 return [self source] == source && [self visible];
2852 /* Section Class {{{ */
2853 @interface Section : NSObject {
2858 NSString *localized_;
2861 - (NSComparisonResult) compareByLocalized:(Section *)section;
2862 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2863 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2864 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2865 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2866 - (NSString *) name;
2873 - (void) addToCount;
2875 - (void) setCount:(size_t)count;
2876 - (NSString *) localized;
2880 @implementation Section
2884 if (localized_ != nil)
2885 [localized_ release];
2889 - (NSComparisonResult) compareByLocalized:(Section *)section {
2890 NSString *lhs(localized_);
2891 NSString *rhs([section localized]);
2893 /*if ([lhs length] != 0 && [rhs length] != 0) {
2894 unichar lhc = [lhs characterAtIndex:0];
2895 unichar rhc = [rhs characterAtIndex:0];
2897 if (isalpha(lhc) && !isalpha(rhc))
2898 return NSOrderedAscending;
2899 else if (!isalpha(lhc) && isalpha(rhc))
2900 return NSOrderedDescending;
2903 return [lhs compare:rhs options:LaxCompareOptions_];
2906 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2907 if ((self = [self initWithName:name localize:NO]) != nil) {
2908 if (localized != nil)
2909 localized_ = [localized retain];
2913 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2914 return [self initWithName:name row:0 localize:localize];
2917 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2918 if ((self = [super init]) != nil) {
2919 name_ = [name retain];
2923 localized_ = [LocalizeSection(name_) retain];
2927 /* XXX: localize the index thingees */
2928 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2929 if ((self = [super init]) != nil) {
2930 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2936 - (NSString *) name {
2956 - (void) addToCount {
2960 - (void) setCount:(size_t)count {
2964 - (NSString *) localized {
2971 static NSString *Colon_;
2972 static NSString *Error_;
2973 static NSString *Warning_;
2975 /* Database Implementation {{{ */
2976 @implementation Database
2978 + (Database *) sharedInstance {
2979 static Database *instance;
2980 if (instance == nil)
2981 instance = [[Database alloc] init];
2991 NSRecycleZone(zone_);
2992 // XXX: malloc_destroy_zone(zone_);
2993 apr_pool_destroy(pool_);
2997 - (void) _readCydia:(NSNumber *)fd { _pooled
2998 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2999 std::istream is(&ib);
3002 static Pcre finish_r("^finish:([^:]*)$");
3004 while (std::getline(is, line)) {
3005 const char *data(line.c_str());
3006 size_t size = line.size();
3007 lprintf("C:%s\n", data);
3009 if (finish_r(data, size)) {
3010 NSString *finish = finish_r[1];
3011 int index = [Finishes_ indexOfObject:finish];
3012 if (index != INT_MAX && index > Finish_)
3020 - (void) _readStatus:(NSNumber *)fd { _pooled
3021 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3022 std::istream is(&ib);
3025 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3026 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3028 while (std::getline(is, line)) {
3029 const char *data(line.c_str());
3030 size_t size(line.size());
3031 lprintf("S:%s\n", data);
3033 if (conffile_r(data, size)) {
3034 [delegate_ setConfigurationData:conffile_r[1]];
3035 } else if (strncmp(data, "status: ", 8) == 0) {
3036 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3037 [delegate_ setProgressTitle:string];
3038 } else if (pmstatus_r(data, size)) {
3039 std::string type([pmstatus_r[1] UTF8String]);
3040 NSString *id = pmstatus_r[2];
3042 float percent([pmstatus_r[3] floatValue]);
3043 [delegate_ setProgressPercent:(percent / 100)];
3045 NSString *string = pmstatus_r[4];
3047 if (type == "pmerror")
3048 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3049 withObject:[NSArray arrayWithObjects:string, id, nil]
3052 else if (type == "pmstatus") {
3053 [delegate_ setProgressTitle:string];
3054 } else if (type == "pmconffile")
3055 [delegate_ setConfigurationData:string];
3057 lprintf("E:unknown pmstatus\n");
3059 lprintf("E:unknown status\n");
3065 - (void) _readOutput:(NSNumber *)fd { _pooled
3066 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3067 std::istream is(&ib);
3070 while (std::getline(is, line)) {
3071 lprintf("O:%s\n", line.c_str());
3072 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3082 - (Package *) packageWithName:(NSString *)name {
3083 @synchronized (self) {
3084 if (static_cast<pkgDepCache *>(cache_) == NULL)
3086 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3087 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3091 if ((self = [super init]) != nil) {
3098 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3099 apr_pool_create(&pool_, NULL);
3101 packages_ = [[NSMutableArray alloc] init];
3105 _assert(pipe(fds) != -1);
3108 _config->Set("APT::Keep-Fds::", cydiafd_);
3109 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3112 detachNewThreadSelector:@selector(_readCydia:)
3114 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3117 _assert(pipe(fds) != -1);
3121 detachNewThreadSelector:@selector(_readStatus:)
3123 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3126 _assert(pipe(fds) != -1);
3127 _assert(dup2(fds[0], 0) != -1);
3128 _assert(close(fds[0]) != -1);
3130 input_ = fdopen(fds[1], "a");
3132 _assert(pipe(fds) != -1);
3133 _assert(dup2(fds[1], 1) != -1);
3134 _assert(close(fds[1]) != -1);
3137 detachNewThreadSelector:@selector(_readOutput:)
3139 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3144 - (pkgCacheFile &) cache {
3148 - (pkgDepCache::Policy *) policy {
3152 - (pkgRecords *) records {
3156 - (pkgProblemResolver *) resolver {
3160 - (pkgAcquire &) fetcher {
3164 - (pkgSourceList &) list {
3168 - (NSArray *) packages {
3172 - (NSArray *) sources {
3173 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3174 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3175 [sources addObject:i->second];
3179 - (NSArray *) issues {
3180 if (cache_->BrokenCount() == 0)
3183 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3185 for (Package *package in packages_) {
3186 if (![package broken])
3188 pkgCache::PkgIterator pkg([package iterator]);
3190 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3191 [entry addObject:[package name]];
3192 [issues addObject:entry];
3194 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3198 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3199 pkgCache::DepIterator start;
3200 pkgCache::DepIterator end;
3201 dep.GlobOr(start, end); // ++dep
3203 if (!cache_->IsImportantDep(end))
3205 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3208 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3209 [entry addObject:failure];
3210 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3212 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3213 if (Package *package = [self packageWithName:name])
3214 name = [package name];
3215 [failure addObject:name];
3217 pkgCache::PkgIterator target(start.TargetPkg());
3218 if (target->ProvidesList != 0)
3219 [failure addObject:@"?"];
3221 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3223 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3224 else if (!cache_[target].CandidateVerIter(cache_).end())
3225 [failure addObject:@"-"];
3226 else if (target->ProvidesList == 0)
3227 [failure addObject:@"!"];
3229 [failure addObject:@"%"];
3233 if (start.TargetVer() != 0)
3234 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3245 - (bool) popErrorWithTitle:(NSString *)title {
3247 std::string message;
3249 while (!_error->empty()) {
3251 bool warning(!_error->PopMessage(error));
3255 size_t size(error.size());
3256 if (size == 0 || error[size - 1] != '\n')
3258 error.resize(size - 1);
3260 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3262 if (!message.empty())
3267 if (fatal && !message.empty())
3268 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3273 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3274 return [self popErrorWithTitle:title] || !success;
3277 - (void) reloadData { CYPoolStart() {
3278 @synchronized (self) {
3281 [packages_ removeAllObjects];
3307 apr_pool_clear(pool_);
3308 NSRecycleZone(zone_);
3310 int chk(creat("/tmp/cydia.chk", 0644));
3314 NSString *title(UCLocalize("DATABASE"));
3317 if (!cache_.Open(progress_, true)) { pop:
3319 bool warning(!_error->PopMessage(error));
3320 lprintf("cache_.Open():[%s]\n", error.c_str());
3322 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3323 [delegate_ repairWithSelector:@selector(configure)];
3324 else if (error == "The package lists or status file could not be parsed or opened.")
3325 [delegate_ repairWithSelector:@selector(update)];
3326 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3327 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3328 // else if (error == "The list of sources could not be read.")
3330 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3339 unlink("/tmp/cydia.chk");
3341 now_ = [[NSDate date] retain];
3343 policy_ = new pkgDepCache::Policy();
3344 records_ = new pkgRecords(cache_);
3345 resolver_ = new pkgProblemResolver(cache_);
3346 fetcher_ = new pkgAcquire(&status_);
3349 list_ = new pkgSourceList();
3350 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3353 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3354 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3358 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3361 if (cache_->BrokenCount() != 0) {
3362 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3365 if (cache_->BrokenCount() != 0) {
3366 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3370 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3376 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3377 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3378 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3379 // XXX: this could be more intelligent
3380 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3381 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3383 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3390 /*std::vector<Package *> packages;
3391 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3392 [packages_ release];
3397 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3398 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3399 //packages.push_back(package);
3400 [packages_ addObject:package];
3404 /*if (packages.empty())
3405 packages_ = [[NSArray alloc] init];
3407 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3410 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3411 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3412 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3420 /*if (!packages.empty())
3421 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3422 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3424 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3426 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3428 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3435 - (void) configure {
3436 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3437 system([dpkg UTF8String]);
3441 // XXX: I don't remember this condition
3446 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3448 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3450 if ([self popErrorWithTitle:title])
3454 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3457 public pkgArchiveCleaner
3460 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3465 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3472 fetcher_->Shutdown();
3474 pkgRecords records(cache_);
3476 lock_ = new FileFd();
3477 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3479 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3481 if ([self popErrorWithTitle:title])
3485 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3488 manager_ = (_system->CreatePM(cache_));
3489 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3496 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3498 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3500 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3502 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3503 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3506 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3511 bool failed = false;
3512 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3513 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3515 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3518 std::string uri = (*item)->DescURI();
3519 std::string error = (*item)->ErrorText;
3521 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3524 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3525 withObject:[NSArray arrayWithObjects:
3526 [NSString stringWithUTF8String:error.c_str()],
3538 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3540 if (_error->PendingError()) {
3545 if (result == pkgPackageManager::Failed) {
3550 if (result != pkgPackageManager::Completed) {
3555 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3557 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3559 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3560 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3563 if (![before isEqualToArray:after])
3568 NSString *title(UCLocalize("UPGRADE"));
3569 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3575 [self updateWithStatus:status_];
3578 - (void) setVisible {
3579 for (Package *package in packages_)
3580 [package setVisible];
3583 - (void) updateWithStatus:(Status &)status {
3584 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3585 NSString *title(UCLocalize("REFRESHING_DATA"));
3588 if (!list.ReadMainList())
3589 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3592 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3593 if ([self popErrorWithTitle:title])
3596 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3597 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3598 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3600 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3604 - (void) setDelegate:(id)delegate {
3605 delegate_ = delegate;
3606 status_.setDelegate(delegate);
3607 progress_.setDelegate(delegate);
3610 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3611 SourceMap::const_iterator i(sources_.find(file->ID));
3612 return i == sources_.end() ? nil : i->second;
3618 /* Confirmation Controller {{{ */
3619 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3620 if (!iterator.end())
3621 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3622 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3624 pkgCache::PkgIterator package(dep.TargetPkg());
3627 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3635 /* Web Scripting {{{ */
3636 @interface CydiaObject : NSObject {
3641 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3644 @implementation CydiaObject
3647 [indirect_ release];
3651 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3652 if ((self = [super init]) != nil) {
3653 indirect_ = [indirect retain];
3657 - (void) setDelegate:(id)delegate {
3658 delegate_ = delegate;
3661 + (NSArray *) _attributeKeys {
3662 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3665 - (NSArray *) attributeKeys {
3666 return [[self class] _attributeKeys];
3669 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3670 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3673 - (NSString *) device {
3674 return [[UIDevice currentDevice] uniqueIdentifier];
3677 #if 0 // XXX: implement!
3678 - (NSString *) mac {
3679 if (![indirect_ promptForSensitive:@"Mac Address"])
3683 - (NSString *) serial {
3684 if (![indirect_ promptForSensitive:@"Serial #"])
3688 - (NSString *) firewire {
3689 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3693 - (NSString *) imei {
3694 if (![indirect_ promptForSensitive:@"IMEI"])
3699 + (NSString *) webScriptNameForSelector:(SEL)selector {
3700 if (selector == @selector(close))
3702 else if (selector == @selector(getInstalledPackages))
3703 return @"getInstalledPackages";
3704 else if (selector == @selector(getPackageById:))
3705 return @"getPackageById";
3706 else if (selector == @selector(installPackages:))
3707 return @"installPackages";
3708 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3709 return @"setButtonImage";
3710 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3711 return @"setButtonTitle";
3712 else if (selector == @selector(setPopupHook:))
3713 return @"setPopupHook";
3714 else if (selector == @selector(setSpecial:))
3715 return @"setSpecial";
3716 else if (selector == @selector(setToken:))
3718 else if (selector == @selector(setViewportWidth:))
3719 return @"setViewportWidth";
3720 else if (selector == @selector(supports:))
3722 else if (selector == @selector(stringWithFormat:arguments:))
3724 else if (selector == @selector(localizedStringForKey:value:table:))
3726 else if (selector == @selector(du:))
3728 else if (selector == @selector(statfs:))
3734 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3735 return [self webScriptNameForSelector:selector] == nil;
3738 - (BOOL) supports:(NSString *)feature {
3739 return [feature isEqualToString:@"window.open"];
3742 - (NSArray *) getInstalledPackages {
3743 NSArray *packages([[Database sharedInstance] packages]);
3744 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3745 for (Package *package in packages)
3746 if ([package installed] != nil)
3747 [installed addObject:package];
3751 - (Package *) getPackageById:(NSString *)id {
3752 Package *package([[Database sharedInstance] packageWithName:id]);
3757 - (NSArray *) statfs:(NSString *)path {
3760 if (path == nil || statfs([path UTF8String], &stat) == -1)
3763 return [NSArray arrayWithObjects:
3764 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3765 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3766 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3770 - (NSNumber *) du:(NSString *)path {
3771 NSNumber *value(nil);
3774 _assert(pipe(fds) != -1);
3776 pid_t pid(ExecFork());
3778 _assert(dup2(fds[1], 1) != -1);
3779 _assert(close(fds[0]) != -1);
3780 _assert(close(fds[1]) != -1);
3781 /* XXX: this should probably not use du */
3782 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3787 _assert(close(fds[1]) != -1);
3789 if (FILE *du = fdopen(fds[0], "r")) {
3791 while (fgets(line, sizeof(line), du) != NULL) {
3792 size_t length(strlen(line));
3793 while (length != 0 && line[length - 1] == '\n')
3794 line[--length] = '\0';
3795 if (char *tab = strchr(line, '\t')) {
3797 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3802 } else _assert(close(fds[0]));
3806 if (waitpid(pid, &status, 0) == -1)
3809 else _assert(false);
3818 - (void) installPackages:(NSArray *)packages {
3819 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3822 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3823 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3826 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3827 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3830 - (void) setSpecial:(id)function {
3831 [indirect_ setSpecial:function];
3834 - (void) setToken:(NSString *)token {
3837 Token_ = [token retain];
3839 [Metadata_ setObject:Token_ forKey:@"Token"];
3843 - (void) setPopupHook:(id)function {
3844 [indirect_ setPopupHook:function];
3847 - (void) setViewportWidth:(float)width {
3848 [indirect_ setViewportWidth:width];
3851 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3852 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3853 unsigned count([arguments count]);
3855 for (unsigned i(0); i != count; ++i)
3856 values[i] = [arguments objectAtIndex:i];
3857 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3860 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3861 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3863 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3865 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3871 /* Cydia Browser Controller {{{ */
3872 @interface CYBrowserController : BrowserController {
3873 CydiaObject *cydia_;
3878 @implementation CYBrowserController
3885 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3888 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3889 [super webView:view didClearWindowObject:window forFrame:frame];
3891 WebDataSource *source([frame dataSource]);
3892 NSURLResponse *response([source response]);
3893 NSURL *url([response URL]);
3894 NSString *scheme([url scheme]);
3896 NSHTTPURLResponse *http;
3897 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3898 http = (NSHTTPURLResponse *) response;
3902 NSDictionary *headers([http allHeaderFields]);
3903 NSString *host([url host]);
3904 [self setHeaders:headers forHost:host];
3907 [host isEqualToString:@"cydia.saurik.com"] ||
3908 [host hasSuffix:@".cydia.saurik.com"] ||
3909 [scheme isEqualToString:@"file"]
3911 [window setValue:cydia_ forKey:@"cydia"];
3914 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3915 if (System_ != NULL)
3916 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3917 if (Machine_ != NULL)
3918 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3920 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3922 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3925 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3926 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3927 [self _setMoreHeaders:copy];
3931 - (void) setDelegate:(id)delegate {
3932 [super setDelegate:delegate];
3933 [cydia_ setDelegate:delegate];
3937 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3938 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3940 WebView *webview([[webview_ _documentView] webView]);
3942 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3944 NSString *application = package == nil ? @"Cydia" : [NSString
3945 stringWithFormat:@"Cydia/%@",
3950 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3952 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3953 if (Product_ != nil)
3954 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3956 [webview setApplicationNameForUserAgent:application];
3963 /* Confirmation {{{ */
3964 @protocol ConfirmationControllerDelegate
3965 - (void) cancelAndClear:(bool)clear;
3966 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3970 @interface ConfirmationController : CYBrowserController {
3971 _transient Database *database_;
3972 UIAlertView *essential_;
3979 - (id) initWithDatabase:(Database *)database;
3983 @implementation ConfirmationController
3990 if (essential_ != nil)
3991 [essential_ release];
3995 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3996 NSString *context([alert context]);
3998 if ([context isEqualToString:@"remove"]) {
3999 if (button == [alert cancelButtonIndex]) {
4000 [self dismissModalViewControllerAnimated:YES];
4001 } else if (button == [alert firstOtherButtonIndex]) {
4004 [delegate_ confirmWithNavigationController:[self navigationController]];
4007 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4008 } else if ([context isEqualToString:@"unable"]) {
4009 [self dismissModalViewControllerAnimated:YES];
4010 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4012 [super alertView:alert clickedButtonAtIndex:button];
4016 - (void) _doContinue {
4017 [self dismissModalViewControllerAnimated:YES];
4018 [delegate_ cancelAndClear:NO];
4021 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4022 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4026 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4027 [super webView:view didClearWindowObject:window forFrame:frame];
4028 [window setValue:changes_ forKey:@"changes"];
4029 [window setValue:issues_ forKey:@"issues"];
4030 [window setValue:sizes_ forKey:@"sizes"];
4031 [window setValue:self forKey:@"queue"];
4034 - (id) initWithDatabase:(Database *)database {
4035 if ((self = [super init]) != nil) {
4036 database_ = database;
4038 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4040 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4041 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4042 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4043 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4044 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4048 pkgDepCache::Policy *policy([database_ policy]);
4050 pkgCacheFile &cache([database_ cache]);
4051 NSArray *packages = [database_ packages];
4052 for (Package *package in packages) {
4053 pkgCache::PkgIterator iterator = [package iterator];
4054 pkgDepCache::StateCache &state(cache[iterator]);
4056 NSString *name([package name]);
4058 if (state.NewInstall())
4059 [installing addObject:name];
4060 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4061 [reinstalling addObject:name];
4062 else if (state.Upgrade())
4063 [upgrading addObject:name];
4064 else if (state.Downgrade())
4065 [downgrading addObject:name];
4066 else if (state.Delete()) {
4067 if ([package essential])
4069 [removing addObject:name];
4072 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4073 substrate_ |= DepSubstrate(iterator.CurrentVer());
4078 else if (Advanced_) {
4079 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4081 essential_ = [[UIAlertView alloc]
4082 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4083 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4085 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4086 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4089 [essential_ setContext:@"remove"];
4091 essential_ = [[UIAlertView alloc]
4092 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4093 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4095 cancelButtonTitle:UCLocalize("OKAY")
4096 otherButtonTitles:nil
4099 [essential_ setContext:@"unable"];
4102 changes_ = [[NSArray alloc] initWithObjects:
4110 issues_ = [database_ issues];
4112 issues_ = [issues_ retain];
4114 sizes_ = [[NSArray alloc] initWithObjects:
4115 SizeString([database_ fetcher].FetchNeeded()),
4116 SizeString([database_ fetcher].PartialPresent()),
4119 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4121 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
4122 initWithTitle:UCLocalize("CANCEL")
4123 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4124 style:UIBarButtonItemStylePlain
4126 action:@selector(cancelButtonClicked)
4128 [[self navigationItem] setLeftBarButtonItem:leftItem];
4133 - (void) applyRightButton {
4134 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
4135 initWithTitle:UCLocalize("CONFIRM")
4136 style:UIBarButtonItemStylePlain
4138 action:@selector(confirmButtonClicked)
4140 #if !AlwaysReload && !IgnoreInstall
4141 if (issues_ == nil && ![self isLoading]) [[self navigationItem] setRightBarButtonItem:rightItem];
4142 else [super applyRightButton];
4144 [[self navigationItem] setRightBarButtonItem:nil];
4146 [rightItem release];
4149 - (void) cancelButtonClicked {
4150 [self dismissModalViewControllerAnimated:YES];
4151 [delegate_ cancelAndClear:YES];
4155 - (void) confirmButtonClicked {
4159 if (essential_ != nil)
4164 [delegate_ confirmWithNavigationController:[self navigationController]];
4172 /* Progress Data {{{ */
4173 @interface ProgressData : NSObject {
4179 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4186 @implementation ProgressData
4188 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4189 if ((self = [super init]) != nil) {
4190 selector_ = selector;
4210 /* Progress Controller {{{ */
4211 @interface ProgressController : CYViewController <
4212 ConfigurationDelegate,
4215 _transient Database *database_;
4216 UIProgressBar *progress_;
4217 UITextView *output_;
4218 UITextLabel *status_;
4219 UIPushButton *close_;
4221 SHA1SumValue springlist_;
4222 SHA1SumValue notifyconf_;
4226 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4228 - (void) _retachThread;
4229 - (void) _detachNewThreadData:(ProgressData *)data;
4230 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4236 @protocol ProgressControllerDelegate
4237 - (void) progressControllerIsComplete:(ProgressController *)sender;
4240 @implementation ProgressController
4243 [database_ setDelegate:nil];
4244 [progress_ release];
4253 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4254 if ((self = [super init]) != nil) {
4255 database_ = database;
4256 [database_ setDelegate:self];
4257 delegate_ = delegate;
4259 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4261 progress_ = [[UIProgressBar alloc] init];
4262 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4263 [progress_ setStyle:0];
4265 status_ = [[UITextLabel alloc] init];
4266 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4267 [status_ setColor:[UIColor whiteColor]];
4268 [status_ setBackgroundColor:[UIColor clearColor]];
4269 [status_ setCentersHorizontally:YES];
4270 //[status_ setFont:font];
4272 output_ = [[UITextView alloc] init];
4274 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4275 //[output_ setTextFont:@"Courier New"];
4276 [output_ setFont:[[output_ font] fontWithSize:12]];
4277 [output_ setTextColor:[UIColor whiteColor]];
4278 [output_ setBackgroundColor:[UIColor clearColor]];
4279 [output_ setMarginTop:0];
4280 [output_ setAllowsRubberBanding:YES];
4281 [output_ setEditable:NO];
4282 [[self view] addSubview:output_];
4284 close_ = [[UIPushButton alloc] init];
4285 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4286 [close_ setAutosizesToFit:NO];
4287 [close_ setDrawsShadow:YES];
4288 [close_ setStretchBackground:YES];
4289 [close_ setEnabled:YES];
4290 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4291 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4292 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4293 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4297 - (void) positionViews {
4298 CGRect bounds = [[self view] bounds];
4299 CGSize prgsize = [UIProgressBar defaultSize];
4302 (bounds.size.width - prgsize.width) / 2,
4303 bounds.size.height - prgsize.height - 20
4306 float closewidth = bounds.size.width - 20;
4307 if (closewidth > 300) closewidth = 300;
4309 [progress_ setFrame:prgrect];
4310 [status_ setFrame:CGRectMake(
4312 bounds.size.height - prgsize.height - 50,
4313 bounds.size.width - 20,
4316 [output_ setFrame:CGRectMake(
4319 bounds.size.width - 20,
4320 bounds.size.height - 62
4322 [close_ setFrame:CGRectMake(
4323 (bounds.size.width - closewidth) / 2,
4324 bounds.size.height - prgsize.height - 50,
4330 - (void) viewWillAppear:(BOOL)animated {
4331 [super viewDidAppear:animated];
4332 [[self navigationItem] setHidesBackButton:YES];
4333 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4335 [self positionViews];
4338 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4339 [self positionViews];
4342 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4343 NSString *context([alert context]);
4345 if ([context isEqualToString:@"conffile"]) {
4346 FILE *input = [database_ input];
4347 if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
4348 else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
4353 - (void) closeButtonPushed {
4356 UpdateExternalStatus(0);
4360 [self dismissModalViewControllerAnimated:YES];
4364 [delegate_ terminateWithSuccess];
4365 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4366 [delegate_ suspendWithAnimation:YES];
4368 [delegate_ suspend];*/
4372 system("launchctl stop com.apple.SpringBoard");
4376 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4385 - (void) _retachThread {
4386 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4388 [[self view] addSubview:close_];
4389 [progress_ removeFromSuperview];
4390 [status_ removeFromSuperview];
4392 [database_ popErrorWithTitle:title_];
4393 [delegate_ progressControllerIsComplete:self];
4397 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4400 MMap mmap(file, MMap::ReadOnly);
4402 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4403 if (!(notifyconf_ == sha1.Result()))
4410 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4413 MMap mmap(file, MMap::ReadOnly);
4415 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4416 if (!(springlist_ == sha1.Result()))
4422 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4423 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4424 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4425 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4426 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4429 system("su -c /usr/bin/uicache mobile");
4431 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4433 [delegate_ setStatusBarShowsProgress:NO];
4436 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4437 [[data target] performSelector:[data selector] withObject:[data object]];
4440 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4443 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4444 UpdateExternalStatus(1);
4451 title_ = [title retain];
4453 [[self navigationItem] setTitle:title_];
4455 [status_ setText:nil];
4456 [output_ setText:@""];
4457 [progress_ setProgress:0];
4459 [close_ removeFromSuperview];
4460 [[self view] addSubview:progress_];
4461 [[self view] addSubview:status_];
4463 [delegate_ setStatusBarShowsProgress:YES];
4468 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4471 MMap mmap(file, MMap::ReadOnly);
4473 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4474 notifyconf_ = sha1.Result();
4480 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4483 MMap mmap(file, MMap::ReadOnly);
4485 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4486 springlist_ = sha1.Result();
4491 detachNewThreadSelector:@selector(_detachNewThreadData:)
4493 withObject:[[ProgressData alloc]
4494 initWithSelector:selector
4501 - (void) repairWithSelector:(SEL)selector {
4503 detachNewThreadSelector:selector
4506 title:UCLocalize("REPAIRING")
4510 - (void) setConfigurationData:(NSString *)data {
4512 performSelectorOnMainThread:@selector(_setConfigurationData:)
4518 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4519 CYActionSheet *sheet([[[CYActionSheet alloc]
4521 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4522 defaultButtonIndex:0
4525 [sheet setMessage:error];
4526 [sheet yieldToPopupAlertAnimated:YES];
4530 - (void) setProgressTitle:(NSString *)title {
4532 performSelectorOnMainThread:@selector(_setProgressTitle:)
4538 - (void) setProgressPercent:(float)percent {
4540 performSelectorOnMainThread:@selector(_setProgressPercent:)
4541 withObject:[NSNumber numberWithFloat:percent]
4546 - (void) startProgress {
4549 - (void) addProgressOutput:(NSString *)output {
4551 performSelectorOnMainThread:@selector(_addProgressOutput:)
4557 - (bool) isCancelling:(size_t)received {
4561 - (void) _setConfigurationData:(NSString *)data {
4562 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4564 if (!conffile_r(data)) {
4565 lprintf("E:invalid conffile\n");
4569 NSString *ofile = conffile_r[1];
4570 //NSString *nfile = conffile_r[2];
4572 UIAlertView *alert = [[[UIAlertView alloc]
4573 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4574 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4576 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4577 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4578 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4582 [alert setContext:@"conffile"];
4586 - (void) _setProgressTitle:(NSString *)title {
4587 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4588 for (size_t i(0), e([words count]); i != e; ++i) {
4589 NSString *word([words objectAtIndex:i]);
4590 if (Package *package = [database_ packageWithName:word])
4591 [words replaceObjectAtIndex:i withObject:[package name]];
4594 [status_ setText:[words componentsJoinedByString:@" "]];
4597 - (void) _setProgressPercent:(NSNumber *)percent {
4598 [progress_ setProgress:[percent floatValue]];
4601 - (void) _addProgressOutput:(NSString *)output {
4602 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4603 CGSize size = [output_ contentSize];
4604 CGRect rect = {{0, size.height}, {size.width, 0}};
4605 [output_ scrollRectToVisible:rect animated:YES];
4608 - (BOOL) isRunning {
4615 /* Cell Content View {{{ */
4616 @protocol ContentDelegate
4617 - (void) drawContentRect:(CGRect)rect;
4620 @interface ContentView : UIView {
4621 _transient id<ContentDelegate> delegate_;
4626 @implementation ContentView
4627 - (id) initWithFrame:(CGRect)frame {
4628 if ((self = [super initWithFrame:frame]) != nil) {
4629 /* Fix landscape stretching. */
4630 [self setNeedsDisplayOnBoundsChange:YES];
4634 - (void) setDelegate:(id<ContentDelegate>)delegate {
4635 delegate_ = delegate;
4638 - (void) drawRect:(CGRect)rect {
4639 [super drawRect:rect];
4640 [delegate_ drawContentRect:rect];
4644 /* Package Cell {{{ */
4645 @interface PackageCell : UITableViewCell <
4650 NSString *description_;
4656 ContentView *content_;
4662 - (PackageCell *) init;
4663 - (void) setPackage:(Package *)package;
4665 + (int) heightForPackage:(Package *)package;
4666 - (void) drawContentRect:(CGRect)rect;
4670 @implementation PackageCell
4672 - (void) clearPackage {
4683 if (description_ != nil) {
4684 [description_ release];
4688 if (source_ != nil) {
4693 if (badge_ != nil) {
4698 if (placard_ != nil) {
4708 [self clearPackage];
4715 return faded_ ? [self selectionPercent] : fade_;
4718 - (PackageCell *) init {
4719 CGRect frame(CGRectMake(0, 0, 320, 74));
4720 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4721 UIView *content([self contentView]);
4722 CGRect bounds([content bounds]);
4724 content_ = [[ContentView alloc] initWithFrame:bounds];
4725 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4726 [content addSubview:content_];
4728 [content_ setDelegate:self];
4729 [content_ setOpaque:YES];
4730 if ([self respondsToSelector:@selector(selectionPercent)])
4735 - (void) _setBackgroundColor {
4737 if (NSString *mode = [package_ mode]) {
4738 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4739 color = remove ? RemovingColor_ : InstallingColor_;
4741 color = [UIColor whiteColor];
4743 [content_ setBackgroundColor:color];
4744 [self setNeedsDisplay];
4747 - (void) setPackage:(Package *)package {
4748 [self clearPackage];
4751 Source *source = [package source];
4753 icon_ = [[package icon] retain];
4754 name_ = [[package name] retain];
4757 description_ = [package longDescription];
4758 if (description_ == nil)
4759 description_ = [package shortDescription];
4760 if (description_ != nil)
4761 description_ = [description_ retain];
4763 commercial_ = [package isCommercial];
4765 package_ = [package retain];
4767 NSString *label = nil;
4768 bool trusted = false;
4770 if (source != nil) {
4771 label = [source label];
4772 trusted = [source trusted];
4773 } else if ([[package id] isEqualToString:@"firmware"])
4774 label = UCLocalize("APPLE");
4776 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4778 NSString *from(label);
4780 NSString *section = [package simpleSection];
4781 if (section != nil && ![section isEqualToString:label]) {
4782 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4783 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4786 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4787 source_ = [from retain];
4789 if (NSString *purpose = [package primaryPurpose])
4790 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4791 badge_ = [badge_ retain];
4793 if ([package installed] != nil)
4794 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4795 placard_ = [placard_ retain];
4797 [self _setBackgroundColor];
4798 [content_ setNeedsDisplay];
4801 - (void) drawContentRect:(CGRect)rect {
4802 bool selected([self isSelected]);
4803 float width([self bounds].size.width);
4806 CGContextRef context(UIGraphicsGetCurrentContext());
4807 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4808 CGContextFillRect(context, rect);
4813 rect.size = [icon_ size];
4815 rect.size.width /= 2;
4816 rect.size.height /= 2;
4818 rect.origin.x = 25 - rect.size.width / 2;
4819 rect.origin.y = 25 - rect.size.height / 2;
4821 [icon_ drawInRect:rect];
4824 if (badge_ != nil) {
4825 CGSize size = [badge_ size];
4827 [badge_ drawAtPoint:CGPointMake(
4828 36 - size.width / 2,
4829 36 - size.height / 2
4837 UISetColor(commercial_ ? Purple_ : Black_);
4838 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4839 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4842 UISetColor(commercial_ ? Purplish_ : Gray_);
4843 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4845 if (placard_ != nil)
4846 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4849 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4850 //[self _setBackgroundColor];
4851 [super setSelected:selected animated:fade];
4852 [content_ setNeedsDisplay];
4855 + (int) heightForPackage:(Package *)package {
4861 /* Section Cell {{{ */
4862 @interface SectionCell : UITableViewCell <
4870 ContentView *content_;
4875 - (void) setSection:(Section *)section editing:(BOOL)editing;
4879 @implementation SectionCell
4881 - (void) clearSection {
4882 if (basic_ != nil) {
4887 if (section_ != nil) {
4897 if (count_ != nil) {
4904 [self clearSection];
4912 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4913 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4914 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4915 switch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4916 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4918 UIView *content([self contentView]);
4919 CGRect bounds([content bounds]);
4921 content_ = [[ContentView alloc] initWithFrame:bounds];
4922 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4923 [content addSubview:content_];
4924 [content_ setBackgroundColor:[UIColor whiteColor]];
4926 [content_ setDelegate:self];
4930 - (void) onSwitch:(id)sender {
4931 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4932 if (metadata == nil) {
4933 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4934 [Sections_ setObject:metadata forKey:basic_];
4938 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4941 - (void) setSection:(Section *)section editing:(BOOL)editing {
4942 if (editing != editing_) {
4944 [switch_ removeFromSuperview];
4946 [self addSubview:switch_];
4950 [self clearSection];
4952 if (section == nil) {
4953 name_ = [UCLocalize("ALL_PACKAGES") retain];
4956 basic_ = [section name];
4958 basic_ = [basic_ retain];
4960 section_ = [section localized];
4961 if (section_ != nil)
4962 section_ = [section_ retain];
4964 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4965 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4968 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4971 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4972 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
4974 [content_ setNeedsDisplay];
4977 - (void) setFrame:(CGRect)frame {
4978 [super setFrame:frame];
4980 CGRect rect([switch_ frame]);
4981 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4984 - (void) drawContentRect:(CGRect)rect {
4985 BOOL selected = [self isSelected];
4987 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4995 float width(rect.size.width);
4999 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5001 CGSize size = [count_ sizeWithFont:Font14_];
5005 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5011 /* File Table {{{ */
5012 @interface FileTable : CYViewController <
5013 UITableViewDataSource,
5016 _transient Database *database_;
5019 NSMutableArray *files_;
5023 - (id) initWithDatabase:(Database *)database;
5024 - (void) setPackage:(Package *)package;
5028 @implementation FileTable
5031 if (package_ != nil)
5040 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5041 return files_ == nil ? 0 : [files_ count];
5044 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5048 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5049 static NSString *reuseIdentifier = @"Cell";
5051 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5053 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5054 [cell setFont:[UIFont systemFontOfSize:16]];
5056 [cell setText:[files_ objectAtIndex:indexPath.row]];
5057 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5062 - (id) initWithDatabase:(Database *)database {
5063 if ((self = [super init]) != nil) {
5064 database_ = database;
5066 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5068 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5070 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5071 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5072 [list_ setRowHeight:24.0f];
5073 [[self view] addSubview:list_];
5075 [list_ setDataSource:self];
5076 [list_ setDelegate:self];
5080 - (void) setPackage:(Package *)package {
5081 if (package_ != nil) {
5082 [package_ autorelease];
5091 [files_ removeAllObjects];
5093 if (package != nil) {
5094 package_ = [package retain];
5095 name_ = [[package id] retain];
5097 if (NSArray *files = [package files])
5098 [files_ addObjectsFromArray:files];
5100 if ([files_ count] != 0) {
5101 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5102 [files_ removeObjectAtIndex:0];
5103 [files_ sortUsingSelector:@selector(compareByPath:)];
5105 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5106 [stack addObject:@"/"];
5108 for (int i(0), e([files_ count]); i != e; ++i) {
5109 NSString *file = [files_ objectAtIndex:i];
5110 while (![file hasPrefix:[stack lastObject]])
5111 [stack removeLastObject];
5112 NSString *directory = [stack lastObject];
5113 [stack addObject:[file stringByAppendingString:@"/"]];
5114 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5115 ([stack count] - 2) * 3, "",
5116 [file substringFromIndex:[directory length]]
5125 - (void) reloadData {
5126 [self setPackage:[database_ packageWithName:name_]];
5131 /* Package Controller {{{ */
5132 @interface PackageController : CYBrowserController <
5133 UIActionSheetDelegate
5135 _transient Database *database_;
5139 NSMutableArray *buttons_;
5140 UIBarButtonItem *button_;
5143 - (id) initWithDatabase:(Database *)database;
5144 - (void) setPackage:(Package *)package;
5148 @implementation PackageController
5151 if (package_ != nil)
5165 if ([self retainCount] == 1)
5166 [delegate_ setPackageController:self];
5170 /* XXX: this is not safe at all... localization of /fail/ */
5171 - (void) _clickButtonWithName:(NSString *)name {
5172 if ([name isEqualToString:UCLocalize("CLEAR")])
5173 [delegate_ clearPackage:package_];
5174 else if ([name isEqualToString:UCLocalize("INSTALL")])
5175 [delegate_ installPackage:package_];
5176 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5177 [delegate_ installPackage:package_];
5178 else if ([name isEqualToString:UCLocalize("REMOVE")])
5179 [delegate_ removePackage:package_];
5180 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5181 [delegate_ installPackage:package_];
5182 else _assert(false);
5185 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5186 NSString *context([sheet context]);
5188 if ([context isEqualToString:@"modify"]) {
5189 if (button != [sheet cancelButtonIndex]) {
5190 NSString *buttonName = [buttons_ objectAtIndex:button];
5191 [self _clickButtonWithName:buttonName];
5194 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5198 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5199 [super webView:view didClearWindowObject:window forFrame:frame];
5200 [window setValue:package_ forKey:@"package"];
5203 - (bool) _allowJavaScriptPanel {
5208 - (void) _customButtonClicked {
5209 int count([buttons_ count]);
5214 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5216 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5217 [buttons addObjectsFromArray:buttons_];
5219 UIActionSheet *sheet = [[[UIActionSheet alloc]
5222 cancelButtonTitle:nil
5223 destructiveButtonTitle:nil
5224 otherButtonTitles:nil
5227 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5229 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5230 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5232 [sheet setContext:@"modify"];
5234 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5238 // We don't want to allow non-commercial packages to do custom things to the install button,
5239 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5240 - (void) customButtonClicked {
5242 [super customButtonClicked];
5244 [self _customButtonClicked];
5247 - (void) reloadButtonClicked {
5248 // Don't reload a package view by clicking the button.
5251 - (void) applyLoadingTitle {
5252 // Don't show "Loading" as the title. Ever.
5255 - (UIBarButtonItem *) rightButton {
5260 - (id) initWithDatabase:(Database *)database {
5261 if ((self = [super init]) != nil) {
5262 database_ = database;
5263 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5264 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5268 - (void) setPackage:(Package *)package {
5269 if (package_ != nil) {
5270 [package_ autorelease];
5279 [buttons_ removeAllObjects];
5281 if (package != nil) {
5284 package_ = [package retain];
5285 name_ = [[package id] retain];
5286 commercial_ = [package isCommercial];
5288 if ([package_ mode] != nil)
5289 [buttons_ addObject:UCLocalize("CLEAR")];
5290 if ([package_ source] == nil);
5291 else if ([package_ upgradableAndEssential:NO])
5292 [buttons_ addObject:UCLocalize("UPGRADE")];
5293 else if ([package_ uninstalled])
5294 [buttons_ addObject:UCLocalize("INSTALL")];
5296 [buttons_ addObject:UCLocalize("REINSTALL")];
5297 if (![package_ uninstalled])
5298 [buttons_ addObject:UCLocalize("REMOVE")];
5305 switch ([buttons_ count]) {
5306 case 0: title = nil; break;
5307 case 1: title = [buttons_ objectAtIndex:0]; break;
5308 default: title = UCLocalize("MODIFY"); break;
5311 button_ = [[UIBarButtonItem alloc]
5313 style:UIBarButtonItemStylePlain
5315 action:@selector(customButtonClicked)
5319 - (bool) isLoading {
5320 return commercial_ ? [super isLoading] : false;
5323 - (void) reloadData {
5324 [self setPackage:[database_ packageWithName:name_]];
5329 /* Package Table {{{ */
5330 @interface PackageTable : UIView <
5331 UITableViewDataSource,
5334 _transient Database *database_;
5335 NSMutableArray *packages_;
5336 NSMutableArray *sections_;
5338 NSMutableArray *index_;
5339 NSMutableDictionary *indices_;
5345 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5347 - (void) setDelegate:(id)delegate;
5349 - (void) reloadData;
5350 - (void) resetCursor;
5352 - (UITableView *) list;
5354 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5356 - (void) deselectWithAnimation:(BOOL)animated;
5360 @implementation PackageTable
5363 [packages_ release];
5364 [sections_ release];
5372 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5373 NSInteger count([sections_ count]);
5374 return count == 0 ? 1 : count;
5377 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5378 if ([sections_ count] == 0)
5380 return [[sections_ objectAtIndex:section] name];
5383 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5384 if ([sections_ count] == 0)
5386 return [[sections_ objectAtIndex:section] count];
5389 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5390 Section *section([sections_ objectAtIndex:[path section]]);
5391 NSInteger row([path row]);
5392 Package *package([packages_ objectAtIndex:([section row] + row)]);
5396 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5397 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5399 cell = [[[PackageCell alloc] init] autorelease];
5400 [cell setPackage:[self packageAtIndexPath:path]];
5404 - (void) deselectWithAnimation:(BOOL)animated {
5405 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5408 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5409 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5412 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5413 Package *package([self packageAtIndexPath:path]);
5414 package = [database_ packageWithName:[package id]];
5415 [target_ performSelector:action_ withObject:package];
5419 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5420 return [packages_ count] > 20 ? index_ : nil;
5423 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5427 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5428 if ((self = [super initWithFrame:frame]) != nil) {
5429 database_ = database;
5434 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5435 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5437 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5438 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5440 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5441 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5442 [list_ setRowHeight:73.0f];
5443 [self addSubview:list_];
5445 [list_ setDataSource:self];
5446 [list_ setDelegate:self];
5450 - (void) setDelegate:(id)delegate {
5451 delegate_ = delegate;
5454 - (bool) hasPackage:(Package *)package {
5458 - (void) reloadData {
5459 NSArray *packages = [database_ packages];
5461 [packages_ removeAllObjects];
5462 [sections_ removeAllObjects];
5464 _profile(PackageTable$reloadData$Filter)
5465 for (Package *package in packages)
5466 if ([self hasPackage:package])
5467 [packages_ addObject:package];
5470 [index_ removeAllObjects];
5471 [indices_ removeAllObjects];
5473 Section *section = nil;
5475 _profile(PackageTable$reloadData$Section)
5476 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5480 _profile(PackageTable$reloadData$Section$Package)
5481 package = [packages_ objectAtIndex:offset];
5482 index = [package index];
5485 if (section == nil || [section index] != index) {
5486 _profile(PackageTable$reloadData$Section$Allocate)
5487 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5490 [index_ addObject:[section name]];
5491 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5493 _profile(PackageTable$reloadData$Section$Add)
5494 [sections_ addObject:section];
5498 [section addToCount];
5502 _profile(PackageTable$reloadData$List)
5507 - (void) resetCursor {
5508 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5511 - (UITableView *) list {
5515 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5516 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5521 /* Filtered Package Table {{{ */
5522 @interface FilteredPackageTable : PackageTable {
5528 - (void) setObject:(id)object;
5529 - (void) setObject:(id)object forFilter:(SEL)filter;
5531 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5535 @implementation FilteredPackageTable
5543 - (void) setFilter:(SEL)filter {
5546 /* XXX: this is an unsafe optimization of doomy hell */
5547 Method method(class_getInstanceMethod([Package class], filter));
5548 _assert(method != NULL);
5549 imp_ = method_getImplementation(method);
5550 _assert(imp_ != NULL);
5553 - (void) setObject:(id)object {
5559 object_ = [object retain];
5562 - (void) setObject:(id)object forFilter:(SEL)filter {
5563 [self setFilter:filter];
5564 [self setObject:object];
5567 - (bool) hasPackage:(Package *)package {
5568 _profile(FilteredPackageTable$hasPackage)
5569 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5573 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5574 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5575 [self setFilter:filter];
5576 object_ = [object retain];
5584 /* Filtered Package Controller {{{ */
5585 @interface FilteredPackageController : CYViewController {
5586 _transient Database *database_;
5587 FilteredPackageTable *packages_;
5591 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5595 @implementation FilteredPackageController
5598 [packages_ release];
5604 - (void) viewDidAppear:(BOOL)animated {
5605 [super viewDidAppear:animated];
5606 [packages_ deselectWithAnimation:animated];
5609 - (void) didSelectPackage:(Package *)package {
5610 PackageController *view([delegate_ packageController]);
5611 [view setPackage:package];
5612 [view setDelegate:delegate_];
5613 [[self navigationController] pushViewController:view animated:YES];
5616 - (NSString *) title { return title_; }
5618 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5619 if ((self = [super init]) != nil) {
5620 database_ = database;
5621 title_ = [title copy];
5622 [[self navigationItem] setTitle:title_];
5624 packages_ = [[FilteredPackageTable alloc]
5625 initWithFrame:[[self view] bounds]
5628 action:@selector(didSelectPackage:)
5633 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5634 [[self view] addSubview:packages_];
5638 - (void) reloadData {
5639 [packages_ reloadData];
5642 - (void) setDelegate:(id)delegate {
5643 [super setDelegate:delegate];
5644 [packages_ setDelegate:delegate];
5651 /* Add Source Controller {{{ */
5652 @interface AddSourceController : CYViewController {
5653 _transient Database *database_;
5656 - (id) initWithDatabase:(Database *)database;
5660 @implementation AddSourceController
5662 - (id) initWithDatabase:(Database *)database {
5663 if ((self = [super init]) != nil) {
5664 database_ = database;
5670 /* Source Cell {{{ */
5671 @interface SourceCell : UITableViewCell <
5676 NSString *description_;
5678 ContentView *content_;
5681 - (void) setSource:(Source *)source;
5685 @implementation SourceCell
5687 - (void) clearSource {
5690 [description_ release];
5699 - (void) setSource:(Source *)source {
5703 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5705 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5706 icon_ = [icon_ retain];
5708 origin_ = [[source name] retain];
5709 label_ = [[source uri] retain];
5710 description_ = [[source description] retain];
5712 [content_ setNeedsDisplay];
5721 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5722 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5723 UIView *content([self contentView]);
5724 CGRect bounds([content bounds]);
5726 content_ = [[ContentView alloc] initWithFrame:bounds];
5727 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5728 [content_ setBackgroundColor:[UIColor whiteColor]];
5729 [content addSubview:content_];
5731 [content_ setDelegate:self];
5732 [content_ setOpaque:YES];
5736 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5737 [super setSelected:selected animated:animated];
5738 [content_ setNeedsDisplay];
5741 - (void) drawContentRect:(CGRect)rect {
5742 bool selected([self isSelected]);
5743 float width(rect.size.width);
5746 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5753 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5757 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5761 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5766 /* Source Table {{{ */
5767 @interface SourceTable : CYViewController <
5768 UITableViewDataSource,
5771 _transient Database *database_;
5773 NSMutableArray *sources_;
5777 UIProgressHUD *hud_;
5780 //NSURLConnection *installer_;
5781 NSURLConnection *trivial_;
5782 NSURLConnection *trivial_bz2_;
5783 NSURLConnection *trivial_gz_;
5784 //NSURLConnection *automatic_;
5789 - (id) initWithDatabase:(Database *)database;
5791 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5795 @implementation SourceTable
5797 - (void) _deallocConnection:(NSURLConnection *)connection {
5798 if (connection != nil) {
5799 [connection cancel];
5800 //[connection setDelegate:nil];
5801 [connection release];
5813 //[self _deallocConnection:installer_];
5814 [self _deallocConnection:trivial_];
5815 [self _deallocConnection:trivial_gz_];
5816 [self _deallocConnection:trivial_bz2_];
5817 //[self _deallocConnection:automatic_];
5824 - (void) viewDidAppear:(BOOL)animated {
5825 [super viewDidAppear:animated];
5826 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5829 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5830 return offset_ == 0 ? 1 : 2;
5833 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5834 switch (section + (offset_ == 0 ? 1 : 0)) {
5835 case 0: return UCLocalize("ENTERED_BY_USER");
5836 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5842 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5843 int count = [sources_ count];
5845 case 0: return (offset_ == 0 ? count : offset_);
5846 case 1: return count - offset_;
5852 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5854 switch (indexPath.section) {
5855 case 0: idx = indexPath.row; break;
5856 case 1: idx = indexPath.row + offset_; break;
5860 return [sources_ objectAtIndex:idx];
5863 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5864 Source *source = [self sourceAtIndexPath:indexPath];
5865 return [source description] == nil ? 56 : 73;
5868 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5869 static NSString *cellIdentifier = @"SourceCell";
5871 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5872 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5873 [cell setSource:[self sourceAtIndexPath:indexPath]];
5878 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5879 return UITableViewCellAccessoryDisclosureIndicator;
5882 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5883 Source *source = [self sourceAtIndexPath:indexPath];
5885 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5886 initWithDatabase:database_
5887 title:[source label]
5888 filter:@selector(isVisibleInSource:)
5892 [packages setDelegate:delegate_];
5894 [[self navigationController] pushViewController:packages animated:YES];
5897 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5898 Source *source = [self sourceAtIndexPath:indexPath];
5899 return [source record] != nil;
5902 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5903 Source *source = [self sourceAtIndexPath:indexPath];
5904 [Sources_ removeObjectForKey:[source key]];
5905 [delegate_ syncData];
5909 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5912 @"./", @"Distribution",
5913 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5915 [delegate_ syncData];
5918 - (NSString *) getWarning {
5919 NSString *href(href_);
5920 NSRange colon([href rangeOfString:@"://"]);
5921 if (colon.location != NSNotFound)
5922 href = [href substringFromIndex:(colon.location + 3)];
5923 href = [href stringByAddingPercentEscapes];
5924 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5925 href = [href stringByCachingURLWithCurrentCDN];
5927 NSURL *url([NSURL URLWithString:href]);
5929 NSStringEncoding encoding;
5930 NSError *error(nil);
5932 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5933 return [warning length] == 0 ? nil : warning;
5937 - (void) _endConnection:(NSURLConnection *)connection {
5938 NSURLConnection **field = NULL;
5939 if (connection == trivial_)
5941 else if (connection == trivial_bz2_)
5942 field = &trivial_bz2_;
5943 else if (connection == trivial_gz_)
5944 field = &trivial_gz_;
5945 _assert(field != NULL);
5946 [connection release];
5951 trivial_bz2_ == nil &&
5957 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5960 UIAlertView *alert = [[[UIAlertView alloc]
5961 initWithTitle:UCLocalize("SOURCE_WARNING")
5964 cancelButtonTitle:UCLocalize("CANCEL")
5965 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5968 [alert setContext:@"warning"];
5969 [alert setNumberOfRows:1];
5973 } else if (error_ != nil) {
5974 UIAlertView *alert = [[[UIAlertView alloc]
5975 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5976 message:[error_ localizedDescription]
5978 cancelButtonTitle:UCLocalize("OK")
5979 otherButtonTitles:nil
5982 [alert setContext:@"urlerror"];
5985 UIAlertView *alert = [[[UIAlertView alloc]
5986 initWithTitle:UCLocalize("NOT_REPOSITORY")
5987 message:UCLocalize("NOT_REPOSITORY_EX")
5989 cancelButtonTitle:UCLocalize("OK")
5990 otherButtonTitles:nil
5993 [alert setContext:@"trivial"];
5997 [delegate_ setStatusBarShowsProgress:NO];
5998 [delegate_ removeProgressHUD:hud_];
6008 if (error_ != nil) {
6015 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6016 switch ([response statusCode]) {
6022 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6023 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6025 error_ = [error retain];
6026 [self _endConnection:connection];
6029 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6030 [self _endConnection:connection];
6033 - (NSString *) title { return UCLocalize("SOURCES"); }
6035 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6036 NSMutableURLRequest *request = [NSMutableURLRequest
6037 requestWithURL:[NSURL URLWithString:href]
6038 cachePolicy:NSURLRequestUseProtocolCachePolicy
6039 timeoutInterval:120.0
6042 [request setHTTPMethod:method];
6044 if (Machine_ != NULL)
6045 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6046 if (UniqueID_ != nil)
6047 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6049 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6051 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6054 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6055 NSString *context([alert context]);
6057 if ([context isEqualToString:@"source"]) {
6060 NSString *href = [[alert textField] text];
6062 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6064 if (![href hasSuffix:@"/"])
6065 href_ = [href stringByAppendingString:@"/"];
6068 href_ = [href_ retain];
6070 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6071 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6072 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6073 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6077 hud_ = [[delegate_ addProgressHUD] retain];
6078 [hud_ setText:UCLocalize("VERIFYING_URL")];
6087 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6088 } else if ([context isEqualToString:@"trivial"])
6089 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6090 else if ([context isEqualToString:@"urlerror"])
6091 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6092 else if ([context isEqualToString:@"warning"]) {
6107 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6111 - (id) initWithDatabase:(Database *)database {
6112 if ((self = [super init]) != nil) {
6113 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6114 [self updateButtonsForEditingStatus:NO animated:NO];
6116 database_ = database;
6117 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6119 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6120 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6121 [[self view] addSubview:list_];
6123 [list_ setDataSource:self];
6124 [list_ setDelegate:self];
6130 - (void) reloadData {
6132 if (!list.ReadMainList())
6135 [sources_ removeAllObjects];
6136 [sources_ addObjectsFromArray:[database_ sources]];
6138 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6141 int count([sources_ count]);
6143 for (int i = 0; i != count; i++) {
6144 if ([[sources_ objectAtIndex:i] record] == nil) break;
6148 [list_ setEditing:NO];
6149 [self updateButtonsForEditingStatus:NO animated:NO];
6153 - (void) addButtonClicked {
6154 /*[book_ pushPage:[[[AddSourceController alloc]
6159 UIAlertView *alert = [[[UIAlertView alloc]
6160 initWithTitle:UCLocalize("ENTER_APT_URL")
6163 cancelButtonTitle:UCLocalize("CANCEL")
6164 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6167 [alert setContext:@"source"];
6168 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6170 [alert setNumberOfRows:1];
6171 [alert addTextFieldWithValue:@"http://" label:@""];
6173 UITextInputTraits *traits = [[alert textField] textInputTraits];
6174 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6175 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6176 [traits setKeyboardType:UIKeyboardTypeURL];
6177 // XXX: UIReturnKeyDone
6178 [traits setReturnKeyType:UIReturnKeyNext];
6183 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6184 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
6185 initWithTitle:UCLocalize("ADD")
6186 style:UIBarButtonItemStylePlain
6188 action:@selector(addButtonClicked)
6190 [[self navigationItem] setLeftBarButtonItem:editing ? leftItem : [[self navigationItem] backBarButtonItem] animated:animated];
6193 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6194 initWithTitle:editing ? UCLocalize("DONE") : UCLocalize("EDIT")
6195 style:editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6197 action:@selector(editButtonClicked)
6199 [[self navigationItem] setRightBarButtonItem:rightItem animated:animated];
6200 [rightItem release];
6202 if (IsWildcat_ && !editing) {
6203 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6204 initWithTitle:UCLocalize("SETTINGS")
6205 style:UIBarButtonItemStylePlain
6207 action:@selector(settingsButtonClicked)
6209 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6210 [settingsItem release];
6214 - (void) settingsButtonClicked {
6215 [delegate_ showSettings];
6218 - (void) editButtonClicked {
6219 [list_ setEditing:![list_ isEditing] animated:YES];
6221 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6227 /* Installed Controller {{{ */
6228 @interface InstalledController : FilteredPackageController {
6232 - (id) initWithDatabase:(Database *)database;
6234 - (void) updateRoleButton;
6235 - (void) queueStatusDidChange;
6239 @implementation InstalledController
6245 - (NSString *) title { return UCLocalize("INSTALLED"); }
6247 - (id) initWithDatabase:(Database *)database {
6248 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6249 [self updateRoleButton];
6250 [self queueStatusDidChange];
6255 - (void) queueButtonClicked {
6260 - (void) queueStatusDidChange {
6263 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6264 initWithTitle:UCLocalize("QUEUE")
6265 style:UIBarButtonItemStyleDone
6267 action:@selector(queueButtonClicked)
6269 if (Queuing_) [[self navigationItem] setLeftBarButtonItem:queueItem];
6270 else [[self navigationItem] setLeftBarButtonItem:nil];
6271 [queueItem release];
6276 - (void) reloadData {
6277 [packages_ reloadData];
6280 - (void) updateRoleButton {
6281 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6282 initWithTitle:expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")
6283 style:expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6285 action:@selector(roleButtonClicked)
6287 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) [[self navigationItem] setRightBarButtonItem:rightItem];
6288 [rightItem release];
6291 - (void) roleButtonClicked {
6292 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6293 [packages_ reloadData];
6296 [self updateRoleButton];
6299 - (void) setDelegate:(id)delegate {
6300 [super setDelegate:delegate];
6301 [packages_ setDelegate:delegate];
6307 /* Home Controller {{{ */
6308 @interface HomeController : CYBrowserController {
6313 @implementation HomeController
6315 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6316 [super _setMoreHeaders:request];
6319 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6320 if (UniqueID_ != nil)
6321 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6323 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6326 - (void) aboutButtonClicked {
6327 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6329 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6330 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6331 [alert setCancelButtonIndex:0];
6334 @"Copyright (C) 2008-2010\n"
6335 "Jay Freeman (saurik)\n"
6336 "saurik@saurik.com\n"
6337 "http://www.saurik.com/"
6343 - (void) viewWillAppear:(BOOL)animated {
6344 [super viewWillAppear:animated];
6345 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6348 - (void) viewWillDisappear:(BOOL)animated {
6349 [super viewWillDisappear:animated];
6350 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6354 if ((self = [super init]) != nil) {
6355 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6356 initWithTitle:UCLocalize("ABOUT")
6357 style:UIBarButtonItemStylePlain
6359 action:@selector(aboutButtonClicked)
6366 /* Manage Controller {{{ */
6367 @interface ManageController : CYBrowserController {
6370 - (void) queueStatusDidChange;
6373 @implementation ManageController
6376 if ((self = [super init]) != nil) {
6377 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6379 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6380 initWithTitle:UCLocalize("SETTINGS")
6381 style:UIBarButtonItemStylePlain
6383 action:@selector(settingsButtonClicked)
6385 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6386 [settingsItem release];
6388 [self queueStatusDidChange];
6392 - (void) settingsButtonClicked {
6393 [delegate_ showSettings];
6397 - (void) queueButtonClicked {
6401 - (void) applyLoadingTitle {
6402 // No "Loading" title.
6405 - (void) applyRightButton {
6410 - (void) queueStatusDidChange {
6412 if (!IsWildcat_ && Queuing_) {
6413 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6414 initWithTitle:UCLocalize("QUEUE")
6415 style:UIBarButtonItemStyleDone
6417 action:@selector(queueButtonClicked)
6419 [[self navigationItem] setRightBarButtonItem:queueItem];
6421 [queueItem release];
6423 [[self navigationItem] setRightBarButtonItem:nil];
6428 - (bool) isLoading {
6435 /* Refresh Bar {{{ */
6436 @interface RefreshBar : UINavigationBar {
6437 UIProgressIndicator *indicator_;
6438 UITextLabel *prompt_;
6439 UIProgressBar *progress_;
6440 UINavigationButton *cancel_;
6445 @implementation RefreshBar
6447 - (void) positionViews {
6448 CGRect frame = [cancel_ frame];
6449 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6450 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6451 [cancel_ setFrame:frame];
6453 CGSize prgsize = {75, 100};
6455 [self frame].size.width - prgsize.width - 10,
6456 ([self frame].size.height - prgsize.height) / 2
6458 [progress_ setFrame:prgrect];
6460 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6461 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6462 CGRect indrect = {{indoffset, indoffset}, indsize};
6463 [indicator_ setFrame:indrect];
6465 CGSize prmsize = {215, indsize.height + 4};
6467 indoffset * 2 + indsize.width,
6468 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6470 [prompt_ setFrame:prmrect];
6473 - (void)setFrame:(CGRect)frame {
6474 [super setFrame:frame];
6476 [self positionViews];
6479 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6480 if ((self = [super initWithFrame:frame])) {
6481 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6483 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6484 [self setBarStyle:UIBarStyleBlack];
6486 UIBarStyle barstyle([self _barStyle:NO]);
6487 bool ugly(barstyle == UIBarStyleDefault);
6489 UIProgressIndicatorStyle style = ugly ?
6490 UIProgressIndicatorStyleMediumBrown :
6491 UIProgressIndicatorStyleMediumWhite;
6493 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6494 [indicator_ setStyle:style];
6495 [indicator_ startAnimation];
6496 [self addSubview:indicator_];
6498 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6499 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6500 [prompt_ setBackgroundColor:[UIColor clearColor]];
6501 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6502 [self addSubview:prompt_];
6504 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6505 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6506 [progress_ setStyle:0];
6507 [self addSubview:progress_];
6509 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6510 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6511 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6512 [cancel_ setBarStyle:barstyle];
6514 [self positionViews];
6519 [cancel_ removeFromSuperview];
6523 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6524 [progress_ setProgress:0];
6525 [self addSubview:cancel_];
6529 [cancel_ removeFromSuperview];
6532 - (void) setPrompt:(NSString *)prompt {
6533 [prompt_ setText:prompt];
6536 - (void) setProgress:(float)progress {
6537 [progress_ setProgress:progress];
6543 @class CYNavigationController;
6545 /* Cydia Tab Bar Controller {{{ */
6546 @interface CYTabBarController : UITabBarController {
6547 Database *database_;
6552 @implementation CYTabBarController
6554 /* XXX: some logic should probably go here related to
6555 freeing the view controllers on tab change */
6557 - (void) reloadData {
6558 size_t count([[self viewControllers] count]);
6559 for (size_t i(0); i != count; ++i) {
6560 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6565 - (id) initWithDatabase:(Database *)database {
6566 if ((self = [super init]) != nil) {
6567 database_ = database;
6574 /* Cydia Navigation Controller {{{ */
6575 @interface CYNavigationController : UINavigationController {
6576 _transient Database *database_;
6577 id<UINavigationControllerDelegate> delegate_;
6580 - (id) initWithDatabase:(Database *)database;
6581 - (void) reloadData;
6586 @implementation CYNavigationController
6588 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6589 // Inherit autorotation settings for modal parents.
6590 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6591 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6593 return [super shouldAutorotateToInterfaceOrientation:orientation];
6601 - (void) reloadData {
6602 size_t count([[self viewControllers] count]);
6603 for (size_t i(0); i != count; ++i) {
6604 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6609 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6610 delegate_ = delegate;
6613 - (id) initWithDatabase:(Database *)database {
6614 if ((self = [super init]) != nil) {
6615 database_ = database;
6621 /* Cydia:// Protocol {{{ */
6622 @interface CydiaURLProtocol : NSURLProtocol {
6627 @implementation CydiaURLProtocol
6629 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6630 NSURL *url([request URL]);
6633 NSString *scheme([[url scheme] lowercaseString]);
6634 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6639 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6643 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6644 id<NSURLProtocolClient> client([self client]);
6646 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6648 NSData *data(UIImagePNGRepresentation(icon));
6650 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6651 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6652 [client URLProtocol:self didLoadData:data];
6653 [client URLProtocolDidFinishLoading:self];
6657 - (void) startLoading {
6658 id<NSURLProtocolClient> client([self client]);
6659 NSURLRequest *request([self request]);
6661 NSURL *url([request URL]);
6662 NSString *href([url absoluteString]);
6664 NSString *path([href substringFromIndex:8]);
6665 NSRange slash([path rangeOfString:@"/"]);
6668 if (slash.location == NSNotFound) {
6672 command = [path substringToIndex:slash.location];
6673 path = [path substringFromIndex:(slash.location + 1)];
6676 Database *database([Database sharedInstance]);
6678 if ([command isEqualToString:@"package-icon"]) {
6681 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6682 Package *package([database packageWithName:path]);
6685 UIImage *icon([package icon]);
6686 [self _returnPNGWithImage:icon forRequest:request];
6687 } else if ([command isEqualToString:@"source-icon"]) {
6690 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6691 NSString *source(Simplify(path));
6692 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6694 icon = [UIImage applicationImageNamed:@"unknown.png"];
6695 [self _returnPNGWithImage:icon forRequest:request];
6696 } else if ([command isEqualToString:@"uikit-image"]) {
6699 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6700 UIImage *icon(_UIImageWithName(path));
6701 [self _returnPNGWithImage:icon forRequest:request];
6702 } else if ([command isEqualToString:@"section-icon"]) {
6705 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6706 NSString *section(Simplify(path));
6707 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6709 icon = [UIImage applicationImageNamed:@"unknown.png"];
6710 [self _returnPNGWithImage:icon forRequest:request];
6712 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6716 - (void) stopLoading {
6722 /* Sections Controller {{{ */
6723 @interface SectionsController : CYViewController <
6724 UITableViewDataSource,
6727 _transient Database *database_;
6728 NSMutableArray *sections_;
6729 NSMutableArray *filtered_;
6735 - (id) initWithDatabase:(Database *)database;
6736 - (void) reloadData;
6739 - (void) editButtonClicked;
6743 @implementation SectionsController
6746 [list_ setDataSource:nil];
6747 [list_ setDelegate:nil];
6749 [sections_ release];
6750 [filtered_ release];
6752 [accessory_ release];
6756 - (void) viewDidAppear:(BOOL)animated {
6757 [super viewDidAppear:animated];
6758 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6761 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6762 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6766 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6767 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6770 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6774 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6775 static NSString *reuseIdentifier = @"SectionCell";
6777 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6778 if (cell == nil) cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6779 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6784 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6788 Section *section = [self sectionAtIndexPath:indexPath];
6789 NSString *name = [section name];
6792 if ([indexPath row] == 0) {
6795 title = UCLocalize("ALL_PACKAGES");
6798 name = [NSString stringWithString:name];
6799 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6802 title = UCLocalize("NO_SECTION");
6806 FilteredPackageController *table = [[[FilteredPackageController alloc]
6807 initWithDatabase:database_
6809 filter:@selector(isVisibleInSection:)
6813 [table setDelegate:delegate_];
6815 [[self navigationController] pushViewController:table animated:YES];
6818 - (NSString *) title { return UCLocalize("SECTIONS"); }
6820 - (id) initWithDatabase:(Database *)database {
6821 if ((self = [super init]) != nil) {
6822 database_ = database;
6824 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6826 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6827 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6829 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6830 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6831 [list_ setRowHeight:45.0f];
6832 [[self view] addSubview:list_];
6834 [list_ setDataSource:self];
6835 [list_ setDelegate:self];
6841 - (void) reloadData {
6842 NSArray *packages = [database_ packages];
6844 [sections_ removeAllObjects];
6845 [filtered_ removeAllObjects];
6848 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6849 SectionMap sections;
6850 sections.resize(64);
6852 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6856 for (Package *package in packages) {
6857 NSString *name([package section]);
6858 NSString *key(name == nil ? @"" : name);
6863 _profile(SectionsView$reloadData$Section)
6864 section = §ions[key];
6865 if (*section == nil) {
6866 _profile(SectionsView$reloadData$Section$Allocate)
6867 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6872 [*section addToCount];
6874 _profile(SectionsView$reloadData$Filter)
6875 if (![package valid] || ![package visible])
6879 [*section addToRow];
6883 _profile(SectionsView$reloadData$Section)
6884 section = [sections objectForKey:key];
6885 if (section == nil) {
6886 _profile(SectionsView$reloadData$Section$Allocate)
6887 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6888 [sections setObject:section forKey:key];
6893 [section addToCount];
6895 _profile(SectionsView$reloadData$Filter)
6896 if (![package valid] || ![package visible])
6906 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6907 [sections_ addObject:i->second];
6909 [sections_ addObjectsFromArray:[sections allValues]];
6912 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6914 for (Section *section in sections_) {
6915 size_t count([section row]);
6919 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6920 [section setCount:count];
6921 [filtered_ addObject:section];
6924 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6925 initWithTitle:[sections_ count] == 0 ? nil : UCLocalize("EDIT")
6926 style:UIBarButtonItemStylePlain
6928 action:@selector(editButtonClicked)
6930 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] != nil];
6931 [rightItem release];
6937 - (void) resetView {
6939 [self editButtonClicked];
6942 - (void) editButtonClicked {
6943 if ((editing_ = !editing_))
6946 [delegate_ updateData];
6948 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6949 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6950 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6953 - (UIView *) accessoryView {
6959 /* Changes Controller {{{ */
6960 @interface ChangesController : CYViewController <
6961 UITableViewDataSource,
6964 _transient Database *database_;
6965 NSMutableArray *packages_;
6966 NSMutableArray *sections_;
6969 BOOL hasSentFirstLoad_;
6972 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6973 - (void) reloadData;
6977 @implementation ChangesController
6980 [list_ setDelegate:nil];
6981 [list_ setDataSource:nil];
6983 [packages_ release];
6984 [sections_ release];
6989 - (void) viewDidAppear:(BOOL)animated {
6990 [super viewDidAppear:animated];
6991 if (!hasSentFirstLoad_) {
6992 hasSentFirstLoad_ = YES;
6993 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6995 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6999 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7000 NSInteger count([sections_ count]);
7001 return count == 0 ? 1 : count;
7004 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7005 if ([sections_ count] == 0)
7007 return [[sections_ objectAtIndex:section] name];
7010 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7011 if ([sections_ count] == 0)
7013 return [[sections_ objectAtIndex:section] count];
7016 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7017 Section *section([sections_ objectAtIndex:[path section]]);
7018 NSInteger row([path row]);
7019 return [packages_ objectAtIndex:([section row] + row)];
7022 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7023 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7025 cell = [[[PackageCell alloc] init] autorelease];
7026 [cell setPackage:[self packageAtIndexPath:path]];
7030 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7031 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7034 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7035 Package *package([self packageAtIndexPath:path]);
7036 PackageController *view([delegate_ packageController]);
7037 [view setDelegate:delegate_];
7038 [view setPackage:package];
7039 [[self navigationController] pushViewController:view animated:YES];
7043 - (void) refreshButtonClicked {
7044 [delegate_ beginUpdate];
7045 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7048 - (void) upgradeButtonClicked {
7049 [delegate_ distUpgrade];
7052 - (NSString *) title { return UCLocalize("CHANGES"); }
7054 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7055 if ((self = [super init]) != nil) {
7056 database_ = database;
7057 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7059 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
7060 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7062 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7063 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7064 [list_ setRowHeight:73.0f];
7065 [[self view] addSubview:list_];
7067 [list_ setDataSource:self];
7068 [list_ setDelegate:self];
7070 delegate_ = delegate;
7074 - (void) _reloadPackages:(NSArray *)packages {
7076 for (Package *package in packages)
7078 [package uninstalled] && [package valid] && [package visible] ||
7079 [package upgradableAndEssential:YES]
7081 [packages_ addObject:package];
7084 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7088 - (void) reloadData {
7089 NSArray *packages = [database_ packages];
7091 [packages_ removeAllObjects];
7092 [sections_ removeAllObjects];
7094 UIProgressHUD *hud([delegate_ addProgressHUD]);
7096 [hud setText:@"Loading Changes"];
7097 //NSLog(@"HUD:%@::%@", delegate_, hud);
7098 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7099 [delegate_ removeProgressHUD:hud];
7101 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7102 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7103 Section *section = nil;
7107 bool unseens = false;
7109 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7111 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7112 Package *package = [packages_ objectAtIndex:offset];
7114 BOOL uae = [package upgradableAndEssential:YES];
7120 _profile(ChangesController$reloadData$Remember)
7121 seen = [package seen];
7124 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7129 name = UCLocalize("UNKNOWN");
7131 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7135 _profile(ChangesController$reloadData$Allocate)
7136 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7137 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7138 [sections_ addObject:section];
7142 [section addToCount];
7143 } else if ([package ignored])
7144 [ignored addToCount];
7147 [upgradable addToCount];
7152 CFRelease(formatter);
7155 Section *last = [sections_ lastObject];
7156 size_t count = [last count];
7157 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7158 [sections_ removeLastObject];
7161 if ([ignored count] != 0)
7162 [sections_ insertObject:ignored atIndex:0];
7164 [sections_ insertObject:upgradable atIndex:0];
7168 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7169 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7170 style:UIBarButtonItemStylePlain
7172 action:@selector(upgradeButtonClicked)
7174 if (upgrades_ > 0) [[self navigationItem] setRightBarButtonItem:rightItem];
7175 [rightItem release];
7177 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
7178 initWithTitle:UCLocalize("REFRESH")
7179 style:UIBarButtonItemStylePlain
7181 action:@selector(refreshButtonClicked)
7183 if (![delegate_ updating]) [[self navigationItem] setLeftBarButtonItem:leftItem];
7189 /* Search Controller {{{ */
7190 @interface SearchController : FilteredPackageController <
7193 UISearchBar *search_;
7196 - (id) initWithDatabase:(Database *)database;
7197 - (void) reloadData;
7201 @implementation SearchController
7208 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7209 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7210 [search_ resignFirstResponder];
7214 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7215 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7219 - (NSString *) title { return nil; }
7221 - (id) initWithDatabase:(Database *)database {
7222 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7225 - (void)viewDidAppear:(BOOL)animated {
7226 [super viewDidAppear:animated];
7228 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7229 [search_ layoutSubviews];
7230 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7231 UITextField *textField = [search_ searchField];
7232 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7233 [search_ setDelegate:self];
7234 [textField setEnablesReturnKeyAutomatically:NO];
7235 [[self navigationItem] setTitleView:textField];
7239 - (void) _reloadData {
7242 - (void) reloadData {
7243 _profile(SearchController$reloadData)
7244 [packages_ reloadData];
7247 [packages_ resetCursor];
7250 - (void) didSelectPackage:(Package *)package {
7251 [search_ resignFirstResponder];
7252 [super didSelectPackage:package];
7257 /* Settings Controller {{{ */
7258 @interface SettingsController : CYViewController <
7259 UITableViewDataSource,
7262 _transient Database *database_;
7265 UITableView *table_;
7266 id subscribedSwitch_;
7268 UITableViewCell *subscribedCell_;
7269 UITableViewCell *ignoredCell_;
7272 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7276 @implementation SettingsController
7280 if (package_ != nil)
7283 [subscribedSwitch_ release];
7284 [ignoredSwitch_ release];
7285 [subscribedCell_ release];
7286 [ignoredCell_ release];
7291 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7292 if (package_ == nil)
7298 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7299 if (package_ == nil)
7305 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7306 return UCLocalize("SHOW_ALL_CHANGES_EX");
7309 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7310 if (package_ == nil)
7313 NSMutableDictionary *metadata([package_ metadata]);
7316 if (NSNumber *number = [metadata objectForKey:key])
7317 before = [number boolValue];
7321 if (value != before) {
7322 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7324 [delegate_ updateData];
7328 - (void) onSubscribed:(id)control {
7329 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7332 - (void) onIgnored:(id)control {
7333 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
7336 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7337 if (package_ == nil)
7340 switch ([indexPath row]) {
7341 case 0: return subscribedCell_;
7342 case 1: return ignoredCell_;
7350 - (NSString *) title { return UCLocalize("SETTINGS"); }
7352 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7353 if ((self = [super init])) {
7354 database_ = database;
7355 name_ = [package retain];
7357 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7359 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7360 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7361 [[self view] addSubview:table_];
7363 subscribedSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7364 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7365 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7367 ignoredSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7368 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7369 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7371 subscribedCell_ = [[UITableViewCell alloc] init];
7372 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7373 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7374 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7376 ignoredCell_ = [[UITableViewCell alloc] init];
7377 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7378 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7379 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7381 [table_ setDataSource:self];
7382 [table_ setDelegate:self];
7387 - (void) reloadData {
7388 if (package_ != nil)
7389 [package_ autorelease];
7390 package_ = [database_ packageWithName:name_];
7391 if (package_ != nil) {
7393 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7394 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7397 [table_ reloadData];
7402 /* Signature Controller {{{ */
7403 @interface SignatureController : CYBrowserController {
7404 _transient Database *database_;
7408 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7412 @implementation SignatureController
7419 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7421 [super webView:view didClearWindowObject:window forFrame:frame];
7424 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7425 if ((self = [super init]) != nil) {
7426 database_ = database;
7427 package_ = [package retain];
7432 - (void) reloadData {
7433 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7439 /* Role Controller {{{ */
7440 @interface RoleController : CYViewController <
7441 UITableViewDataSource,
7444 _transient Database *database_;
7446 UITableView *table_;
7447 UISegmentedControl *segment_;
7451 - (void) showDoneButton;
7452 - (void) resizeSegmentedControl;
7456 @implementation RoleController
7460 [container_ release];
7465 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7466 if ((self = [super init])) {
7467 database_ = database;
7468 roledelegate_ = delegate;
7470 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7472 NSArray *items = [NSArray arrayWithObjects:
7474 UCLocalize("HACKER"),
7475 UCLocalize("DEVELOPER"),
7477 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7478 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7479 [container_ addSubview:segment_];
7482 if ([Role_ isEqualToString:@"User"]) index = 0;
7483 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7484 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7486 [segment_ setSelectedSegmentIndex:index];
7487 [self showDoneButton];
7490 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7491 [self resizeSegmentedControl];
7493 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7494 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7495 [table_ setDelegate:self];
7496 [table_ setDataSource:self];
7497 [[self view] addSubview:table_];
7498 [table_ reloadData];
7502 - (void) resizeSegmentedControl {
7503 CGFloat width = [[self view] frame].size.width;
7504 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7507 - (void) viewWillAppear:(BOOL)animated {
7508 [super viewWillAppear:animated];
7510 [self resizeSegmentedControl];
7513 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7514 [self resizeSegmentedControl];
7517 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7518 [self resizeSegmentedControl];
7522 NSString *role(nil);
7524 switch ([segment_ selectedSegmentIndex]) {
7525 case 0: role = @"User"; break;
7526 case 1: role = @"Hacker"; break;
7527 case 2: role = @"Developer"; break;
7532 if (![role isEqualToString:Role_]) {
7533 bool rolling(Role_ == nil);
7536 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7540 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7545 [roledelegate_ loadData];
7547 [roledelegate_ updateData];
7551 - (void) segmentChanged:(UISegmentedControl *)control {
7552 [self showDoneButton];
7555 - (void) doneButtonClicked {
7557 [[self navigationController] dismissModalViewControllerAnimated:YES];
7560 - (void) showDoneButton {
7561 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7562 initWithTitle:UCLocalize("DONE")
7563 style:UIBarButtonItemStyleDone
7565 action:@selector(doneButtonClicked)
7567 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] == nil];
7568 [rightItem release];
7571 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7572 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7576 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7580 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7581 return nil; // This method is required by the protocol.
7584 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7586 return UCLocalize("ROLE_EX");
7588 return [NSString stringWithFormat:
7589 @"%@: %@\n%@: %@\n%@: %@",
7590 UCLocalize("USER"), UCLocalize("USER_EX"),
7591 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7592 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7597 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7598 if (section == 3) return 44.0f;
7602 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7603 if (section == 3) return container_;
7609 /* Stash Controller {{{ */
7610 @interface CYStashController : CYViewController {
7611 UIActivityIndicatorView *spinner_;
7617 @implementation CYStashController
7619 if ((self = [super init])) {
7620 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7622 spinner_ = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
7623 CGRect spinrect = [spinner_ frame];
7624 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7625 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7626 [spinner_ setFrame:spinrect];
7627 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7628 [[self view] addSubview:spinner_];
7630 [spinner_ startAnimating];
7633 captrect.size.width = [[self view] frame].size.width;
7634 captrect.size.height = 40.0f;
7635 captrect.origin.x = 0;
7636 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7637 caption_ = [[UILabel alloc] initWithFrame:captrect];
7638 [caption_ setText:@"Initializing Filesystem"];
7639 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7640 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7641 [caption_ setTextColor:[UIColor whiteColor]];
7642 [caption_ setBackgroundColor:[UIColor clearColor]];
7643 [caption_ setShadowColor:[UIColor blackColor]];
7644 [caption_ setTextAlignment:UITextAlignmentCenter];
7645 [[self view] addSubview:caption_];
7649 statusrect.size.width = [[self view] frame].size.width;
7650 statusrect.size.height = 30.0f;
7651 statusrect.origin.x = 0;
7652 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7653 status_ = [[UILabel alloc] initWithFrame:statusrect];
7654 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7655 [status_ setText:@"(Cydia will exit when complete.)"];
7656 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7657 [status_ setTextColor:[UIColor whiteColor]];
7658 [status_ setBackgroundColor:[UIColor clearColor]];
7659 [status_ setShadowColor:[UIColor blackColor]];
7660 [status_ setTextAlignment:UITextAlignmentCenter];
7661 [[self view] addSubview:status_];
7666 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7667 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7672 /* Cydia Container {{{ */
7673 @interface CYContainer : UIViewController <ProgressDelegate> {
7674 _transient Database *database_;
7675 RefreshBar *refreshbar_;
7680 UITabBarController *root_;
7683 - (void) setTabBarController:(UITabBarController *)controller;
7685 - (void) dropBar:(BOOL)animated;
7686 - (void) beginUpdate;
7687 - (void) raiseBar:(BOOL)animated;
7692 @implementation CYContainer
7694 - (BOOL) _reallyWantsFullScreenLayout {
7698 // NOTE: UIWindow only sends the top controller these messages,
7699 // So we have to forward them on.
7701 - (void) viewDidAppear:(BOOL)animated {
7702 [super viewDidAppear:animated];
7703 [root_ viewDidAppear:animated];
7706 - (void) viewWillAppear:(BOOL)animated {
7707 [super viewWillAppear:animated];
7708 [root_ viewWillAppear:animated];
7711 - (void) viewDidDisappear:(BOOL)animated {
7712 [super viewDidDisappear:animated];
7713 [root_ viewDidDisappear:animated];
7716 - (void) viewWillDisappear:(BOOL)animated {
7717 [super viewWillDisappear:animated];
7718 [root_ viewWillDisappear:animated];
7721 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7722 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7725 - (void) setTabBarController:(UITabBarController *)controller {
7727 [[self view] addSubview:[root_ view]];
7730 - (void) setUpdate:(NSDate *)date {
7734 - (void) beginUpdate {
7736 [refreshbar_ start];
7741 detachNewThreadSelector:@selector(performUpdate)
7747 - (void) performUpdate { _pooled
7749 status.setDelegate(self);
7750 [database_ updateWithStatus:status];
7753 performSelectorOnMainThread:@selector(completeUpdate)
7759 - (void) completeUpdate {
7760 if (!updating_) return;
7763 [self raiseBar:YES];
7765 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7768 - (void) cancelUpdate {
7770 [self raiseBar:YES];
7772 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7775 - (void) cancelPressed {
7776 [self cancelUpdate];
7783 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7784 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7787 - (void) startProgress {
7790 - (void) setProgressTitle:(NSString *)title {
7792 performSelectorOnMainThread:@selector(_setProgressTitle:)
7798 - (bool) isCancelling:(size_t)received {
7802 - (void) setProgressPercent:(float)percent {
7804 performSelectorOnMainThread:@selector(_setProgressPercent:)
7805 withObject:[NSNumber numberWithFloat:percent]
7810 - (void) addProgressOutput:(NSString *)output {
7812 performSelectorOnMainThread:@selector(_addProgressOutput:)
7818 - (void) _setProgressTitle:(NSString *)title {
7819 [refreshbar_ setPrompt:title];
7822 - (void) _setProgressPercent:(NSNumber *)percent {
7823 [refreshbar_ setProgress:[percent floatValue]];
7826 - (void) _addProgressOutput:(NSString *)output {
7829 - (void) setUpdateDelegate:(id)delegate {
7830 updatedelegate_ = delegate;
7833 - (CGFloat) statusBarHeight {
7834 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7835 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7837 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7841 - (void) dropBar:(BOOL)animated {
7842 if (dropped_) return;
7845 [[self view] addSubview:refreshbar_];
7847 CGFloat sboffset = [self statusBarHeight];
7849 CGRect barframe = [refreshbar_ frame];
7850 barframe.origin.y = sboffset;
7851 [refreshbar_ setFrame:barframe];
7853 if (animated) [UIView beginAnimations:nil context:NULL];
7854 CGRect viewframe = [[root_ view] frame];
7855 viewframe.origin.y += barframe.size.height + sboffset;
7856 viewframe.size.height -= barframe.size.height + sboffset;
7857 [[root_ view] setFrame:viewframe];
7858 if (animated) [UIView commitAnimations];
7860 // Ensure bar has the proper width for our view, it might have changed
7861 barframe.size.width = viewframe.size.width;
7862 [refreshbar_ setFrame:barframe];
7864 // XXX: fix Apple's layout bug
7865 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7868 - (void) raiseBar:(BOOL)animated {
7869 if (!dropped_) return;
7872 [refreshbar_ removeFromSuperview];
7874 CGFloat sboffset = [self statusBarHeight];
7876 if (animated) [UIView beginAnimations:nil context:NULL];
7877 CGRect barframe = [refreshbar_ frame];
7878 CGRect viewframe = [[root_ view] frame];
7879 viewframe.origin.y -= barframe.size.height + sboffset;
7880 viewframe.size.height += barframe.size.height + sboffset;
7881 [[root_ view] setFrame:viewframe];
7882 if (animated) [UIView commitAnimations];
7884 // XXX: fix Apple's layout bug
7885 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7888 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7889 // XXX: fix Apple's layout bug
7890 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7893 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7899 // XXX: fix Apple's layout bug
7900 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7903 - (void) statusBarFrameChanged:(NSNotification *)notification {
7911 [refreshbar_ release];
7912 [[NSNotificationCenter defaultCenter] removeObserver:self];
7916 - (id) initWithDatabase:(Database *)database {
7917 if ((self = [super init]) != nil) {
7918 database_ = database;
7920 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7921 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7923 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7940 @interface Cydia : UIApplication <
7941 ConfirmationControllerDelegate,
7942 ProgressControllerDelegate,
7944 UINavigationControllerDelegate
7947 CYContainer *container_;
7950 NSMutableArray *essential_;
7951 NSMutableArray *broken_;
7953 Database *database_;
7957 UIKeyboard *keyboard_;
7958 UIProgressHUD *hud_;
7960 SectionsController *sections_;
7961 ChangesController *changes_;
7962 ManageController *manage_;
7963 SearchController *search_;
7964 SourceTable *sources_;
7965 InstalledController *installed_;
7968 CYStashController *stash_;
7973 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7974 - (void) setPage:(CYViewController *)page;
7979 static _finline void _setHomePage(Cydia *self) {
7980 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7983 @implementation Cydia
7985 - (void) beginUpdate {
7986 [container_ beginUpdate];
7990 return [container_ updating];
7993 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7998 if ([broken_ count] != 0) {
7999 int count = [broken_ count];
8001 UIAlertView *alert = [[[UIAlertView alloc]
8002 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8003 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8005 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8006 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8009 [alert setContext:@"fixhalf"];
8011 } else if (!Ignored_ && [essential_ count] != 0) {
8012 int count = [essential_ count];
8014 UIAlertView *alert = [[[UIAlertView alloc]
8015 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8016 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8018 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8019 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8022 [alert setContext:@"upgrade"];
8027 - (void) _saveConfig {
8030 NSString *error(nil);
8031 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8033 NSError *error(nil);
8034 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8035 NSLog(@"failure to save metadata data: %@", error);
8038 NSLog(@"failure to serialize metadata: %@", error);
8046 - (void) _updateData {
8049 /* XXX: this is just stupid */
8050 if (tag_ != 1 && sections_ != nil)
8051 [sections_ reloadData];
8052 if (tag_ != 2 && changes_ != nil)
8053 [changes_ reloadData];
8054 if (tag_ != 4 && search_ != nil)
8055 [search_ reloadData];
8057 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8060 - (int)indexOfTabWithTag:(int)tag {
8062 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8063 if ([[controller tabBarItem] tag] == tag) return i;
8070 - (void) _refreshIfPossible {
8071 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8073 bool recently = false;
8074 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8075 if (update != nil) {
8076 NSTimeInterval interval([update timeIntervalSinceNow]);
8077 if (interval <= 0 && interval > -(15*60))
8081 // Don't automatic refresh if:
8082 // - We already refreshed recently.
8083 // - We already auto-refreshed this launch.
8084 // - Auto-refresh is disabled.
8085 if (recently || loaded_ || ManualRefresh) {
8086 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8088 // If we are cancelling due to ManualRefresh or a recent refresh
8089 // we need to make sure it knows it's already loaded.
8093 // We are going to load, so remember that.
8097 SCNetworkReachabilityFlags flags; {
8098 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8099 SCNetworkReachabilityGetFlags(reachability, &flags);
8100 CFRelease(reachability);
8103 // XXX: this elaborate mess is what Apple is using to determine this? :(
8104 // XXX: do we care if the user has to intervene? maybe that's ok?
8106 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8107 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8108 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8109 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8110 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8111 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8115 // If we can reach the server, auto-refresh!
8117 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8122 - (void) refreshIfPossible {
8123 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8126 - (void) _reloadData {
8127 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8128 [hud setText:UCLocalize("RELOADING_DATA")];
8130 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8133 if (hud) [self removeProgressHUD:hud];
8137 [essential_ removeAllObjects];
8138 [broken_ removeAllObjects];
8140 NSArray *packages([database_ packages]);
8141 for (Package *package in packages) {
8143 [broken_ addObject:package];
8144 if ([package upgradableAndEssential:NO]) {
8145 if ([package essential])
8146 [essential_ addObject:package];
8151 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8153 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8154 [changesItem setBadgeValue:badge];
8155 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8157 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8158 [self setApplicationBadge:badge];
8160 [self setApplicationBadgeString:badge];
8162 [changesItem setBadgeValue:nil];
8163 [changesItem setAnimatedBadge:NO];
8165 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8166 [self removeApplicationBadge];
8167 else // XXX: maybe use setApplicationBadgeString also?
8168 [self setApplicationIconBadgeNumber:0];
8173 [self refreshIfPossible];
8176 - (void) updateData {
8177 [database_ setVisible];
8186 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8187 _assert(file != NULL);
8189 for (NSString *key in [Sources_ allKeys]) {
8190 NSDictionary *source([Sources_ objectForKey:key]);
8192 fprintf(file, "%s %s %s\n",
8193 [[source objectForKey:@"Type"] UTF8String],
8194 [[source objectForKey:@"URI"] UTF8String],
8195 [[source objectForKey:@"Distribution"] UTF8String]
8203 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8204 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8205 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8206 [container_ presentModalViewController:navigation animated:YES];
8209 detachNewThreadSelector:@selector(update_)
8212 title:UCLocalize("UPDATING_SOURCES")
8216 - (void) reloadData {
8217 @synchronized (self) {
8223 pkgProblemResolver *resolver = [database_ resolver];
8225 resolver->InstallProtect();
8226 if (!resolver->Resolve(true))
8230 - (CGRect) popUpBounds {
8231 return [[tabbar_ view] bounds];
8235 if (![database_ prepare])
8238 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8239 [page setDelegate:self];
8240 CYNavigationController *confirm_ = [[CYNavigationController alloc] initWithRootViewController:page];
8241 [confirm_ setDelegate:self];
8243 if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8244 [container_ presentModalViewController:confirm_ animated:YES];
8250 @synchronized (self) {
8255 - (void) clearPackage:(Package *)package {
8256 @synchronized (self) {
8263 - (void) installPackages:(NSArray *)packages {
8264 @synchronized (self) {
8265 for (Package *package in packages)
8272 - (void) installPackage:(Package *)package {
8273 @synchronized (self) {
8280 - (void) removePackage:(Package *)package {
8281 @synchronized (self) {
8288 - (void) distUpgrade {
8289 @synchronized (self) {
8290 if (![database_ upgrade])
8297 @synchronized (self) {
8302 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8303 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8305 if (navigation != nil) {
8306 [navigation pushViewController:progress animated:YES];
8308 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8309 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8310 [container_ presentModalViewController:navigation animated:YES];
8314 detachNewThreadSelector:@selector(perform)
8317 title:UCLocalize("RUNNING")
8321 - (void) progressControllerIsComplete:(ProgressController *)progress {
8325 - (void) setPage:(CYViewController *)page {
8326 [page setDelegate:self];
8328 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8329 [navController setViewControllers:[NSArray arrayWithObject:page]];
8330 for (CYNavigationController *page in [tabbar_ viewControllers]) {
8331 if (page != navController) [page setViewControllers:nil];
8335 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8336 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8337 [browser loadURL:url];
8341 - (SectionsController *) sectionsController {
8342 if (sections_ == nil)
8343 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8347 - (ChangesController *) changesController {
8348 if (changes_ == nil)
8349 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8353 - (ManageController *) manageController {
8354 if (manage_ == nil) {
8355 manage_ = (ManageController *) [[self
8356 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8357 withClass:[ManageController class]
8359 if (!IsWildcat_) queueDelegate_ = manage_;
8364 - (SearchController *) searchController {
8366 search_ = [[SearchController alloc] initWithDatabase:database_];
8370 - (SourceTable *) sourcesController {
8371 if (sources_ == nil)
8372 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8376 - (InstalledController *) installedController {
8377 if (installed_ == nil) {
8378 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8379 if (IsWildcat_) queueDelegate_ = installed_;
8384 - (void) tabBarController:(id)tabBarController didSelectViewController:(UIViewController *)viewController {
8385 int tag = [[viewController tabBarItem] tag];
8387 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8389 } else if (tag_ == 1) {
8390 [[self sectionsController] resetView];
8394 case kCydiaTag: _setHomePage(self); break;
8396 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8397 case kChangesTag: [self setPage:[self changesController]]; break;
8398 case kManageTag: [self setPage:[self manageController]]; break;
8399 case kInstalledTag: [self setPage:[self installedController]]; break;
8400 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8401 case kSearchTag: [self setPage:[self searchController]]; break;
8409 - (void) showSettings {
8410 RoleController *role = [[RoleController alloc] initWithDatabase:database_ delegate:self];
8411 CYNavigationController *nav = [[CYNavigationController alloc] initWithRootViewController:role];
8412 if (IsWildcat_) [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8413 [container_ presentModalViewController:nav animated:YES];
8416 - (void) setPackageController:(PackageController *)view {
8418 [view setPackage:nil];
8422 - (PackageController *) _packageController {
8423 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8426 - (PackageController *) packageController {
8427 return [self _packageController];
8430 // Returns the navigation controller for the queuing badge.
8431 - (id) queueBadgeController {
8432 int index = [self indexOfTabWithTag:kManageTag];
8433 if (index == -1) index = [self indexOfTabWithTag:kInstalledTag];
8435 return [[tabbar_ viewControllers] objectAtIndex:index];
8438 - (void) cancelAndClear:(bool)clear {
8439 @synchronized (self) {
8442 pkgCacheFile &cache([database_ cache]);
8443 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
8444 // Unmark method taken from Synaptic Package Manager.
8445 // Thanks for being sane, unlike Aptitude.
8446 if (!cache[iterator].Keep()) {
8447 cache->MarkKeep(iterator, false);
8448 cache->SetReInstall(iterator, false);
8454 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
8458 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8461 // Show the changes in the current view.
8462 [(CYNavigationController *) [tabbar_ selectedViewController] reloadData];
8463 [queueDelegate_ queueStatusDidChange];
8467 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8468 NSString *context([alert context]);
8470 if ([context isEqualToString:@"fixhalf"]) {
8471 if (button == [alert firstOtherButtonIndex]) {
8472 @synchronized (self) {
8473 for (Package *broken in broken_) {
8476 NSString *id = [broken id];
8477 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8478 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8479 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8480 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8486 } else if (button == [alert cancelButtonIndex]) {
8487 [broken_ removeAllObjects];
8491 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8492 } else if ([context isEqualToString:@"upgrade"]) {
8493 if (button == [alert firstOtherButtonIndex]) {
8494 @synchronized (self) {
8495 for (Package *essential in essential_)
8496 [essential install];
8501 } else if (button == [alert firstOtherButtonIndex] + 1) {
8503 } else if (button == [alert cancelButtonIndex]) {
8507 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8511 - (void) system:(NSString *)command { _pooled
8512 system([command UTF8String]);
8515 - (void) applicationWillSuspend {
8517 [super applicationWillSuspend];
8520 - (void) applicationSuspend:(__GSEvent *)event {
8521 // Use external process status API internally.
8522 // This is probably a really bad idea.
8523 uint64_t status = 0;
8525 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8526 notify_get_state(notify_token, &status);
8527 notify_cancel(notify_token);
8530 if (hud_ == nil && status == 0)
8531 [super applicationSuspend:event];
8534 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8536 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8539 - (void) _setSuspended:(BOOL)value {
8541 [super _setSuspended:value];
8544 - (UIProgressHUD *) addProgressHUD {
8545 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8546 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8548 [window_ setUserInteractionEnabled:NO];
8551 UIViewController *target = container_;
8552 while ([target modalViewController] != nil) target = [target modalViewController];
8553 [[target view] addSubview:hud];
8558 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8560 [hud removeFromSuperview];
8561 [window_ setUserInteractionEnabled:YES];
8564 - (CYViewController *) pageForPackage:(NSString *)name {
8565 if (Package *package = [database_ packageWithName:name]) {
8566 PackageController *view([self packageController]);
8567 [view setPackage:package];
8570 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8571 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8572 return [self _pageForURL:url withClass:[CYBrowserController class]];
8576 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8580 NSString *href([url absoluteString]);
8581 if ([href hasPrefix:@"apptapp://package/"])
8582 return [self pageForPackage:[href substringFromIndex:18]];
8584 NSString *scheme([[url scheme] lowercaseString]);
8585 if (![scheme isEqualToString:@"cydia"])
8587 NSString *path([url absoluteString]);
8588 if ([path length] < 8)
8590 path = [path substringFromIndex:8];
8591 if (![path hasPrefix:@"/"])
8592 path = [@"/" stringByAppendingString:path];
8594 if ([path isEqualToString:@"/add-source"])
8595 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8596 else if ([path isEqualToString:@"/storage"])
8597 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8598 else if ([path isEqualToString:@"/sources"])
8599 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8600 else if ([path isEqualToString:@"/packages"])
8601 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8602 else if ([path hasPrefix:@"/url/"])
8603 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8604 else if ([path hasPrefix:@"/launch/"])
8605 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8606 else if ([path hasPrefix:@"/package-settings/"])
8607 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8608 else if ([path hasPrefix:@"/package-signature/"])
8609 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8610 else if ([path hasPrefix:@"/package/"])
8611 return [self pageForPackage:[path substringFromIndex:9]];
8612 else if ([path hasPrefix:@"/files/"]) {
8613 NSString *name = [path substringFromIndex:7];
8615 if (Package *package = [database_ packageWithName:name]) {
8616 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8617 [files setPackage:package];
8625 - (void) applicationOpenURL:(NSURL *)url {
8626 [super applicationOpenURL:url];
8628 if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
8629 [self setPage:page];
8631 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8635 - (void) applicationWillResignActive:(UIApplication *)application {
8636 // Stop refreshing if you get a phone call or lock the device.
8637 if ([container_ updating]) [container_ cancelUpdate];
8639 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8640 [super applicationWillResignActive:application];
8643 - (void) addStashController {
8644 stash_ = [[CYStashController alloc] init];
8645 [window_ addSubview:[stash_ view]];
8648 - (void) removeStashController {
8649 [[stash_ view] removeFromSuperview];
8654 [self setIdleTimerDisabled:YES];
8656 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8657 [self setStatusBarShowsProgress:YES];
8658 UpdateExternalStatus(1);
8660 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8662 UpdateExternalStatus(0);
8663 [self setStatusBarShowsProgress:NO];
8665 [self removeStashController];
8667 if (ExecFork() == 0) {
8668 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8669 perror("launchctl stop");
8673 - (void) setupTabBarController {
8674 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8675 [tabbar_ setDelegate:self];
8677 NSMutableArray *items([NSMutableArray arrayWithObjects:
8678 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8679 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8680 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8681 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8685 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8686 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8688 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8691 NSMutableArray *controllers([NSMutableArray array]);
8693 for (UITabBarItem *item in items) {
8694 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8695 [controller setTabBarItem:item];
8696 [controllers addObject:controller];
8699 [tabbar_ setViewControllers:controllers];
8700 [tabbar_ setSelectedIndex:0];
8703 - (void) applicationDidFinishLaunching:(id)unused {
8704 [CYBrowserController _initialize];
8706 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8708 Font12_ = [[UIFont systemFontOfSize:12] retain];
8709 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8710 Font14_ = [[UIFont systemFontOfSize:14] retain];
8711 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8712 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8716 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8717 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8719 UIScreen *screen([UIScreen mainScreen]);
8721 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8722 [window_ orderFront:self];
8723 [window_ makeKey:self];
8724 [window_ setHidden:NO];
8727 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8728 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8729 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8730 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8731 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8732 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8733 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8734 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8735 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8738 [self addStashController];
8739 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8743 database_ = [Database sharedInstance];
8745 [self setupTabBarController];
8747 container_ = [[CYContainer alloc] initWithDatabase:database_];
8748 [container_ setUpdateDelegate:self];
8749 [container_ setTabBarController:tabbar_];
8750 [window_ addSubview:[container_ view]];
8752 // Show pinstripes while loading data.
8753 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8755 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8760 [self showSettings];
8764 [UIKeyboard initImplementationNow];
8766 [window_ setUserInteractionEnabled:NO];
8768 UIView *container = [[UIView alloc] init];
8769 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8771 UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
8772 [spinner startAnimating];
8773 [container addSubview:spinner];
8776 UILabel *label = [[UILabel alloc] init];
8777 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8778 [label setBackgroundColor:[UIColor clearColor]];
8779 [label setTextColor:[UIColor blackColor]];
8780 [label setShadowColor:[UIColor whiteColor]];
8781 [label setShadowOffset:CGSizeMake(0, 1)];
8782 [label setText:UCLocalize("LOADING_DATA")];
8783 [container addSubview:label];
8786 CGSize viewsize = [[tabbar_ view] frame].size;
8787 CGSize spinnersize = [spinner bounds].size;
8788 CGSize textsize = [[label text] sizeWithFont:[label font]];
8789 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8791 CGRect containrect = {
8792 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8793 CGSizeMake(bothwidth, spinnersize.height)
8796 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8804 [container setFrame:containrect];
8805 [spinner setFrame:spinrect];
8806 [label setFrame:textrect];
8807 [[container_ view] addSubview:container];
8808 [container release];
8813 // Show the home page
8815 [window_ setUserInteractionEnabled:YES];
8817 // XXX: does this actually slow anything down?
8818 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8819 [container removeFromSuperview];
8822 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8823 if (item != nil && IsWildcat_) {
8824 [sheet showFromBarButtonItem:item animated:YES];
8826 [sheet showInView:window_];
8833 id Alloc_(id self, SEL selector) {
8834 id object = alloc_(self, selector);
8835 lprintf("[%s]A-%p\n", self->isa->name, object);
8840 id Dealloc_(id self, SEL selector) {
8841 id object = dealloc_(self, selector);
8842 lprintf("[%s]D-%p\n", self->isa->name, object);
8846 Class $WebDefaultUIKitDelegate;
8848 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8849 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8850 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8851 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8854 static NSNumber *shouldPlayKeyboardSounds;
8858 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8860 case 1104: // Keyboard Button Clicked
8861 case 1105: // Keyboard Delete Repeated
8862 if (shouldPlayKeyboardSounds == nil) {
8863 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8864 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8867 if (![shouldPlayKeyboardSounds boolValue])
8871 _UIHardware$_playSystemSound$(self, _cmd, sound);
8875 int main(int argc, char *argv[]) { _pooled
8878 if (Class $UIDevice = objc_getClass("UIDevice")) {
8879 UIDevice *device([$UIDevice currentDevice]);
8880 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8884 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8886 /* Library Hacks {{{ */
8887 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8889 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8890 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8891 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8892 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8893 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8896 $UIHardware = objc_getClass("UIHardware");
8897 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8898 if (UIHardware$_playSystemSound$ != NULL) {
8899 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8900 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8903 /* Set Locale {{{ */
8904 Locale_ = CFLocaleCopyCurrent();
8905 Languages_ = [NSLocale preferredLanguages];
8906 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8907 //NSLog(@"%@", [Languages_ description]);
8910 if (Languages_ == nil || [Languages_ count] == 0)
8911 // XXX: consider just setting to C and then falling through?
8914 lang = [[Languages_ objectAtIndex:0] UTF8String];
8915 setenv("LANG", lang, true);
8918 //std::setlocale(LC_ALL, lang);
8919 NSLog(@"Setting Language: %s", lang);
8922 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8924 /* Parse Arguments {{{ */
8925 bool substrate(false);
8931 for (int argi(1); argi != argc; ++argi)
8932 if (strcmp(argv[argi], "--") == 0) {
8934 argv[argi] = argv[0];
8940 for (int argi(1); argi != arge; ++argi)
8941 if (strcmp(args[argi], "--substrate") == 0)
8944 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8948 App_ = [[NSBundle mainBundle] bundlePath];
8949 Home_ = NSHomeDirectory();
8955 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8956 alloc_ = alloc->method_imp;
8957 alloc->method_imp = (IMP) &Alloc_;*/
8959 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8960 dealloc_ = dealloc->method_imp;
8961 dealloc->method_imp = (IMP) &Dealloc_;*/
8963 /* System Information {{{ */
8967 size = sizeof(maxproc);
8968 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8969 perror("sysctlbyname(\"kern.maxproc\", ?)");
8970 else if (maxproc < 64) {
8972 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8973 perror("sysctlbyname(\"kern.maxproc\", #)");
8976 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8977 char *osversion = new char[size];
8978 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8979 perror("sysctlbyname(\"kern.osversion\", ?)");
8981 System_ = [NSString stringWithUTF8String:osversion];
8983 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8984 char *machine = new char[size];
8985 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8986 perror("sysctlbyname(\"hw.machine\", ?)");
8990 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8991 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8992 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8993 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8997 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8998 NSData *data((NSData *) ecid);
8999 size_t length([data length]);
9000 uint8_t bytes[length];
9001 [data getBytes:bytes];
9002 char string[length * 2 + 1];
9003 for (size_t i(0); i != length; ++i)
9004 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9005 ChipID_ = [NSString stringWithUTF8String:string];
9009 IOObjectRelease(service);
9013 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9015 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9016 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9017 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9019 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9020 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9021 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9023 if (mcc != NULL && mnc != NULL)
9024 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9031 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9032 Build_ = [system objectForKey:@"ProductBuildVersion"];
9033 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9034 Product_ = [info objectForKey:@"SafariProductVersion"];
9035 Safari_ = [info objectForKey:@"CFBundleVersion"];
9038 /* Load Database {{{ */
9040 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9042 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9045 if (Metadata_ == NULL)
9046 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9048 Settings_ = [Metadata_ objectForKey:@"Settings"];
9050 Packages_ = [Metadata_ objectForKey:@"Packages"];
9051 Sections_ = [Metadata_ objectForKey:@"Sections"];
9052 Sources_ = [Metadata_ objectForKey:@"Sources"];
9054 Token_ = [Metadata_ objectForKey:@"Token"];
9057 if (Settings_ != nil)
9058 Role_ = [Settings_ objectForKey:@"Role"];
9060 if (Packages_ == nil) {
9061 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
9062 [Metadata_ setObject:Packages_ forKey:@"Packages"];
9065 if (Sections_ == nil) {
9066 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9067 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9070 if (Sources_ == nil) {
9071 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9072 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9076 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9078 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9079 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9080 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9081 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9082 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9083 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9085 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9087 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9088 unlink("/tmp/.cydia.fw");
9090 } else if (access("/User", F_OK) != 0 || version < 2) {
9093 system("/usr/libexec/cydia/firmware.sh");
9097 _assert([[NSFileManager defaultManager]
9098 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9099 withIntermediateDirectories:YES
9104 if (access("/tmp/cydia.chk", F_OK) == 0) {
9105 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9106 _assert(errno == ENOENT);
9107 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9108 _assert(errno == ENOENT);
9111 /* APT Initialization {{{ */
9112 _assert(pkgInitConfig(*_config));
9113 _assert(pkgInitSystem(*_config, _system));
9116 _config->Set("APT::Acquire::Translation", lang);
9118 // XXX: this timeout might be important :(
9119 //_config->Set("Acquire::http::Timeout", 15);
9121 _config->Set("Acquire::http::MaxParallel", 3);
9123 /* Color Choices {{{ */
9124 space_ = CGColorSpaceCreateDeviceRGB();
9126 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9127 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9128 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9129 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9130 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9131 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9132 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9133 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9134 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9136 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9137 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9139 /* UIKit Configuration {{{ */
9140 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9141 if ($GSFontSetUseLegacyFontMetrics != NULL)
9142 $GSFontSetUseLegacyFontMetrics(YES);
9144 // XXX: I have a feeling this was important
9145 //UIKeyboardDisableAutomaticAppearance();
9148 Colon_ = UCLocalize("COLON_DELIMITED");
9149 Error_ = UCLocalize("ERROR");
9150 Warning_ = UCLocalize("WARNING");
9153 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9155 CGColorSpaceRelease(space_);