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 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
202 void NSLogPoint(const char *fix, const CGPoint &point) {
203 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
206 void NSLogRect(const char *fix, const CGRect &rect) {
207 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
210 static _finline NSString *CydiaURL(NSString *path) {
212 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
213 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
214 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
215 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
216 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
217 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
220 static _finline void UpdateExternalStatus(uint64_t newStatus) {
222 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
223 notify_set_state(notify_token, newStatus);
224 notify_cancel(notify_token);
226 notify_post("com.saurik.Cydia.status");
229 /* [NSObject yieldToSelector:(withObject:)] {{{*/
230 @interface NSObject (Cydia)
231 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
232 - (id) yieldToSelector:(SEL)selector;
235 @implementation NSObject (Cydia)
240 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
241 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
242 id object([[context objectAtIndex:1] nonretainedObjectValue]);
243 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
245 /* XXX: deal with exceptions */
246 id value([self performSelector:selector withObject:object]);
248 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
249 [context removeAllObjects];
250 if ([signature methodReturnLength] != 0 && value != nil)
251 [context addObject:value];
256 performSelectorOnMainThread:@selector(doNothing)
262 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
263 /*return [self performSelector:selector withObject:object];*/
265 volatile bool stopped(false);
267 NSMutableArray *context([NSMutableArray arrayWithObjects:
268 [NSValue valueWithPointer:selector],
269 [NSValue valueWithNonretainedObject:object],
270 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
273 NSThread *thread([[[NSThread alloc]
275 selector:@selector(_yieldToContext:)
281 NSRunLoop *loop([NSRunLoop currentRunLoop]);
282 NSDate *future([NSDate distantFuture]);
284 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
286 return [context count] == 0 ? nil : [context objectAtIndex:0];
289 - (id) yieldToSelector:(SEL)selector {
290 return [self yieldToSelector:selector withObject:nil];
296 @interface CYActionSheet : UIAlertView {
300 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
303 @implementation CYActionSheet
305 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
306 if ((self = [super init])) {
307 [self setTitle:title];
308 [self setDelegate:self];
309 for (NSString *button in buttons) [self addButtonWithTitle:button];
310 [self setCancelButtonIndex:index];
314 - (void)_updateFrameForDisplay {
315 [super _updateFrameForDisplay];
316 if ([self cancelButtonIndex] == -1) {
317 NSArray *buttons = [self buttons];
318 if ([buttons count]) {
319 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
320 for (UIThreePartButton *button in buttons)
321 [button setBackground:background forState:0];
326 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
327 button_ = buttonIndex + 1;
331 [self dismissWithClickedButtonIndex:-1 animated:YES];
334 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
335 [self setRunsModal:YES];
343 /* NSForcedOrderingSearch doesn't work on the iPhone */
344 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
345 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
346 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
348 /* Information Dictionaries {{{ */
349 @interface NSMutableArray (Cydia)
350 - (void) addInfoDictionary:(NSDictionary *)info;
353 @implementation NSMutableArray (Cydia)
355 - (void) addInfoDictionary:(NSDictionary *)info {
356 [self addObject:info];
361 @interface NSMutableDictionary (Cydia)
362 - (void) addInfoDictionary:(NSDictionary *)info;
365 @implementation NSMutableDictionary (Cydia)
367 - (void) addInfoDictionary:(NSDictionary *)info {
368 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
374 #define lprintf(args...) fprintf(stderr, args)
377 #define TraceLogging (1 && !ForRelease)
378 #define HistogramInsertionSort (0 && !ForRelease)
379 #define ProfileTimes (0 && !ForRelease)
380 #define ForSaurik (0 && !ForRelease)
381 #define LogBrowser (0 && !ForRelease)
382 #define TrackResize (0 && !ForRelease)
383 #define ManualRefresh (0 && !ForRelease)
384 #define ShowInternals (0 && !ForRelease)
385 #define IgnoreInstall (0 && !ForRelease)
386 #define RecycleWebViews 0
387 #define RecyclePackageViews (1 && ForRelease)
388 #define AlwaysReload (1 && !ForRelease)
392 #define _trace(args...)
397 #define _profile(name) {
400 #define PrintTimes() do {} while (false)
404 typedef uint32_t (*SKRadixFunction)(id, void *);
406 @interface NSMutableArray (Radix)
407 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
408 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
416 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
417 struct RadixItem_ *lhs(swap), *rhs(swap + count);
419 static const size_t width = 32;
420 static const size_t bits = 11;
421 static const size_t slots = 1 << bits;
422 static const size_t passes = (width + (bits - 1)) / bits;
424 size_t *hist(new size_t[slots]);
426 for (size_t pass(0); pass != passes; ++pass) {
427 memset(hist, 0, sizeof(size_t) * slots);
429 for (size_t i(0); i != count; ++i) {
430 uint32_t key(lhs[i].key);
432 key &= _not(uint32_t) >> width - bits;
437 for (size_t i(0); i != slots; ++i) {
438 size_t local(offset);
443 for (size_t i(0); i != count; ++i) {
444 uint32_t key(lhs[i].key);
446 key &= _not(uint32_t) >> width - bits;
447 rhs[hist[key]++] = lhs[i];
450 RadixItem_ *tmp(lhs);
457 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
458 for (size_t i(0); i != count; ++i)
459 [values addObject:[self objectAtIndex:lhs[i].index]];
460 [self setArray:values];
465 @implementation NSMutableArray (Radix)
467 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
468 size_t count([self count]);
473 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
474 [invocation setSelector:selector];
475 [invocation setArgument:&object atIndex:2];
477 /* XXX: this is an unsafe optimization of doomy hell */
478 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
479 _assert(method != NULL);
480 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
481 _assert(imp != NULL);
484 struct RadixItem_ *swap(new RadixItem_[count * 2]);
486 for (size_t i(0); i != count; ++i) {
487 RadixItem_ &item(swap[i]);
490 id object([self objectAtIndex:i]);
493 [invocation setTarget:object];
495 [invocation getReturnValue:&item.key];
497 item.key = imp(object, selector, object);
501 RadixSort_(self, count, swap);
504 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
505 size_t count([self count]);
506 struct RadixItem_ *swap(new RadixItem_[count * 2]);
508 for (size_t i(0); i != count; ++i) {
509 RadixItem_ &item(swap[i]);
512 id object([self objectAtIndex:i]);
513 item.key = function(object, argument);
516 RadixSort_(self, count, swap);
521 /* Insertion Sort {{{ */
523 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
524 const char *ptr = (const char *)list;
526 CFIndex half = count / 2;
527 const char *probe = ptr + elementSize * half;
528 CFComparisonResult cr = comparator(element, probe, context);
529 if (0 == cr) return (probe - (const char *)list) / elementSize;
530 ptr = (cr < 0) ? ptr : probe + elementSize;
531 count = (cr < 0) ? half : (half + (count & 1) - 1);
533 return (ptr - (const char *)list) / elementSize;
536 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
537 const char *ptr = (const char *)list;
539 CFIndex half = count / 2;
540 const char *probe = ptr + elementSize * half;
541 CFComparisonResult cr = comparator(element, probe, context);
542 if (0 == cr) return (probe - (const char *)list) / elementSize;
543 ptr = (cr < 0) ? ptr : probe + elementSize;
544 count = (cr < 0) ? half : (half + (count & 1) - 1);
546 return (ptr - (const char *)list) / elementSize;
549 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
550 if (range.length == 0)
552 const void **values(new const void *[range.length]);
553 CFArrayGetValues(array, range, values);
555 #if HistogramInsertionSort
556 uint32_t total(0), *offsets(new uint32_t[range.length]);
559 for (CFIndex index(1); index != range.length; ++index) {
560 const void *value(values[index]);
561 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
562 CFIndex correct(index);
563 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
566 if (correct != index) {
567 size_t offset(index - correct);
568 #if HistogramInsertionSort
572 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
574 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
575 values[correct] = value;
579 CFArrayReplaceValues(array, range, values, range.length);
582 #if HistogramInsertionSort
583 for (CFIndex index(0); index != range.length; ++index)
584 if (offsets[index] != 0)
585 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
586 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
593 /* Apple Bug Fixes {{{ */
594 @implementation UIWebDocumentView (Cydia)
596 - (void) _setScrollerOffset:(CGPoint)offset {
597 UIScroller *scroller([self _scroller]);
599 CGSize size([scroller contentSize]);
600 CGSize bounds([scroller bounds].size);
603 max.x = size.width - bounds.width;
604 max.y = size.height - bounds.height;
612 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
613 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
615 [scroller setOffset:offset];
621 NSUInteger WebScriptObject$countByEnumeratingWithState$objects$count$(WebScriptObject *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
622 size_t length([self count] - state->state);
625 else if (length > count)
627 for (size_t i(0); i != length; ++i)
628 objects[i] = [self objectAtIndex:state->state++];
629 state->itemsPtr = objects;
630 state->mutationsPtr = (unsigned long *) self;
634 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
635 size_t length([self length] - state->state);
638 else if (length > count)
640 for (size_t i(0); i != length; ++i)
641 objects[i] = [self item:state->state++];
642 state->itemsPtr = objects;
643 state->mutationsPtr = (unsigned long *) self;
647 /* Cydia NSString Additions {{{ */
648 @interface NSString (Cydia)
649 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
650 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
651 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
652 - (NSComparisonResult) compareByPath:(NSString *)other;
653 - (NSString *) stringByCachingURLWithCurrentCDN;
654 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
657 @implementation NSString (Cydia)
659 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
660 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
663 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
664 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
665 memcpy(data, bytes, length);
666 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
669 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
670 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
673 - (NSComparisonResult) compareByPath:(NSString *)other {
674 NSString *prefix = [self commonPrefixWithString:other options:0];
675 size_t length = [prefix length];
677 NSRange lrange = NSMakeRange(length, [self length] - length);
678 NSRange rrange = NSMakeRange(length, [other length] - length);
680 lrange = [self rangeOfString:@"/" options:0 range:lrange];
681 rrange = [other rangeOfString:@"/" options:0 range:rrange];
683 NSComparisonResult value;
685 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
686 value = NSOrderedSame;
687 else if (lrange.location == NSNotFound)
688 value = NSOrderedAscending;
689 else if (rrange.location == NSNotFound)
690 value = NSOrderedDescending;
692 value = NSOrderedSame;
694 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
695 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
696 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
697 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
699 NSComparisonResult result = [lpath compare:rpath];
700 return result == NSOrderedSame ? value : result;
703 - (NSString *) stringByCachingURLWithCurrentCDN {
705 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
706 withString:@"://cache.cydia.saurik.com/"
710 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
711 return [(id)CFURLCreateStringByAddingPercentEscapes(
716 kCFStringEncodingUTF8
723 /* C++ NSString Wrapper Cache {{{ */
730 _finline void clear_() {
731 if (cache_ != NULL) {
738 _finline bool empty() const {
742 _finline size_t size() const {
746 _finline char *data() const {
750 _finline void clear() {
755 _finline CYString() :
762 _finline ~CYString() {
766 void operator =(const CYString &rhs) {
770 if (rhs.cache_ == nil)
773 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
776 void set(apr_pool_t *pool, const char *data, size_t size) {
782 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
783 memcpy(temp, data, size);
790 _finline void set(apr_pool_t *pool, const char *data) {
791 set(pool, data, data == NULL ? 0 : strlen(data));
794 _finline void set(apr_pool_t *pool, const std::string &rhs) {
795 set(pool, rhs.data(), rhs.size());
798 bool operator ==(const CYString &rhs) const {
799 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
802 operator CFStringRef() {
803 if (cache_ == NULL) {
806 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
808 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
812 _finline operator id() {
813 return (NSString *) static_cast<CFStringRef>(*this);
817 /* C++ NSString Algorithm Adapters {{{ */
819 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
822 struct NSStringMapHash :
823 std::unary_function<NSString *, size_t>
825 _finline size_t operator ()(NSString *value) const {
826 return CFStringHashNSString((CFStringRef) value);
830 struct NSStringMapLess :
831 std::binary_function<NSString *, NSString *, bool>
833 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
834 return [lhs compare:rhs] == NSOrderedAscending;
838 struct NSStringMapEqual :
839 std::binary_function<NSString *, NSString *, bool>
841 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
842 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
843 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
844 //[lhs isEqualToString:rhs];
849 /* Perl-Compatible RegEx {{{ */
859 Pcre(const char *regex) :
864 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
867 lprintf("%d:%s\n", offset, error);
871 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
872 matches_ = new int[(capture_ + 1) * 3];
880 NSString *operator [](size_t match) {
881 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
884 bool operator ()(NSString *data) {
885 // XXX: length is for characters, not for bytes
886 return operator ()([data UTF8String], [data length]);
889 bool operator ()(const char *data, size_t size) {
891 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
895 /* Mime Addresses {{{ */
896 @interface Address : NSObject {
902 - (NSString *) address;
904 - (void) setAddress:(NSString *)address;
906 + (Address *) addressWithString:(NSString *)string;
907 - (Address *) initWithString:(NSString *)string;
910 @implementation Address
919 - (NSString *) name {
923 - (NSString *) address {
927 - (void) setAddress:(NSString *)address {
929 [address_ autorelease];
933 address_ = [address retain];
936 + (Address *) addressWithString:(NSString *)string {
937 return [[[Address alloc] initWithString:string] autorelease];
940 + (NSArray *) _attributeKeys {
941 return [NSArray arrayWithObjects:@"address", @"name", nil];
944 - (NSArray *) attributeKeys {
945 return [[self class] _attributeKeys];
948 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
949 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
952 - (Address *) initWithString:(NSString *)string {
953 if ((self = [super init]) != nil) {
954 const char *data = [string UTF8String];
955 size_t size = [string length];
957 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
959 if (address_r(data, size)) {
960 name_ = [address_r[1] retain];
961 address_ = [address_r[2] retain];
963 name_ = [string retain];
971 /* CoreGraphics Primitives {{{ */
982 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
985 Set(space, red, green, blue, alpha);
990 CGColorRelease(color_);
997 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
999 float color[] = {red, green, blue, alpha};
1000 color_ = CGColorCreate(space, (CGFloat *) color);
1003 operator CGColorRef() {
1009 /* Random Global Variables {{{ */
1010 static const int PulseInterval_ = 50000;
1011 static const int ButtonBarWidth_ = 60;
1012 static const int ButtonBarHeight_ = 48;
1013 static const float KeyboardTime_ = 0.3f;
1016 static NSArray *Finishes_;
1018 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1019 #define NotifyConfig_ "/etc/notify.conf"
1021 static bool Queuing_;
1023 static CYColor Blue_;
1024 static CYColor Blueish_;
1025 static CYColor Black_;
1026 static CYColor Off_;
1027 static CYColor White_;
1028 static CYColor Gray_;
1029 static CYColor Green_;
1030 static CYColor Purple_;
1031 static CYColor Purplish_;
1033 static UIColor *InstallingColor_;
1034 static UIColor *RemovingColor_;
1036 static NSString *App_;
1037 static NSString *Home_;
1039 static BOOL Advanced_;
1040 static BOOL Ignored_;
1042 static UIFont *Font12_;
1043 static UIFont *Font12Bold_;
1044 static UIFont *Font14_;
1045 static UIFont *Font18Bold_;
1046 static UIFont *Font22Bold_;
1048 static const char *Machine_ = NULL;
1049 static NSString *System_ = nil;
1050 static NSString *SerialNumber_ = nil;
1051 static NSString *ChipID_ = nil;
1052 static NSString *Token_ = nil;
1053 static NSString *UniqueID_ = nil;
1054 static NSString *Build_ = nil;
1055 static NSString *Product_ = nil;
1056 static NSString *Safari_ = nil;
1058 static CFLocaleRef Locale_;
1059 static NSArray *Languages_;
1060 static CGColorSpaceRef space_;
1062 static NSDictionary *SectionMap_;
1063 static NSMutableDictionary *Metadata_;
1064 static _transient NSMutableDictionary *Settings_;
1065 static _transient NSString *Role_;
1066 static _transient NSMutableDictionary *Packages_;
1067 static _transient NSMutableDictionary *Sections_;
1068 static _transient NSMutableDictionary *Sources_;
1069 static bool Changed_;
1070 static NSDate *now_;
1072 static bool IsWildcat_;
1075 static NSMutableArray *Documents_;
1079 /* Display Helpers {{{ */
1080 inline float Interpolate(float begin, float end, float fraction) {
1081 return (end - begin) * fraction + begin;
1084 /* XXX: localize this! */
1085 NSString *SizeString(double size) {
1086 bool negative = size < 0;
1091 while (size > 1024) {
1096 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1098 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1101 static _finline CFStringRef CFCString(const char *value) {
1102 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1105 const char *StripVersion_(const char *version) {
1106 const char *colon(strchr(version, ':'));
1108 version = colon + 1;
1112 CFStringRef StripVersion(const char *version) {
1113 const char *colon(strchr(version, ':'));
1115 version = colon + 1;
1116 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1118 return CFCString(version);
1121 NSString *LocalizeSection(NSString *section) {
1122 static Pcre title_r("^(.*?) \\((.*)\\)$");
1123 if (title_r(section)) {
1124 NSString *parent(title_r[1]);
1125 NSString *child(title_r[2]);
1127 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1128 LocalizeSection(parent),
1129 LocalizeSection(child)
1133 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1136 NSString *Simplify(NSString *title) {
1137 const char *data = [title UTF8String];
1138 size_t size = [title length];
1140 static Pcre square_r("^\\[(.*)\\]$");
1141 if (square_r(data, size))
1142 return Simplify(square_r[1]);
1144 static Pcre paren_r("^\\((.*)\\)$");
1145 if (paren_r(data, size))
1146 return Simplify(paren_r[1]);
1148 static Pcre title_r("^(.*?) \\((.*)\\)$");
1149 if (title_r(data, size))
1150 return Simplify(title_r[1]);
1156 NSString *GetLastUpdate() {
1157 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1160 return UCLocalize("NEVER_OR_UNKNOWN");
1162 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1163 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1165 CFRelease(formatter);
1167 return [(NSString *) formatted autorelease];
1170 bool isSectionVisible(NSString *section) {
1171 NSDictionary *metadata([Sections_ objectForKey:section]);
1172 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1173 return hidden == nil || ![hidden boolValue];
1178 /* Delegate Prototypes {{{ */
1182 @interface NSObject (ProgressDelegate)
1185 @protocol ProgressDelegate
1186 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1187 - (void) setProgressTitle:(NSString *)title;
1188 - (void) setProgressPercent:(float)percent;
1189 - (void) startProgress;
1190 - (void) addProgressOutput:(NSString *)output;
1191 - (bool) isCancelling:(size_t)received;
1194 @protocol ConfigurationDelegate
1195 - (void) repairWithSelector:(SEL)selector;
1196 - (void) setConfigurationData:(NSString *)data;
1199 @class PackageController;
1201 @protocol CydiaDelegate
1202 - (void) setPackageController:(PackageController *)view;
1203 - (void) clearPackage:(Package *)package;
1204 - (void) installPackage:(Package *)package;
1205 - (void) installPackages:(NSArray *)packages;
1206 - (void) removePackage:(Package *)package;
1207 - (void) beginUpdate;
1209 - (void) distUpgrade;
1211 - (void) updateData;
1213 - (void) showSettings;
1214 - (UIProgressHUD *) addProgressHUD;
1215 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1216 - (CYViewController *) pageForPackage:(NSString *)name;
1217 - (PackageController *) packageController;
1218 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1222 /* Status Delegation {{{ */
1224 public pkgAcquireStatus
1227 _transient NSObject<ProgressDelegate> *delegate_;
1235 void setDelegate(id delegate) {
1236 delegate_ = delegate;
1239 NSObject<ProgressDelegate> *getDelegate() const {
1243 virtual bool MediaChange(std::string media, std::string drive) {
1247 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1250 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1251 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1252 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1255 virtual void Done(pkgAcquire::ItemDesc &item) {
1258 virtual void Fail(pkgAcquire::ItemDesc &item) {
1260 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1261 item.Owner->Status == pkgAcquire::Item::StatDone
1265 std::string &error(item.Owner->ErrorText);
1269 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1270 NSArray *fields([description componentsSeparatedByString:@" "]);
1271 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1273 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1274 withObject:[NSArray arrayWithObjects:
1275 [NSString stringWithUTF8String:error.c_str()],
1282 virtual bool Pulse(pkgAcquire *Owner) {
1283 bool value = pkgAcquireStatus::Pulse(Owner);
1286 double(CurrentBytes + CurrentItems) /
1287 double(TotalBytes + TotalItems)
1290 [delegate_ setProgressPercent:percent];
1291 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1294 virtual void Start() {
1295 [delegate_ startProgress];
1298 virtual void Stop() {
1302 /* Progress Delegation {{{ */
1307 _transient id<ProgressDelegate> delegate_;
1311 virtual void Update() {
1312 /*if (abs(Percent - percent_) > 2)
1313 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1317 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1318 [delegate_ setProgressPercent:(Percent / 100)];*/
1328 void setDelegate(id delegate) {
1329 delegate_ = delegate;
1332 id getDelegate() const {
1336 virtual void Done() {
1338 //[delegate_ setProgressPercent:1];
1343 /* Database Interface {{{ */
1344 typedef std::map< unsigned long, _H<Source> > SourceMap;
1346 @interface Database : NSObject {
1352 pkgCacheFile cache_;
1353 pkgDepCache::Policy *policy_;
1354 pkgRecords *records_;
1355 pkgProblemResolver *resolver_;
1356 pkgAcquire *fetcher_;
1358 SPtr<pkgPackageManager> manager_;
1359 pkgSourceList *list_;
1362 NSMutableArray *packages_;
1364 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1373 + (Database *) sharedInstance;
1376 - (void) _readCydia:(NSNumber *)fd;
1377 - (void) _readStatus:(NSNumber *)fd;
1378 - (void) _readOutput:(NSNumber *)fd;
1382 - (Package *) packageWithName:(NSString *)name;
1384 - (pkgCacheFile &) cache;
1385 - (pkgDepCache::Policy *) policy;
1386 - (pkgRecords *) records;
1387 - (pkgProblemResolver *) resolver;
1388 - (pkgAcquire &) fetcher;
1389 - (pkgSourceList &) list;
1390 - (NSArray *) packages;
1391 - (NSArray *) sources;
1392 - (void) reloadData;
1400 - (void) setVisible;
1402 - (void) updateWithStatus:(Status &)status;
1404 - (void) setDelegate:(id)delegate;
1405 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1408 /* Delegate Helpers {{{ */
1409 @implementation NSObject (ProgressDelegate)
1411 - (void) _setProgressErrorPackage:(NSArray *)args {
1412 [self performSelector:@selector(setProgressError:forPackage:)
1413 withObject:[args objectAtIndex:0]
1414 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1418 - (void) _setProgressErrorTitle:(NSArray *)args {
1419 [self performSelector:@selector(setProgressError:withTitle:)
1420 withObject:[args objectAtIndex:0]
1421 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1425 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1426 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1427 withObject:[NSArray arrayWithObjects:error, title, nil]
1432 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1433 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1435 [self performSelector:@selector(setProgressError:withTitle:)
1437 withObject:(package == nil ? id : [package name])
1444 /* Source Class {{{ */
1445 @interface Source : NSObject {
1446 CYString depiction_;
1447 CYString description_;
1453 CYString distribution_;
1458 NSString *authority_;
1460 CYString defaultIcon_;
1462 NSDictionary *record_;
1466 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1468 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1470 - (NSString *) depictionForPackage:(NSString *)package;
1471 - (NSString *) supportForPackage:(NSString *)package;
1473 - (NSDictionary *) record;
1477 - (NSString *) distribution;
1478 - (NSString *) type;
1480 - (NSString *) host;
1482 - (NSString *) name;
1483 - (NSString *) description;
1484 - (NSString *) label;
1485 - (NSString *) origin;
1486 - (NSString *) version;
1488 - (NSString *) defaultIcon;
1492 @implementation Source
1496 distribution_.clear();
1499 description_.clear();
1505 defaultIcon_.clear();
1507 if (record_ != nil) {
1517 if (authority_ != nil) {
1518 [authority_ release];
1528 + (NSArray *) _attributeKeys {
1529 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1532 - (NSArray *) attributeKeys {
1533 return [[self class] _attributeKeys];
1536 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1537 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1540 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1543 trusted_ = index->IsTrusted();
1545 uri_.set(pool, index->GetURI());
1546 distribution_.set(pool, index->GetDist());
1547 type_.set(pool, index->GetType());
1549 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1550 if (dindex != NULL) {
1552 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1555 pkgTagFile tags(&fd);
1557 pkgTagSection section;
1564 {"default-icon", &defaultIcon_},
1565 {"depiction", &depiction_},
1566 {"description", &description_},
1568 {"origin", &origin_},
1569 {"support", &support_},
1570 {"version", &version_},
1573 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1574 const char *start, *end;
1576 if (section.Find(names[i].name_, start, end)) {
1577 CYString &value(*names[i].value_);
1578 value.set(pool, start, end - start);
1584 record_ = [Sources_ objectForKey:[self key]];
1586 record_ = [record_ retain];
1588 NSURL *url([NSURL URLWithString:uri_]);
1592 host_ = [[host_ lowercaseString] retain];
1597 authority_ = [url path];
1599 if (authority_ != nil)
1600 authority_ = [authority_ retain];
1603 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1604 if ((self = [super init]) != nil) {
1605 [self setMetaIndex:index inPool:pool];
1609 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1610 NSDictionary *lhr = [self record];
1611 NSDictionary *rhr = [source record];
1614 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1616 NSString *lhs = [self name];
1617 NSString *rhs = [source name];
1619 if ([lhs length] != 0 && [rhs length] != 0) {
1620 unichar lhc = [lhs characterAtIndex:0];
1621 unichar rhc = [rhs characterAtIndex:0];
1623 if (isalpha(lhc) && !isalpha(rhc))
1624 return NSOrderedAscending;
1625 else if (!isalpha(lhc) && isalpha(rhc))
1626 return NSOrderedDescending;
1629 return [lhs compare:rhs options:LaxCompareOptions_];
1632 - (NSString *) depictionForPackage:(NSString *)package {
1633 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1636 - (NSString *) supportForPackage:(NSString *)package {
1637 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1640 - (NSDictionary *) record {
1648 - (NSString *) uri {
1652 - (NSString *) distribution {
1653 return distribution_;
1656 - (NSString *) type {
1660 - (NSString *) key {
1661 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1664 - (NSString *) host {
1668 - (NSString *) name {
1669 return origin_.empty() ? authority_ : origin_;
1672 - (NSString *) description {
1673 return description_;
1676 - (NSString *) label {
1677 return label_.empty() ? authority_ : label_;
1680 - (NSString *) origin {
1684 - (NSString *) version {
1688 - (NSString *) defaultIcon {
1689 return defaultIcon_;
1694 /* Relationship Class {{{ */
1695 @interface Relationship : NSObject {
1700 - (NSString *) type;
1702 - (NSString *) name;
1706 @implementation Relationship
1714 - (NSString *) type {
1722 - (NSString *) name {
1729 /* Package Class {{{ */
1730 @interface Package : NSObject {
1734 pkgCache::VerIterator version_;
1735 pkgCache::PkgIterator iterator_;
1736 _transient Database *database_;
1737 pkgCache::VerFileIterator file_;
1744 NSString *section$_;
1751 CYString installed_;
1757 CYString depiction_;
1768 NSMutableArray *tags_;
1771 NSArray *relationships_;
1773 NSMutableDictionary *metadata_;
1774 _transient NSDate *firstSeen_;
1775 _transient NSDate *lastSeen_;
1779 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1780 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1782 - (pkgCache::PkgIterator) iterator;
1785 - (NSString *) section;
1786 - (NSString *) simpleSection;
1788 - (NSString *) longSection;
1789 - (NSString *) shortSection;
1793 - (Address *) maintainer;
1795 - (NSString *) longDescription;
1796 - (NSString *) shortDescription;
1799 - (NSMutableDictionary *) metadata;
1801 - (BOOL) subscribed;
1804 - (NSString *) latest;
1805 - (NSString *) installed;
1806 - (BOOL) uninstalled;
1809 - (BOOL) upgradableAndEssential:(BOOL)essential;
1812 - (BOOL) unfiltered;
1816 - (BOOL) halfConfigured;
1817 - (BOOL) halfInstalled;
1819 - (NSString *) mode;
1821 - (void) setVisible;
1824 - (NSString *) name;
1826 - (NSString *) homepage;
1827 - (NSString *) depiction;
1828 - (Address *) author;
1830 - (NSString *) support;
1832 - (NSArray *) files;
1833 - (NSArray *) relationships;
1834 - (NSArray *) warnings;
1835 - (NSArray *) applications;
1837 - (Source *) source;
1838 - (NSString *) role;
1840 - (BOOL) matches:(NSString *)text;
1842 - (bool) hasSupportingRole;
1843 - (BOOL) hasTag:(NSString *)tag;
1844 - (NSString *) primaryPurpose;
1845 - (NSArray *) purposes;
1846 - (bool) isCommercial;
1848 - (CYString &) cyname;
1850 - (uint32_t) compareBySection:(NSArray *)sections;
1852 - (uint32_t) compareForChanges;
1857 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1858 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1859 - (bool) isInstalledAndVisible:(NSNumber *)number;
1860 - (bool) isVisibleInSection:(NSString *)section;
1861 - (bool) isVisibleInSource:(Source *)source;
1865 uint32_t PackageChangesRadix(Package *self, void *) {
1870 uint32_t timestamp : 30;
1871 uint32_t ignored : 1;
1872 uint32_t upgradable : 1;
1876 bool upgradable([self upgradableAndEssential:YES]);
1877 value.bits.upgradable = upgradable ? 1 : 0;
1880 value.bits.timestamp = 0;
1881 value.bits.ignored = [self ignored] ? 0 : 1;
1882 value.bits.upgradable = 1;
1884 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1885 value.bits.ignored = 0;
1886 value.bits.upgradable = 0;
1889 return _not(uint32_t) - value.key;
1892 _finline static void Stifle(uint8_t &value) {
1895 uint32_t PackagePrefixRadix(Package *self, void *context) {
1896 size_t offset(reinterpret_cast<size_t>(context));
1897 CYString &name([self cyname]);
1899 size_t size(name.size());
1902 char *text(name.data());
1905 if (!isdigit(text[0]))
1909 while (size != digits && isdigit(text[digits]))
1919 if (offset == 0 && zeros != 0) {
1920 memset(data, '0', zeros);
1921 memcpy(data + zeros, text, 4 - zeros);
1923 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1924 if (size <= offset - zeros)
1927 text += offset - zeros;
1928 size -= offset - zeros;
1931 memcpy(data, text, 4);
1933 memcpy(data, text, size);
1934 memset(data + size, 0, 4 - size);
1937 for (size_t i(0); i != 4; ++i)
1938 if (isalpha(data[i]))
1943 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1945 /* XXX: ntohl may be more honest */
1946 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1949 CYString &(*PackageName)(Package *self, SEL sel);
1951 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1952 _profile(PackageNameCompare)
1953 CYString &lhi(PackageName(lhs, @selector(cyname)));
1954 CYString &rhi(PackageName(rhs, @selector(cyname)));
1955 CFStringRef lhn(lhi), rhn(rhi);
1958 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1959 else if (rhn == NULL)
1960 return NSOrderedDescending;
1962 _profile(PackageNameCompare$NumbersLast)
1963 if (!lhi.empty() && !rhi.empty()) {
1964 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1965 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1966 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1967 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1968 return lha ? NSOrderedAscending : NSOrderedDescending;
1972 CFIndex length = CFStringGetLength(lhn);
1974 _profile(PackageNameCompare$Compare)
1975 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1980 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1981 return PackageNameCompare(*lhs, *rhs, context);
1984 struct PackageNameOrdering :
1985 std::binary_function<Package *, Package *, bool>
1987 _finline bool operator ()(Package *lhs, Package *rhs) const {
1988 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1992 @implementation Package
1994 - (NSString *) description {
1995 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2001 if (section$_ != nil)
2002 [section$_ release];
2007 if (sponsor$_ != nil)
2008 [sponsor$_ release];
2009 if (author$_ != nil)
2016 if (relationships_ != nil)
2017 [relationships_ release];
2018 if (metadata_ != nil)
2019 [metadata_ release];
2024 + (NSString *) webScriptNameForSelector:(SEL)selector {
2025 if (selector == @selector(hasTag:))
2031 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2032 return [self webScriptNameForSelector:selector] == nil;
2035 + (NSArray *) _attributeKeys {
2036 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];
2039 - (NSArray *) attributeKeys {
2040 return [[self class] _attributeKeys];
2043 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2044 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2054 _profile(Package$parse)
2055 pkgRecords::Parser *parser;
2057 _profile(Package$parse$Lookup)
2058 parser = &[database_ records]->Lookup(file_);
2063 _profile(Package$parse$Find)
2069 {"depiction", &depiction_},
2070 {"homepage", &homepage_},
2071 {"website", &website},
2073 {"support", &support_},
2074 {"sponsor", &sponsor_},
2075 {"author", &author_},
2078 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2079 const char *start, *end;
2081 if (parser->Find(names[i].name_, start, end)) {
2082 CYString &value(*names[i].value_);
2083 _profile(Package$parse$Value)
2084 value.set(pool_, start, end - start);
2090 _profile(Package$parse$Tagline)
2091 const char *start, *end;
2092 if (parser->ShortDesc(start, end)) {
2093 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2096 while (stop != start && stop[-1] == '\r')
2098 tagline_.set(pool_, start, stop - start);
2102 _profile(Package$parse$Retain)
2103 if (homepage_.empty())
2104 homepage_ = website;
2105 if (homepage_ == depiction_)
2111 - (void) setVisible {
2112 visible_ = required_ && [self unfiltered];
2115 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2116 if ((self = [super init]) != nil) {
2117 _profile(Package$initWithVersion)
2118 @synchronized (database) {
2119 era_ = [database era];
2123 iterator_ = version.ParentPkg();
2124 database_ = database;
2126 _profile(Package$initWithVersion$Latest)
2127 latest_ = (NSString *) StripVersion(version_.VerStr());
2130 pkgCache::VerIterator current;
2131 _profile(Package$initWithVersion$Versions)
2132 current = iterator_.CurrentVer();
2134 installed_.set(pool_, StripVersion_(current.VerStr()));
2136 if (!version_.end())
2137 file_ = version_.FileList();
2139 pkgCache &cache([database_ cache]);
2140 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2144 _profile(Package$initWithVersion$Name)
2145 id_.set(pool_, iterator_.Name());
2146 name_.set(pool, iterator_.Display());
2150 _profile(Package$initWithVersion$Source)
2151 source_ = [database_ getSource:file_.File()];
2160 _profile(Package$initWithVersion$Tags)
2161 pkgCache::TagIterator tag(iterator_.TagList());
2163 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2165 const char *name(tag.Name());
2166 [tags_ addObject:(NSString *)CFCString(name)];
2167 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2168 role_ = (NSString *) CFCString(name + 6);
2169 if (required_ && strncmp(name, "require::", 9) == 0 && (
2174 } while (!tag.end());
2178 bool changed(false);
2179 NSString *key([id_ lowercaseString]);
2181 _profile(Package$initWithVersion$Metadata)
2182 metadata_ = [Packages_ objectForKey:key];
2184 if (metadata_ == nil) {
2187 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2188 firstSeen_, @"FirstSeen",
2189 latest_, @"LastVersion",
2194 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2195 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2197 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2198 subscribed_ = [subscribed boolValue];
2200 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2202 if (firstSeen_ == nil) {
2203 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2204 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2208 if (version == nil) {
2209 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2211 } else if (![version isEqualToString:latest_]) {
2212 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2214 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2219 metadata_ = [metadata_ retain];
2222 [Packages_ setObject:metadata_ forKey:key];
2227 _profile(Package$initWithVersion$Section)
2228 section_.set(pool_, iterator_.Section());
2231 obsolete_ = [self hasTag:@"cydia::obsolete"];
2232 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2234 } _end } return self;
2237 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2238 @synchronized ([Database class]) {
2239 pkgCache::VerIterator version;
2241 _profile(Package$packageWithIterator$GetCandidateVer)
2242 version = [database policy]->GetCandidateVer(iterator);
2248 return [[[Package alloc]
2249 initWithVersion:version
2256 - (pkgCache::PkgIterator) iterator {
2260 - (NSString *) section {
2261 if (section$_ == nil) {
2262 if (section_.empty())
2265 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2266 NSString *name(section_);
2269 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2270 if (NSString *rename = [value objectForKey:@"Rename"]) {
2275 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2279 - (NSString *) simpleSection {
2280 if (NSString *section = [self section])
2281 return Simplify(section);
2286 - (NSString *) longSection {
2287 return LocalizeSection([self section]);
2290 - (NSString *) shortSection {
2291 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2294 - (NSString *) uri {
2297 pkgIndexFile *index;
2298 pkgCache::PkgFileIterator file(file_.File());
2299 if (![database_ list].FindIndex(file, index))
2301 return [NSString stringWithUTF8String:iterator_->Path];
2302 //return [NSString stringWithUTF8String:file.Site()];
2303 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2307 - (Address *) maintainer {
2310 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2311 const std::string &maintainer(parser->Maintainer());
2312 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2316 return version_.end() ? 0 : version_->InstalledSize;
2319 - (NSString *) longDescription {
2322 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2323 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2325 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2326 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2327 if ([lines count] < 2)
2330 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2331 for (size_t i(1), e([lines count]); i != e; ++i) {
2332 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2333 [trimmed addObject:trim];
2336 return [trimmed componentsJoinedByString:@"\n"];
2339 - (NSString *) shortDescription {
2344 _profile(Package$index)
2345 CFStringRef name((CFStringRef) [self name]);
2346 if (CFStringGetLength(name) == 0)
2348 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2349 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2351 return toupper(character);
2355 - (NSMutableDictionary *) metadata {
2360 if (subscribed_ && lastSeen_ != nil)
2365 - (BOOL) subscribed {
2370 NSDictionary *metadata([self metadata]);
2371 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2372 return [ignored boolValue];
2377 - (NSString *) latest {
2381 - (NSString *) installed {
2385 - (BOOL) uninstalled {
2386 return installed_.empty();
2390 return !version_.end();
2393 - (BOOL) upgradableAndEssential:(BOOL)essential {
2394 _profile(Package$upgradableAndEssential)
2395 pkgCache::VerIterator current(iterator_.CurrentVer());
2397 return essential && essential_ && visible_;
2399 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2403 - (BOOL) essential {
2408 return [database_ cache][iterator_].InstBroken();
2411 - (BOOL) unfiltered {
2412 NSString *section([self section]);
2413 return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
2421 unsigned char current(iterator_->CurrentState);
2422 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2425 - (BOOL) halfConfigured {
2426 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2429 - (BOOL) halfInstalled {
2430 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2434 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2435 return state.Mode != pkgDepCache::ModeKeep;
2438 - (NSString *) mode {
2439 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2441 switch (state.Mode) {
2442 case pkgDepCache::ModeDelete:
2443 if ((state.iFlags & pkgDepCache::Purge) != 0)
2447 case pkgDepCache::ModeKeep:
2448 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2449 return @"REINSTALL";
2450 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2454 case pkgDepCache::ModeInstall:
2455 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2456 return @"REINSTALL";
2457 else*/ switch (state.Status) {
2459 return @"DOWNGRADE";
2465 return @"NEW_INSTALL";
2476 - (NSString *) name {
2477 return name_.empty() ? id_ : name_;
2480 - (UIImage *) icon {
2481 NSString *section = [self simpleSection];
2485 if ([icon_ hasPrefix:@"file:///"])
2486 // XXX: correct escaping
2487 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2488 if (icon == nil) if (section != nil)
2489 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2490 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2491 if ([dicon hasPrefix:@"file:///"])
2492 // XXX: correct escaping
2493 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2495 icon = [UIImage applicationImageNamed:@"unknown.png"];
2499 - (NSString *) homepage {
2503 - (NSString *) depiction {
2504 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2507 - (Address *) sponsor {
2508 if (sponsor$_ == nil) {
2509 if (sponsor_.empty())
2511 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2515 - (Address *) author {
2516 if (author$_ == nil) {
2517 if (author_.empty())
2519 author$_ = [[Address addressWithString:author_] retain];
2523 - (NSString *) support {
2524 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2527 - (NSArray *) files {
2528 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2529 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2532 fin.open([path UTF8String]);
2537 while (std::getline(fin, line))
2538 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2543 - (NSArray *) relationships {
2544 return relationships_;
2547 - (NSArray *) warnings {
2548 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2549 const char *name(iterator_.Name());
2551 size_t length(strlen(name));
2552 if (length < 2) invalid:
2553 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2554 else for (size_t i(0); i != length; ++i)
2556 /* XXX: technically this is not allowed */
2557 (name[i] < 'A' || name[i] > 'Z') &&
2558 (name[i] < 'a' || name[i] > 'z') &&
2559 (name[i] < '0' || name[i] > '9') &&
2560 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2563 if (strcmp(name, "cydia") != 0) {
2566 bool _private = false;
2569 bool repository = [[self section] isEqualToString:@"Repositories"];
2571 if (NSArray *files = [self files])
2572 for (NSString *file in files)
2573 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2575 else if (!user && [file isEqualToString:@"/User"])
2577 else if (!_private && [file isEqualToString:@"/private"])
2579 else if (!stash && [file isEqualToString:@"/var/stash"])
2582 /* XXX: this is not sensitive enough. only some folders are valid. */
2583 if (cydia && !repository)
2584 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2586 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2588 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2590 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2593 return [warnings count] == 0 ? nil : warnings;
2596 - (NSArray *) applications {
2597 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2599 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2601 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2602 if (NSArray *files = [self files])
2603 for (NSString *file in files)
2604 if (application_r(file)) {
2605 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2606 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2607 if ([id isEqualToString:me])
2610 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2612 display = application_r[1];
2614 NSString *bundle([file stringByDeletingLastPathComponent]);
2615 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2616 if (icon == nil || [icon length] == 0)
2618 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2620 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2621 [applications addObject:application];
2623 [application addObject:id];
2624 [application addObject:display];
2625 [application addObject:url];
2628 return [applications count] == 0 ? nil : applications;
2631 - (Source *) source {
2633 @synchronized (database_) {
2634 if ([database_ era] != era_ || file_.end())
2637 source_ = [database_ getSource:file_.File()];
2649 - (NSString *) role {
2653 - (BOOL) matches:(NSString *)text {
2659 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2660 if (range.location != NSNotFound)
2663 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2664 if (range.location != NSNotFound)
2667 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2668 if (range.location != NSNotFound)
2674 - (bool) hasSupportingRole {
2677 if ([role_ isEqualToString:@"enduser"])
2679 if ([Role_ isEqualToString:@"User"])
2681 if ([role_ isEqualToString:@"hacker"])
2683 if ([Role_ isEqualToString:@"Hacker"])
2685 if ([role_ isEqualToString:@"developer"])
2687 if ([Role_ isEqualToString:@"Developer"])
2692 - (BOOL) hasTag:(NSString *)tag {
2693 return tags_ == nil ? NO : [tags_ containsObject:tag];
2696 - (NSString *) primaryPurpose {
2697 for (NSString *tag in tags_)
2698 if ([tag hasPrefix:@"purpose::"])
2699 return [tag substringFromIndex:9];
2703 - (NSArray *) purposes {
2704 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2705 for (NSString *tag in tags_)
2706 if ([tag hasPrefix:@"purpose::"])
2707 [purposes addObject:[tag substringFromIndex:9]];
2708 return [purposes count] == 0 ? nil : purposes;
2711 - (bool) isCommercial {
2712 return [self hasTag:@"cydia::commercial"];
2715 - (CYString &) cyname {
2716 return name_.empty() ? id_ : name_;
2719 - (uint32_t) compareBySection:(NSArray *)sections {
2720 NSString *section([self section]);
2721 for (size_t i(0), e([sections count]); i != e; ++i) {
2722 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2726 return _not(uint32_t);
2729 - (uint32_t) compareForChanges {
2734 uint32_t timestamp : 30;
2735 uint32_t ignored : 1;
2736 uint32_t upgradable : 1;
2740 bool upgradable([self upgradableAndEssential:YES]);
2741 value.bits.upgradable = upgradable ? 1 : 0;
2744 value.bits.timestamp = 0;
2745 value.bits.ignored = [self ignored] ? 0 : 1;
2746 value.bits.upgradable = 1;
2748 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2749 value.bits.ignored = 0;
2750 value.bits.upgradable = 0;
2753 return _not(uint32_t) - value.key;
2757 pkgProblemResolver *resolver = [database_ resolver];
2758 resolver->Clear(iterator_);
2759 resolver->Protect(iterator_);
2763 pkgProblemResolver *resolver = [database_ resolver];
2764 resolver->Clear(iterator_);
2765 resolver->Protect(iterator_);
2766 pkgCacheFile &cache([database_ cache]);
2767 cache->MarkInstall(iterator_, false);
2768 pkgDepCache::StateCache &state((*cache)[iterator_]);
2769 if (!state.Install())
2770 cache->SetReInstall(iterator_, true);
2774 pkgProblemResolver *resolver = [database_ resolver];
2775 resolver->Clear(iterator_);
2776 resolver->Protect(iterator_);
2777 resolver->Remove(iterator_);
2778 [database_ cache]->MarkDelete(iterator_, true);
2781 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2782 _profile(Package$isUnfilteredAndSearchedForBy)
2785 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2786 value &= [self unfiltered];
2789 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2790 value &= [self matches:search];
2797 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2798 if ([search length] == 0)
2801 _profile(Package$isUnfilteredAndSelectedForBy)
2804 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2805 value &= [self unfiltered];
2808 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2809 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2816 - (bool) isInstalledAndVisible:(NSNumber *)number {
2817 return (![number boolValue] || [self visible]) && ![self uninstalled];
2820 - (bool) isVisibleInSection:(NSString *)name {
2821 NSString *section = [self section];
2826 section == nil && [name length] == 0 ||
2827 [name isEqualToString:section]
2831 - (bool) isVisibleInSource:(Source *)source {
2832 return [self source] == source && [self visible];
2837 /* Section Class {{{ */
2838 @interface Section : NSObject {
2843 NSString *localized_;
2846 - (NSComparisonResult) compareByLocalized:(Section *)section;
2847 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2848 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2849 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2850 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2851 - (NSString *) name;
2858 - (void) addToCount;
2860 - (void) setCount:(size_t)count;
2861 - (NSString *) localized;
2865 @implementation Section
2869 if (localized_ != nil)
2870 [localized_ release];
2874 - (NSComparisonResult) compareByLocalized:(Section *)section {
2875 NSString *lhs(localized_);
2876 NSString *rhs([section localized]);
2878 /*if ([lhs length] != 0 && [rhs length] != 0) {
2879 unichar lhc = [lhs characterAtIndex:0];
2880 unichar rhc = [rhs characterAtIndex:0];
2882 if (isalpha(lhc) && !isalpha(rhc))
2883 return NSOrderedAscending;
2884 else if (!isalpha(lhc) && isalpha(rhc))
2885 return NSOrderedDescending;
2888 return [lhs compare:rhs options:LaxCompareOptions_];
2891 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2892 if ((self = [self initWithName:name localize:NO]) != nil) {
2893 if (localized != nil)
2894 localized_ = [localized retain];
2898 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2899 return [self initWithName:name row:0 localize:localize];
2902 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2903 if ((self = [super init]) != nil) {
2904 name_ = [name retain];
2908 localized_ = [LocalizeSection(name_) retain];
2912 /* XXX: localize the index thingees */
2913 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2914 if ((self = [super init]) != nil) {
2915 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2921 - (NSString *) name {
2941 - (void) addToCount {
2945 - (void) setCount:(size_t)count {
2949 - (NSString *) localized {
2956 static NSString *Colon_;
2957 static NSString *Error_;
2958 static NSString *Warning_;
2960 /* Database Implementation {{{ */
2961 @implementation Database
2963 + (Database *) sharedInstance {
2964 static Database *instance;
2965 if (instance == nil)
2966 instance = [[Database alloc] init];
2976 NSRecycleZone(zone_);
2977 // XXX: malloc_destroy_zone(zone_);
2978 apr_pool_destroy(pool_);
2982 - (void) _readCydia:(NSNumber *)fd { _pooled
2983 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2984 std::istream is(&ib);
2987 static Pcre finish_r("^finish:([^:]*)$");
2989 while (std::getline(is, line)) {
2990 const char *data(line.c_str());
2991 size_t size = line.size();
2992 lprintf("C:%s\n", data);
2994 if (finish_r(data, size)) {
2995 NSString *finish = finish_r[1];
2996 int index = [Finishes_ indexOfObject:finish];
2997 if (index != INT_MAX && index > Finish_)
3005 - (void) _readStatus:(NSNumber *)fd { _pooled
3006 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3007 std::istream is(&ib);
3010 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3011 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3013 while (std::getline(is, line)) {
3014 const char *data(line.c_str());
3015 size_t size(line.size());
3016 lprintf("S:%s\n", data);
3018 if (conffile_r(data, size)) {
3019 [delegate_ setConfigurationData:conffile_r[1]];
3020 } else if (strncmp(data, "status: ", 8) == 0) {
3021 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3022 [delegate_ setProgressTitle:string];
3023 } else if (pmstatus_r(data, size)) {
3024 std::string type([pmstatus_r[1] UTF8String]);
3025 NSString *id = pmstatus_r[2];
3027 float percent([pmstatus_r[3] floatValue]);
3028 [delegate_ setProgressPercent:(percent / 100)];
3030 NSString *string = pmstatus_r[4];
3032 if (type == "pmerror")
3033 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3034 withObject:[NSArray arrayWithObjects:string, id, nil]
3037 else if (type == "pmstatus") {
3038 [delegate_ setProgressTitle:string];
3039 } else if (type == "pmconffile")
3040 [delegate_ setConfigurationData:string];
3042 lprintf("E:unknown pmstatus\n");
3044 lprintf("E:unknown status\n");
3050 - (void) _readOutput:(NSNumber *)fd { _pooled
3051 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3052 std::istream is(&ib);
3055 while (std::getline(is, line)) {
3056 lprintf("O:%s\n", line.c_str());
3057 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3067 - (Package *) packageWithName:(NSString *)name {
3068 @synchronized ([Database class]) {
3069 if (static_cast<pkgDepCache *>(cache_) == NULL)
3071 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3072 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3076 if ((self = [super init]) != nil) {
3083 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3084 apr_pool_create(&pool_, NULL);
3086 packages_ = [[NSMutableArray alloc] init];
3090 _assert(pipe(fds) != -1);
3093 _config->Set("APT::Keep-Fds::", cydiafd_);
3094 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3097 detachNewThreadSelector:@selector(_readCydia:)
3099 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3102 _assert(pipe(fds) != -1);
3106 detachNewThreadSelector:@selector(_readStatus:)
3108 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3111 _assert(pipe(fds) != -1);
3112 _assert(dup2(fds[0], 0) != -1);
3113 _assert(close(fds[0]) != -1);
3115 input_ = fdopen(fds[1], "a");
3117 _assert(pipe(fds) != -1);
3118 _assert(dup2(fds[1], 1) != -1);
3119 _assert(close(fds[1]) != -1);
3122 detachNewThreadSelector:@selector(_readOutput:)
3124 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3129 - (pkgCacheFile &) cache {
3133 - (pkgDepCache::Policy *) policy {
3137 - (pkgRecords *) records {
3141 - (pkgProblemResolver *) resolver {
3145 - (pkgAcquire &) fetcher {
3149 - (pkgSourceList &) list {
3153 - (NSArray *) packages {
3157 - (NSArray *) sources {
3158 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3159 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3160 [sources addObject:i->second];
3164 - (NSArray *) issues {
3165 if (cache_->BrokenCount() == 0)
3168 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3170 for (Package *package in packages_) {
3171 if (![package broken])
3173 pkgCache::PkgIterator pkg([package iterator]);
3175 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3176 [entry addObject:[package name]];
3177 [issues addObject:entry];
3179 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3183 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3184 pkgCache::DepIterator start;
3185 pkgCache::DepIterator end;
3186 dep.GlobOr(start, end); // ++dep
3188 if (!cache_->IsImportantDep(end))
3190 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3193 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3194 [entry addObject:failure];
3195 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3197 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3198 if (Package *package = [self packageWithName:name])
3199 name = [package name];
3200 [failure addObject:name];
3202 pkgCache::PkgIterator target(start.TargetPkg());
3203 if (target->ProvidesList != 0)
3204 [failure addObject:@"?"];
3206 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3208 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3209 else if (!cache_[target].CandidateVerIter(cache_).end())
3210 [failure addObject:@"-"];
3211 else if (target->ProvidesList == 0)
3212 [failure addObject:@"!"];
3214 [failure addObject:@"%"];
3218 if (start.TargetVer() != 0)
3219 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3230 - (bool) popErrorWithTitle:(NSString *)title {
3232 std::string message;
3234 while (!_error->empty()) {
3236 bool warning(!_error->PopMessage(error));
3240 size_t size(error.size());
3241 if (size == 0 || error[size - 1] != '\n')
3243 error.resize(size - 1);
3245 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3247 if (!message.empty())
3252 if (fatal && !message.empty())
3253 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3258 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3259 return [self popErrorWithTitle:title] || !success;
3262 - (void) reloadData { _pooled
3263 @synchronized ([Database class]) {
3264 @synchronized (self) {
3268 [packages_ removeAllObjects];
3294 apr_pool_clear(pool_);
3295 NSRecycleZone(zone_);
3297 int chk(creat("/tmp/cydia.chk", 0644));
3301 NSString *title(UCLocalize("DATABASE"));
3304 if (!cache_.Open(progress_, true)) { pop:
3306 bool warning(!_error->PopMessage(error));
3307 lprintf("cache_.Open():[%s]\n", error.c_str());
3309 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3310 [delegate_ repairWithSelector:@selector(configure)];
3311 else if (error == "The package lists or status file could not be parsed or opened.")
3312 [delegate_ repairWithSelector:@selector(update)];
3313 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3314 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3315 // else if (error == "The list of sources could not be read.")
3317 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3326 unlink("/tmp/cydia.chk");
3328 now_ = [[NSDate date] retain];
3330 policy_ = new pkgDepCache::Policy();
3331 records_ = new pkgRecords(cache_);
3332 resolver_ = new pkgProblemResolver(cache_);
3333 fetcher_ = new pkgAcquire(&status_);
3336 list_ = new pkgSourceList();
3337 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3340 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3341 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3345 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3348 if (cache_->BrokenCount() != 0) {
3349 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3352 if (cache_->BrokenCount() != 0) {
3353 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3357 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3363 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3364 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3365 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3366 // XXX: this could be more intelligent
3367 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3368 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3370 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3377 /*std::vector<Package *> packages;
3378 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3379 [packages_ release];
3384 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3385 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3386 //packages.push_back(package);
3387 [packages_ addObject:package];
3391 /*if (packages.empty())
3392 packages_ = [[NSArray alloc] init];
3394 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3397 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3398 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3399 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3407 /*if (!packages.empty())
3408 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3409 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3411 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3413 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3415 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3421 - (void) configure {
3422 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3423 system([dpkg UTF8String]);
3427 // XXX: I don't remember this condition
3432 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3434 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3436 if ([self popErrorWithTitle:title])
3440 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3443 public pkgArchiveCleaner
3446 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3451 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3458 fetcher_->Shutdown();
3460 pkgRecords records(cache_);
3462 lock_ = new FileFd();
3463 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3465 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3467 if ([self popErrorWithTitle:title])
3471 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3474 manager_ = (_system->CreatePM(cache_));
3475 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3482 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3484 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3486 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3488 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3489 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3492 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3497 bool failed = false;
3498 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3499 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3501 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3504 std::string uri = (*item)->DescURI();
3505 std::string error = (*item)->ErrorText;
3507 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3510 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3511 withObject:[NSArray arrayWithObjects:
3512 [NSString stringWithUTF8String:error.c_str()],
3524 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3526 if (_error->PendingError()) {
3531 if (result == pkgPackageManager::Failed) {
3536 if (result != pkgPackageManager::Completed) {
3541 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3543 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3545 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3546 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3549 if (![before isEqualToArray:after])
3554 NSString *title(UCLocalize("UPGRADE"));
3555 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3561 [self updateWithStatus:status_];
3564 - (void) setVisible {
3565 for (Package *package in packages_)
3566 [package setVisible];
3569 - (void) updateWithStatus:(Status &)status {
3570 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3571 NSString *title(UCLocalize("REFRESHING_DATA"));
3574 if (!list.ReadMainList())
3575 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3578 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3579 if ([self popErrorWithTitle:title])
3582 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3583 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3584 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3586 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3590 - (void) setDelegate:(id)delegate {
3591 delegate_ = delegate;
3592 status_.setDelegate(delegate);
3593 progress_.setDelegate(delegate);
3596 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3597 SourceMap::const_iterator i(sources_.find(file->ID));
3598 return i == sources_.end() ? nil : i->second;
3604 /* Confirmation Controller {{{ */
3605 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3606 if (!iterator.end())
3607 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3608 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3610 pkgCache::PkgIterator package(dep.TargetPkg());
3613 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3621 /* Web Scripting {{{ */
3622 @interface CydiaObject : NSObject {
3627 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3630 @implementation CydiaObject
3633 [indirect_ release];
3637 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3638 if ((self = [super init]) != nil) {
3639 indirect_ = [indirect retain];
3643 - (void) setDelegate:(id)delegate {
3644 delegate_ = delegate;
3647 + (NSArray *) _attributeKeys {
3648 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3651 - (NSArray *) attributeKeys {
3652 return [[self class] _attributeKeys];
3655 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3656 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3659 - (NSString *) device {
3660 return [[UIDevice currentDevice] uniqueIdentifier];
3663 #if 0 // XXX: implement!
3664 - (NSString *) mac {
3665 if (![indirect_ promptForSensitive:@"Mac Address"])
3669 - (NSString *) serial {
3670 if (![indirect_ promptForSensitive:@"Serial #"])
3674 - (NSString *) firewire {
3675 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3679 - (NSString *) imei {
3680 if (![indirect_ promptForSensitive:@"IMEI"])
3685 + (NSString *) webScriptNameForSelector:(SEL)selector {
3686 if (selector == @selector(close))
3688 else if (selector == @selector(getInstalledPackages))
3689 return @"getInstalledPackages";
3690 else if (selector == @selector(getPackageById:))
3691 return @"getPackageById";
3692 else if (selector == @selector(installPackages:))
3693 return @"installPackages";
3694 else if (selector == @selector(setAutoPopup:))
3695 return @"setAutoPopup";
3696 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3697 return @"setButtonImage";
3698 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3699 return @"setButtonTitle";
3700 else if (selector == @selector(setFinishHook:))
3701 return @"setFinishHook";
3702 else if (selector == @selector(setPopupHook:))
3703 return @"setPopupHook";
3704 else if (selector == @selector(setSpecial:))
3705 return @"setSpecial";
3706 else if (selector == @selector(setToken:))
3708 else if (selector == @selector(setViewportWidth:))
3709 return @"setViewportWidth";
3710 else if (selector == @selector(supports:))
3712 else if (selector == @selector(stringWithFormat:arguments:))
3714 else if (selector == @selector(localizedStringForKey:value:table:))
3716 else if (selector == @selector(du:))
3718 else if (selector == @selector(statfs:))
3724 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3725 return [self webScriptNameForSelector:selector] == nil;
3728 - (BOOL) supports:(NSString *)feature {
3729 return [feature isEqualToString:@"window.open"];
3732 - (NSArray *) getInstalledPackages {
3733 NSArray *packages([[Database sharedInstance] packages]);
3734 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3735 for (Package *package in packages)
3736 if ([package installed] != nil)
3737 [installed addObject:package];
3741 - (Package *) getPackageById:(NSString *)id {
3742 Package *package([[Database sharedInstance] packageWithName:id]);
3747 - (NSArray *) statfs:(NSString *)path {
3750 if (path == nil || statfs([path UTF8String], &stat) == -1)
3753 return [NSArray arrayWithObjects:
3754 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3755 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3756 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3760 - (NSNumber *) du:(NSString *)path {
3761 NSNumber *value(nil);
3764 _assert(pipe(fds) != -1);
3766 pid_t pid(ExecFork());
3768 _assert(dup2(fds[1], 1) != -1);
3769 _assert(close(fds[0]) != -1);
3770 _assert(close(fds[1]) != -1);
3771 /* XXX: this should probably not use du */
3772 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3777 _assert(close(fds[1]) != -1);
3779 if (FILE *du = fdopen(fds[0], "r")) {
3781 while (fgets(line, sizeof(line), du) != NULL) {
3782 size_t length(strlen(line));
3783 while (length != 0 && line[length - 1] == '\n')
3784 line[--length] = '\0';
3785 if (char *tab = strchr(line, '\t')) {
3787 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3792 } else _assert(close(fds[0]));
3796 if (waitpid(pid, &status, 0) == -1)
3799 else _assert(false);
3808 - (void) installPackages:(NSArray *)packages {
3809 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3812 - (void) setAutoPopup:(BOOL)popup {
3813 [indirect_ setAutoPopup:popup];
3816 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3817 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3820 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3821 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3824 - (void) setSpecial:(id)function {
3825 [indirect_ setSpecial:function];
3828 - (void) setToken:(NSString *)token {
3831 Token_ = [token retain];
3833 [Metadata_ setObject:Token_ forKey:@"Token"];
3837 - (void) setFinishHook:(id)function {
3838 [indirect_ setFinishHook:function];
3841 - (void) setPopupHook:(id)function {
3842 [indirect_ setPopupHook:function];
3845 - (void) setViewportWidth:(float)width {
3846 [indirect_ setViewportWidth:width];
3849 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3850 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3851 unsigned count([arguments count]);
3853 for (unsigned i(0); i != count; ++i)
3854 values[i] = [arguments objectAtIndex:i];
3855 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3858 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3859 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3861 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3863 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3869 /* Cydia Browser Controller {{{ */
3870 @interface CYBrowserController : BrowserController {
3871 CydiaObject *cydia_;
3876 @implementation CYBrowserController
3883 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3886 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3887 [super webView:sender didClearWindowObject:window forFrame:frame];
3889 WebDataSource *source([frame dataSource]);
3890 NSURLResponse *response([source response]);
3891 NSURL *url([response URL]);
3892 NSString *scheme([url scheme]);
3894 NSHTTPURLResponse *http;
3895 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3896 http = (NSHTTPURLResponse *) response;
3900 NSDictionary *headers([http allHeaderFields]);
3901 NSString *host([url host]);
3902 [self setHeaders:headers forHost:host];
3905 [host isEqualToString:@"cydia.saurik.com"] ||
3906 [host hasSuffix:@".cydia.saurik.com"] ||
3907 [scheme isEqualToString:@"file"]
3909 [window setValue:cydia_ forKey:@"cydia"];
3912 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3913 if (System_ != NULL)
3914 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3915 if (Machine_ != NULL)
3916 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3918 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3920 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3923 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3924 NSMutableURLRequest *copy = [request mutableCopy];
3925 [self _setMoreHeaders:copy];
3929 - (void) setDelegate:(id)delegate {
3930 [super setDelegate:delegate];
3931 [cydia_ setDelegate:delegate];
3935 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3936 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3938 WebView *webview([document_ webView]);
3940 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3942 NSString *application = package == nil ? @"Cydia" : [NSString
3943 stringWithFormat:@"Cydia/%@",
3948 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3950 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3951 if (Product_ != nil)
3952 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3954 [webview setApplicationNameForUserAgent:application];
3961 /* Confirmation {{{ */
3962 @protocol ConfirmationControllerDelegate
3963 - (void) cancelAndClear:(bool)clear;
3964 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3968 @interface ConfirmationController : CYBrowserController {
3969 _transient Database *database_;
3970 UIAlertView *essential_;
3977 - (id) initWithDatabase:(Database *)database;
3981 @implementation ConfirmationController
3988 if (essential_ != nil)
3989 [essential_ release];
3993 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3994 NSString *context([alert context]);
3996 if ([context isEqualToString:@"remove"]) {
3997 if (button == [alert cancelButtonIndex]) {
3998 [self dismissModalViewControllerAnimated:YES];
3999 } else if (button == [alert firstOtherButtonIndex]) {
4002 [delegate_ confirmWithNavigationController:[self navigationController]];
4005 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4006 } else if ([context isEqualToString:@"unable"]) {
4007 [self dismissModalViewControllerAnimated:YES];
4008 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4010 [super alertView:alert clickedButtonAtIndex:button];
4014 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4015 [self dismissModalViewControllerAnimated:YES];
4016 [delegate_ cancelAndClear:NO];
4021 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4022 [super webView:sender didClearWindowObject:window forFrame:frame];
4023 [window setValue:changes_ forKey:@"changes"];
4024 [window setValue:issues_ forKey:@"issues"];
4025 [window setValue:sizes_ forKey:@"sizes"];
4026 [window setValue:self forKey:@"queue"];
4029 - (id) initWithDatabase:(Database *)database {
4030 if ((self = [super init]) != nil) {
4031 database_ = database;
4033 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4035 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4036 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4037 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4038 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4039 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4043 pkgDepCache::Policy *policy([database_ policy]);
4045 pkgCacheFile &cache([database_ cache]);
4046 NSArray *packages = [database_ packages];
4047 for (Package *package in packages) {
4048 pkgCache::PkgIterator iterator = [package iterator];
4049 pkgDepCache::StateCache &state(cache[iterator]);
4051 NSString *name([package name]);
4053 if (state.NewInstall())
4054 [installing addObject:name];
4055 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4056 [reinstalling addObject:name];
4057 else if (state.Upgrade())
4058 [upgrading addObject:name];
4059 else if (state.Downgrade())
4060 [downgrading addObject:name];
4061 else if (state.Delete()) {
4062 if ([package essential])
4064 [removing addObject:name];
4067 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4068 substrate_ |= DepSubstrate(iterator.CurrentVer());
4073 else if (Advanced_) {
4074 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4076 essential_ = [[UIAlertView alloc]
4077 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4078 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4080 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4081 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4084 [essential_ setContext:@"remove"];
4086 essential_ = [[UIAlertView alloc]
4087 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4088 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4090 cancelButtonTitle:UCLocalize("OKAY")
4091 otherButtonTitles:nil
4094 [essential_ setContext:@"unable"];
4097 changes_ = [[NSArray alloc] initWithObjects:
4105 issues_ = [database_ issues];
4107 issues_ = [issues_ retain];
4109 sizes_ = [[NSArray alloc] initWithObjects:
4110 SizeString([database_ fetcher].FetchNeeded()),
4111 SizeString([database_ fetcher].PartialPresent()),
4114 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4116 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
4117 initWithTitle:UCLocalize("CANCEL")
4118 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4119 style:UIBarButtonItemStylePlain
4121 action:@selector(cancelButtonClicked)
4123 [[self navigationItem] setLeftBarButtonItem:leftItem];
4128 - (void) applyRightButton {
4129 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
4130 initWithTitle:UCLocalize("CONFIRM")
4131 style:UIBarButtonItemStylePlain
4133 action:@selector(confirmButtonClicked)
4135 #if !AlwaysReload && !IgnoreInstall
4136 if (issues_ == nil && ![self isLoading]) [[self navigationItem] setRightBarButtonItem:rightItem];
4137 else [super applyRightButton];
4139 [[self navigationItem] setRightBarButtonItem:nil];
4141 [rightItem release];
4144 - (void) cancelButtonClicked {
4145 [self dismissModalViewControllerAnimated:YES];
4146 [delegate_ cancelAndClear:YES];
4150 - (void) confirmButtonClicked {
4154 if (essential_ != nil)
4159 [delegate_ confirmWithNavigationController:[self navigationController]];
4167 /* Progress Data {{{ */
4168 @interface ProgressData : NSObject {
4174 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4181 @implementation ProgressData
4183 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4184 if ((self = [super init]) != nil) {
4185 selector_ = selector;
4205 /* Progress Controller {{{ */
4206 @interface ProgressController : CYViewController <
4207 ConfigurationDelegate,
4210 _transient Database *database_;
4211 UIProgressBar *progress_;
4212 UITextView *output_;
4213 UITextLabel *status_;
4214 UIPushButton *close_;
4216 SHA1SumValue springlist_;
4217 SHA1SumValue notifyconf_;
4221 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4223 - (void) _retachThread;
4224 - (void) _detachNewThreadData:(ProgressData *)data;
4225 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4231 @protocol ProgressControllerDelegate
4232 - (void) progressControllerIsComplete:(ProgressController *)sender;
4235 @implementation ProgressController
4238 [database_ setDelegate:nil];
4239 [progress_ release];
4248 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4249 if ((self = [super init]) != nil) {
4250 database_ = database;
4251 [database_ setDelegate:self];
4252 delegate_ = delegate;
4254 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4256 progress_ = [[UIProgressBar alloc] init];
4257 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4258 [progress_ setStyle:0];
4260 status_ = [[UITextLabel alloc] init];
4261 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4262 [status_ setColor:[UIColor whiteColor]];
4263 [status_ setBackgroundColor:[UIColor clearColor]];
4264 [status_ setCentersHorizontally:YES];
4265 //[status_ setFont:font];
4267 output_ = [[UITextView alloc] init];
4269 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4270 //[output_ setTextFont:@"Courier New"];
4271 [output_ setFont:[[output_ font] fontWithSize:12]];
4272 [output_ setTextColor:[UIColor whiteColor]];
4273 [output_ setBackgroundColor:[UIColor clearColor]];
4274 [output_ setMarginTop:0];
4275 [output_ setAllowsRubberBanding:YES];
4276 [output_ setEditable:NO];
4277 [[self view] addSubview:output_];
4279 close_ = [[UIPushButton alloc] init];
4280 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4281 [close_ setAutosizesToFit:NO];
4282 [close_ setDrawsShadow:YES];
4283 [close_ setStretchBackground:YES];
4284 [close_ setEnabled:YES];
4285 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4286 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4287 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4288 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4292 - (void) positionViews {
4293 CGRect bounds = [[self view] bounds];
4294 CGSize prgsize = [UIProgressBar defaultSize];
4297 (bounds.size.width - prgsize.width) / 2,
4298 bounds.size.height - prgsize.height - 64
4301 float closewidth = bounds.size.width - 20;
4302 if (closewidth > 300) closewidth = 300;
4304 [progress_ setFrame:prgrect];
4305 [status_ setFrame:CGRectMake(
4307 bounds.size.height - prgsize.height - 94,
4308 bounds.size.width - 20,
4311 [output_ setFrame:CGRectMake(
4314 bounds.size.width - 20,
4315 bounds.size.height - 106
4317 [close_ setFrame:CGRectMake(
4318 (bounds.size.width - closewidth) / 2,
4319 bounds.size.height - prgsize.height - 94,
4325 - (void) viewWillAppear:(BOOL)animated {
4326 [super viewDidAppear:animated];
4327 [[self navigationItem] setHidesBackButton:YES];
4328 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4330 [self positionViews];
4333 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4334 [self positionViews];
4337 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4338 NSString *context([alert context]);
4340 if ([context isEqualToString:@"conffile"]) {
4341 FILE *input = [database_ input];
4342 if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
4343 else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
4348 - (void) closeButtonPushed {
4351 UpdateExternalStatus(0);
4355 [self dismissModalViewControllerAnimated:YES];
4359 [delegate_ terminateWithSuccess];
4360 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4361 [delegate_ suspendWithAnimation:YES];
4363 [delegate_ suspend];*/
4367 system("launchctl stop com.apple.SpringBoard");
4371 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4380 - (void) _retachThread {
4381 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4383 [[self view] addSubview:close_];
4384 [progress_ removeFromSuperview];
4385 [status_ removeFromSuperview];
4387 [database_ popErrorWithTitle:title_];
4388 [delegate_ progressControllerIsComplete:self];
4392 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4395 MMap mmap(file, MMap::ReadOnly);
4397 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4398 if (!(notifyconf_ == sha1.Result()))
4405 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4408 MMap mmap(file, MMap::ReadOnly);
4410 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4411 if (!(springlist_ == sha1.Result()))
4417 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4418 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4419 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4420 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4421 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4424 system("su -c /usr/bin/uicache mobile");
4426 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4428 [delegate_ setStatusBarShowsProgress:NO];
4431 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4432 [[data target] performSelector:[data selector] withObject:[data object]];
4435 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4438 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4439 UpdateExternalStatus(1);
4446 title_ = [title retain];
4448 [[self navigationItem] setTitle:title_];
4450 [status_ setText:nil];
4451 [output_ setText:@""];
4452 [progress_ setProgress:0];
4454 [close_ removeFromSuperview];
4455 [[self view] addSubview:progress_];
4456 [[self view] addSubview:status_];
4458 [delegate_ setStatusBarShowsProgress:YES];
4463 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4466 MMap mmap(file, MMap::ReadOnly);
4468 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4469 notifyconf_ = sha1.Result();
4475 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4478 MMap mmap(file, MMap::ReadOnly);
4480 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4481 springlist_ = sha1.Result();
4486 detachNewThreadSelector:@selector(_detachNewThreadData:)
4488 withObject:[[ProgressData alloc]
4489 initWithSelector:selector
4496 - (void) repairWithSelector:(SEL)selector {
4498 detachNewThreadSelector:selector
4501 title:UCLocalize("REPAIRING")
4505 - (void) setConfigurationData:(NSString *)data {
4507 performSelectorOnMainThread:@selector(_setConfigurationData:)
4513 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4514 CYActionSheet *sheet([[[CYActionSheet alloc]
4516 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4517 defaultButtonIndex:0
4520 [sheet setMessage:error];
4521 [sheet yieldToPopupAlertAnimated:YES];
4525 - (void) setProgressTitle:(NSString *)title {
4527 performSelectorOnMainThread:@selector(_setProgressTitle:)
4533 - (void) setProgressPercent:(float)percent {
4535 performSelectorOnMainThread:@selector(_setProgressPercent:)
4536 withObject:[NSNumber numberWithFloat:percent]
4541 - (void) startProgress {
4544 - (void) addProgressOutput:(NSString *)output {
4546 performSelectorOnMainThread:@selector(_addProgressOutput:)
4552 - (bool) isCancelling:(size_t)received {
4556 - (void) _setConfigurationData:(NSString *)data {
4557 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4559 if (!conffile_r(data)) {
4560 lprintf("E:invalid conffile\n");
4564 NSString *ofile = conffile_r[1];
4565 //NSString *nfile = conffile_r[2];
4567 UIAlertView *alert = [[[UIAlertView alloc]
4568 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4569 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4571 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4572 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4573 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4577 [alert setContext:@"conffile"];
4581 - (void) _setProgressTitle:(NSString *)title {
4582 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4583 for (size_t i(0), e([words count]); i != e; ++i) {
4584 NSString *word([words objectAtIndex:i]);
4585 if (Package *package = [database_ packageWithName:word])
4586 [words replaceObjectAtIndex:i withObject:[package name]];
4589 [status_ setText:[words componentsJoinedByString:@" "]];
4592 - (void) _setProgressPercent:(NSNumber *)percent {
4593 [progress_ setProgress:[percent floatValue]];
4596 - (void) _addProgressOutput:(NSString *)output {
4597 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4598 CGSize size = [output_ contentSize];
4599 CGRect rect = {{0, size.height}, {size.width, 0}};
4600 [output_ scrollRectToVisible:rect animated:YES];
4603 - (BOOL) isRunning {
4610 /* Cell Content View {{{ */
4611 @protocol ContentDelegate
4612 - (void) drawContentRect:(CGRect)rect;
4615 @interface ContentView : UIView {
4616 _transient id<ContentDelegate> delegate_;
4621 @implementation ContentView
4622 - (id) initWithFrame:(CGRect)frame {
4623 if ((self = [super initWithFrame:frame]) != nil) {
4624 /* Fix landscape stretching. */
4625 [self setNeedsDisplayOnBoundsChange:YES];
4629 - (void) setDelegate:(id<ContentDelegate>)delegate {
4630 delegate_ = delegate;
4633 - (void) drawRect:(CGRect)rect {
4634 [super drawRect:rect];
4635 [delegate_ drawContentRect:rect];
4639 /* Package Cell {{{ */
4640 @interface PackageCell : UITableViewCell <
4645 NSString *description_;
4651 ContentView *content_;
4657 - (PackageCell *) init;
4658 - (void) setPackage:(Package *)package;
4660 + (int) heightForPackage:(Package *)package;
4661 - (void) drawContentRect:(CGRect)rect;
4665 @implementation PackageCell
4667 - (void) clearPackage {
4678 if (description_ != nil) {
4679 [description_ release];
4683 if (source_ != nil) {
4688 if (badge_ != nil) {
4693 if (placard_ != nil) {
4703 [self clearPackage];
4710 return faded_ ? [self selectionPercent] : fade_;
4713 - (PackageCell *) init {
4714 CGRect frame(CGRectMake(0, 0, 320, 74));
4715 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4716 UIView *content([self contentView]);
4717 CGRect bounds([content bounds]);
4719 content_ = [[ContentView alloc] initWithFrame:bounds];
4720 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4721 [content addSubview:content_];
4723 [content_ setDelegate:self];
4724 [content_ setOpaque:YES];
4725 if ([self respondsToSelector:@selector(selectionPercent)])
4730 - (void) _setBackgroundColor {
4732 if (NSString *mode = [package_ mode]) {
4733 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4734 color = remove ? RemovingColor_ : InstallingColor_;
4736 color = [UIColor whiteColor];
4738 [content_ setBackgroundColor:color];
4739 [self setNeedsDisplay];
4742 - (void) setPackage:(Package *)package {
4743 [self clearPackage];
4746 Source *source = [package source];
4748 icon_ = [[package icon] retain];
4749 name_ = [[package name] retain];
4752 description_ = [package longDescription];
4753 if (description_ == nil)
4754 description_ = [package shortDescription];
4755 if (description_ != nil)
4756 description_ = [description_ retain];
4758 commercial_ = [package isCommercial];
4760 package_ = [package retain];
4762 NSString *label = nil;
4763 bool trusted = false;
4765 if (source != nil) {
4766 label = [source label];
4767 trusted = [source trusted];
4768 } else if ([[package id] isEqualToString:@"firmware"])
4769 label = UCLocalize("APPLE");
4771 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4773 NSString *from(label);
4775 NSString *section = [package simpleSection];
4776 if (section != nil && ![section isEqualToString:label]) {
4777 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4778 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4781 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4782 source_ = [from retain];
4784 if (NSString *purpose = [package primaryPurpose])
4785 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4786 badge_ = [badge_ retain];
4788 if ([package installed] != nil)
4789 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4790 placard_ = [placard_ retain];
4792 [self _setBackgroundColor];
4793 [content_ setNeedsDisplay];
4796 - (void) drawContentRect:(CGRect)rect {
4797 bool selected([self isSelected]);
4798 float width([self bounds].size.width);
4801 CGContextRef context(UIGraphicsGetCurrentContext());
4802 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4803 CGContextFillRect(context, rect);
4808 rect.size = [icon_ size];
4810 rect.size.width /= 2;
4811 rect.size.height /= 2;
4813 rect.origin.x = 25 - rect.size.width / 2;
4814 rect.origin.y = 25 - rect.size.height / 2;
4816 [icon_ drawInRect:rect];
4819 if (badge_ != nil) {
4820 CGSize size = [badge_ size];
4822 [badge_ drawAtPoint:CGPointMake(
4823 36 - size.width / 2,
4824 36 - size.height / 2
4832 UISetColor(commercial_ ? Purple_ : Black_);
4833 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4834 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4837 UISetColor(commercial_ ? Purplish_ : Gray_);
4838 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4840 if (placard_ != nil)
4841 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4844 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4845 //[self _setBackgroundColor];
4846 [super setSelected:selected animated:fade];
4847 [content_ setNeedsDisplay];
4850 + (int) heightForPackage:(Package *)package {
4856 /* Section Cell {{{ */
4857 @interface SectionCell : UITableViewCell <
4865 ContentView *content_;
4870 - (void) setSection:(Section *)section editing:(BOOL)editing;
4874 @implementation SectionCell
4876 - (void) clearSection {
4877 if (basic_ != nil) {
4882 if (section_ != nil) {
4892 if (count_ != nil) {
4899 [self clearSection];
4907 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4908 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4909 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4910 switch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4911 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4913 UIView *content([self contentView]);
4914 CGRect bounds([content bounds]);
4916 content_ = [[ContentView alloc] initWithFrame:bounds];
4917 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4918 [content addSubview:content_];
4919 [content_ setBackgroundColor:[UIColor whiteColor]];
4921 [content_ setDelegate:self];
4925 - (void) onSwitch:(id)sender {
4926 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4927 if (metadata == nil) {
4928 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4929 [Sections_ setObject:metadata forKey:basic_];
4933 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4936 - (void) setSection:(Section *)section editing:(BOOL)editing {
4937 if (editing != editing_) {
4939 [switch_ removeFromSuperview];
4941 [self addSubview:switch_];
4945 [self clearSection];
4947 if (section == nil) {
4948 name_ = [UCLocalize("ALL_PACKAGES") retain];
4951 basic_ = [section name];
4953 basic_ = [basic_ retain];
4955 section_ = [section localized];
4956 if (section_ != nil)
4957 section_ = [section_ retain];
4959 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4960 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4963 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4966 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4967 [content_ setNeedsDisplay];
4970 - (void) setFrame:(CGRect)frame {
4971 [super setFrame:frame];
4973 CGRect rect([switch_ frame]);
4974 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4977 - (void) drawContentRect:(CGRect)rect {
4978 BOOL selected = [self isSelected];
4980 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4988 float width(rect.size.width);
4992 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4994 CGSize size = [count_ sizeWithFont:Font14_];
4998 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5004 /* File Table {{{ */
5005 @interface FileTable : CYViewController <
5006 UITableViewDataSource,
5009 _transient Database *database_;
5012 NSMutableArray *files_;
5016 - (id) initWithDatabase:(Database *)database;
5017 - (void) setPackage:(Package *)package;
5021 @implementation FileTable
5024 if (package_ != nil)
5033 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5034 return files_ == nil ? 0 : [files_ count];
5037 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5041 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5042 static NSString *reuseIdentifier = @"Cell";
5044 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5046 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5047 [cell setFont:[UIFont systemFontOfSize:16]];
5049 [cell setText:[files_ objectAtIndex:indexPath.row]];
5050 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5055 - (id) initWithDatabase:(Database *)database {
5056 if ((self = [super init]) != nil) {
5057 database_ = database;
5059 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5061 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5063 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5064 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5065 [list_ setRowHeight:24.0f];
5066 [[self view] addSubview:list_];
5068 [list_ setDataSource:self];
5069 [list_ setDelegate:self];
5073 - (void) setPackage:(Package *)package {
5074 if (package_ != nil) {
5075 [package_ autorelease];
5084 [files_ removeAllObjects];
5086 if (package != nil) {
5087 package_ = [package retain];
5088 name_ = [[package id] retain];
5090 if (NSArray *files = [package files])
5091 [files_ addObjectsFromArray:files];
5093 if ([files_ count] != 0) {
5094 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5095 [files_ removeObjectAtIndex:0];
5096 [files_ sortUsingSelector:@selector(compareByPath:)];
5098 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5099 [stack addObject:@"/"];
5101 for (int i(0), e([files_ count]); i != e; ++i) {
5102 NSString *file = [files_ objectAtIndex:i];
5103 while (![file hasPrefix:[stack lastObject]])
5104 [stack removeLastObject];
5105 NSString *directory = [stack lastObject];
5106 [stack addObject:[file stringByAppendingString:@"/"]];
5107 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5108 ([stack count] - 2) * 3, "",
5109 [file substringFromIndex:[directory length]]
5118 - (void) reloadData {
5119 [self setPackage:[database_ packageWithName:name_]];
5124 /* Package Controller {{{ */
5125 @interface PackageController : CYBrowserController <
5126 UIActionSheetDelegate
5128 _transient Database *database_;
5132 NSMutableArray *buttons_;
5135 - (id) initWithDatabase:(Database *)database;
5136 - (void) setPackage:(Package *)package;
5140 @implementation PackageController
5143 if (package_ != nil)
5152 if ([self retainCount] == 1)
5153 [delegate_ setPackageController:self];
5157 /* XXX: this is not safe at all... localization of /fail/ */
5158 - (void) _clickButtonWithName:(NSString *)name {
5159 if ([name isEqualToString:UCLocalize("CLEAR")])
5160 [delegate_ clearPackage:package_];
5161 else if ([name isEqualToString:UCLocalize("INSTALL")])
5162 [delegate_ installPackage:package_];
5163 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5164 [delegate_ installPackage:package_];
5165 else if ([name isEqualToString:UCLocalize("REMOVE")])
5166 [delegate_ removePackage:package_];
5167 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5168 [delegate_ installPackage:package_];
5169 else _assert(false);
5172 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5173 NSString *context([sheet context]);
5175 if ([context isEqualToString:@"modify"]) {
5176 if (button != [sheet cancelButtonIndex]) {
5177 NSString *buttonName = [buttons_ objectAtIndex:button];
5178 [self _clickButtonWithName:buttonName];
5181 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5185 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
5186 return [super webView:sender didFinishLoadForFrame:frame];
5189 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5190 [super webView:sender didClearWindowObject:window forFrame:frame];
5191 [window setValue:package_ forKey:@"package"];
5194 - (bool) _allowJavaScriptPanel {
5199 - (void) _customButtonClicked {
5200 int count([buttons_ count]);
5205 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5207 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5208 [buttons addObjectsFromArray:buttons_];
5210 UIActionSheet *sheet = [[[UIActionSheet alloc]
5213 cancelButtonTitle:nil
5214 destructiveButtonTitle:nil
5215 otherButtonTitles:nil
5218 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5220 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5221 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5223 [sheet setContext:@"modify"];
5225 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5229 // We don't want to allow non-commercial packages to do custom things to the install button,
5230 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5231 - (void) customButtonClicked {
5233 [super customButtonClicked];
5235 [self _customButtonClicked];
5238 - (void) reloadButtonClicked {
5239 // Don't reload a package view by clicking the button.
5242 - (void) applyLoadingTitle {
5243 // Don't show "Loading" as the title. Ever.
5246 - (UIBarButtonItem *) rightButton {
5247 int count = [buttons_ count];
5248 return [[[UIBarButtonItem alloc]
5249 initWithTitle:count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0]
5250 style:UIBarButtonItemStylePlain
5252 action:@selector(customButtonClicked)
5257 - (id) initWithDatabase:(Database *)database {
5258 if ((self = [super init]) != nil) {
5259 database_ = database;
5260 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5261 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5265 - (void) setPackage:(Package *)package {
5266 if (package_ != nil) {
5267 [package_ autorelease];
5276 [buttons_ removeAllObjects];
5278 if (package != nil) {
5281 package_ = [package retain];
5282 name_ = [[package id] retain];
5283 commercial_ = [package isCommercial];
5285 if ([package_ mode] != nil)
5286 [buttons_ addObject:UCLocalize("CLEAR")];
5287 if ([package_ source] == nil);
5288 else if ([package_ upgradableAndEssential:NO])
5289 [buttons_ addObject:UCLocalize("UPGRADE")];
5290 else if ([package_ uninstalled])
5291 [buttons_ addObject:UCLocalize("INSTALL")];
5293 [buttons_ addObject:UCLocalize("REINSTALL")];
5294 if (![package_ uninstalled])
5295 [buttons_ addObject:UCLocalize("REMOVE")];
5297 if (special_ != NULL) {
5298 CGRect frame([document_ frame]);
5299 frame.size.height = 0;
5300 [document_ setFrame:frame];
5302 if ([scroller_ respondsToSelector:@selector(scrollPointVisibleAtTopLeft:)])
5303 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5305 [scroller_ scrollRectToVisible:CGRectZero animated:NO];
5308 [[[document_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5310 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5312 [self setFinishHook:nil];
5313 [self setPopupHook:nil];
5316 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5317 [super callFunction:special_];
5322 - (bool) isLoading {
5323 return commercial_ ? [super isLoading] : false;
5326 - (void) reloadData {
5327 [self setPackage:[database_ packageWithName:name_]];
5332 /* Package Table {{{ */
5333 @interface PackageTable : UIView <
5334 UITableViewDataSource,
5337 _transient Database *database_;
5338 NSMutableArray *packages_;
5339 NSMutableArray *sections_;
5341 NSMutableArray *index_;
5342 NSMutableDictionary *indices_;
5348 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5350 - (void) setDelegate:(id)delegate;
5352 - (void) reloadData;
5353 - (void) resetCursor;
5355 - (UITableView *) list;
5357 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5359 - (void) deselectWithAnimation:(BOOL)animated;
5363 @implementation PackageTable
5366 [packages_ release];
5367 [sections_ release];
5375 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5376 NSInteger count([sections_ count]);
5377 return count == 0 ? 1 : count;
5380 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5381 if ([sections_ count] == 0)
5383 return [[sections_ objectAtIndex:section] name];
5386 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5387 if ([sections_ count] == 0)
5389 return [[sections_ objectAtIndex:section] count];
5392 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5393 Section *section([sections_ objectAtIndex:[path section]]);
5394 NSInteger row([path row]);
5395 Package *package([packages_ objectAtIndex:([section row] + row)]);
5399 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5400 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5402 cell = [[[PackageCell alloc] init] autorelease];
5403 [cell setPackage:[self packageAtIndexPath:path]];
5407 - (void) deselectWithAnimation:(BOOL)animated {
5408 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5411 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5412 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5415 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5416 Package *package([self packageAtIndexPath:path]);
5417 package = [database_ packageWithName:[package id]];
5418 [target_ performSelector:action_ withObject:package];
5422 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5423 return [packages_ count] > 20 ? index_ : nil;
5426 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5430 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5431 if ((self = [super initWithFrame:frame]) != nil) {
5432 database_ = database;
5437 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5438 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5440 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5441 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5443 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5444 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5445 [list_ setRowHeight:73.0f];
5446 [self addSubview:list_];
5448 [list_ setDataSource:self];
5449 [list_ setDelegate:self];
5453 - (void) setDelegate:(id)delegate {
5454 delegate_ = delegate;
5457 - (bool) hasPackage:(Package *)package {
5461 - (void) reloadData {
5462 NSArray *packages = [database_ packages];
5464 [packages_ removeAllObjects];
5465 [sections_ removeAllObjects];
5467 _profile(PackageTable$reloadData$Filter)
5468 for (Package *package in packages)
5469 if ([self hasPackage:package])
5470 [packages_ addObject:package];
5473 [index_ removeAllObjects];
5474 [indices_ removeAllObjects];
5476 Section *section = nil;
5478 _profile(PackageTable$reloadData$Section)
5479 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5483 _profile(PackageTable$reloadData$Section$Package)
5484 package = [packages_ objectAtIndex:offset];
5485 index = [package index];
5488 if (section == nil || [section index] != index) {
5489 _profile(PackageTable$reloadData$Section$Allocate)
5490 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5493 [index_ addObject:[section name]];
5494 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5496 _profile(PackageTable$reloadData$Section$Add)
5497 [sections_ addObject:section];
5501 [section addToCount];
5505 _profile(PackageTable$reloadData$List)
5510 - (void) resetCursor {
5511 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5514 - (UITableView *) list {
5518 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5519 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5524 /* Filtered Package Table {{{ */
5525 @interface FilteredPackageTable : PackageTable {
5531 - (void) setObject:(id)object;
5532 - (void) setObject:(id)object forFilter:(SEL)filter;
5534 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5538 @implementation FilteredPackageTable
5546 - (void) setFilter:(SEL)filter {
5549 /* XXX: this is an unsafe optimization of doomy hell */
5550 Method method(class_getInstanceMethod([Package class], filter));
5551 _assert(method != NULL);
5552 imp_ = method_getImplementation(method);
5553 _assert(imp_ != NULL);
5556 - (void) setObject:(id)object {
5562 object_ = [object retain];
5565 - (void) setObject:(id)object forFilter:(SEL)filter {
5566 [self setFilter:filter];
5567 [self setObject:object];
5570 - (bool) hasPackage:(Package *)package {
5571 _profile(FilteredPackageTable$hasPackage)
5572 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5576 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5577 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5578 [self setFilter:filter];
5579 object_ = [object retain];
5587 /* Filtered Package Controller {{{ */
5588 @interface FilteredPackageController : CYViewController {
5589 _transient Database *database_;
5590 FilteredPackageTable *packages_;
5594 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5598 @implementation FilteredPackageController
5601 [packages_ release];
5607 - (void) viewDidAppear:(BOOL)animated {
5608 [super viewDidAppear:animated];
5609 [packages_ deselectWithAnimation:animated];
5612 - (void) didSelectPackage:(Package *)package {
5613 PackageController *view([delegate_ packageController]);
5614 [view setPackage:package];
5615 [view setDelegate:delegate_];
5616 [[self navigationController] pushViewController:view animated:YES];
5619 - (NSString *) title { return title_; }
5621 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5622 if ((self = [super init]) != nil) {
5623 database_ = database;
5624 title_ = [title copy];
5625 [[self navigationItem] setTitle:title_];
5627 packages_ = [[FilteredPackageTable alloc]
5628 initWithFrame:[[self view] bounds]
5631 action:@selector(didSelectPackage:)
5636 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5637 [[self view] addSubview:packages_];
5641 - (void) reloadData {
5642 [packages_ reloadData];
5645 - (void) setDelegate:(id)delegate {
5646 [super setDelegate:delegate];
5647 [packages_ setDelegate:delegate];
5654 /* Add Source Controller {{{ */
5655 @interface AddSourceController : CYViewController {
5656 _transient Database *database_;
5659 - (id) initWithDatabase:(Database *)database;
5663 @implementation AddSourceController
5665 - (id) initWithDatabase:(Database *)database {
5666 if ((self = [super init]) != nil) {
5667 database_ = database;
5673 /* Source Cell {{{ */
5674 @interface SourceCell : UITableViewCell <
5679 NSString *description_;
5681 ContentView *content_;
5684 - (void) setSource:(Source *)source;
5688 @implementation SourceCell
5690 - (void) clearSource {
5693 [description_ release];
5702 - (void) setSource:(Source *)source {
5706 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5708 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5709 icon_ = [icon_ retain];
5711 origin_ = [[source name] retain];
5712 label_ = [[source uri] retain];
5713 description_ = [[source description] retain];
5715 [content_ setNeedsDisplay];
5724 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5725 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5726 UIView *content([self contentView]);
5727 CGRect bounds([content bounds]);
5729 content_ = [[ContentView alloc] initWithFrame:bounds];
5730 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5731 [content_ setBackgroundColor:[UIColor whiteColor]];
5732 [content addSubview:content_];
5734 [content_ setDelegate:self];
5735 [content_ setOpaque:YES];
5739 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5740 [super setSelected:selected animated:animated];
5741 [content_ setNeedsDisplay];
5744 - (void) drawContentRect:(CGRect)rect {
5745 bool selected([self isSelected]);
5746 float width(rect.size.width);
5749 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5756 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5760 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5764 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5769 /* Source Table {{{ */
5770 @interface SourceTable : CYViewController <
5771 UITableViewDataSource,
5774 _transient Database *database_;
5776 NSMutableArray *sources_;
5780 UIProgressHUD *hud_;
5783 //NSURLConnection *installer_;
5784 NSURLConnection *trivial_;
5785 NSURLConnection *trivial_bz2_;
5786 NSURLConnection *trivial_gz_;
5787 //NSURLConnection *automatic_;
5792 - (id) initWithDatabase:(Database *)database;
5794 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5798 @implementation SourceTable
5800 - (void) _deallocConnection:(NSURLConnection *)connection {
5801 if (connection != nil) {
5802 [connection cancel];
5803 //[connection setDelegate:nil];
5804 [connection release];
5816 //[self _deallocConnection:installer_];
5817 [self _deallocConnection:trivial_];
5818 [self _deallocConnection:trivial_gz_];
5819 [self _deallocConnection:trivial_bz2_];
5820 //[self _deallocConnection:automatic_];
5827 - (void) viewDidAppear:(BOOL)animated {
5828 [super viewDidAppear:animated];
5829 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5832 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5833 return offset_ == 0 ? 1 : 2;
5836 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5837 switch (section + (offset_ == 0 ? 1 : 0)) {
5838 case 0: return UCLocalize("ENTERED_BY_USER");
5839 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5845 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5846 int count = [sources_ count];
5848 case 0: return (offset_ == 0 ? count : offset_);
5849 case 1: return count - offset_;
5855 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5857 switch (indexPath.section) {
5858 case 0: idx = indexPath.row; break;
5859 case 1: idx = indexPath.row + offset_; break;
5863 return [sources_ objectAtIndex:idx];
5866 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5867 Source *source = [self sourceAtIndexPath:indexPath];
5868 return [source description] == nil ? 56 : 73;
5871 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5872 static NSString *cellIdentifier = @"SourceCell";
5874 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5875 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5876 [cell setSource:[self sourceAtIndexPath:indexPath]];
5881 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5882 return UITableViewCellAccessoryDisclosureIndicator;
5885 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5886 Source *source = [self sourceAtIndexPath:indexPath];
5888 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5889 initWithDatabase:database_
5890 title:[source label]
5891 filter:@selector(isVisibleInSource:)
5895 [packages setDelegate:delegate_];
5897 [[self navigationController] pushViewController:packages animated:YES];
5900 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5901 Source *source = [self sourceAtIndexPath:indexPath];
5902 return [source record] != nil;
5905 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5906 Source *source = [self sourceAtIndexPath:indexPath];
5907 [Sources_ removeObjectForKey:[source key]];
5908 [delegate_ syncData];
5912 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5915 @"./", @"Distribution",
5916 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5918 [delegate_ syncData];
5921 - (NSString *) getWarning {
5922 NSString *href(href_);
5923 NSRange colon([href rangeOfString:@"://"]);
5924 if (colon.location != NSNotFound)
5925 href = [href substringFromIndex:(colon.location + 3)];
5926 href = [href stringByAddingPercentEscapes];
5927 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5928 href = [href stringByCachingURLWithCurrentCDN];
5930 NSURL *url([NSURL URLWithString:href]);
5932 NSStringEncoding encoding;
5933 NSError *error(nil);
5935 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5936 return [warning length] == 0 ? nil : warning;
5940 - (void) _endConnection:(NSURLConnection *)connection {
5941 NSURLConnection **field = NULL;
5942 if (connection == trivial_)
5944 else if (connection == trivial_bz2_)
5945 field = &trivial_bz2_;
5946 else if (connection == trivial_gz_)
5947 field = &trivial_gz_;
5948 _assert(field != NULL);
5949 [connection release];
5954 trivial_bz2_ == nil &&
5960 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5963 UIAlertView *alert = [[[UIAlertView alloc]
5964 initWithTitle:UCLocalize("SOURCE_WARNING")
5967 cancelButtonTitle:UCLocalize("CANCEL")
5968 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5971 [alert setContext:@"warning"];
5972 [alert setNumberOfRows:1];
5976 } else if (error_ != nil) {
5977 UIAlertView *alert = [[[UIAlertView alloc]
5978 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5979 message:[error_ localizedDescription]
5981 cancelButtonTitle:UCLocalize("OK")
5982 otherButtonTitles:nil
5985 [alert setContext:@"urlerror"];
5988 UIAlertView *alert = [[[UIAlertView alloc]
5989 initWithTitle:UCLocalize("NOT_REPOSITORY")
5990 message:UCLocalize("NOT_REPOSITORY_EX")
5992 cancelButtonTitle:UCLocalize("OK")
5993 otherButtonTitles:nil
5996 [alert setContext:@"trivial"];
6000 [delegate_ setStatusBarShowsProgress:NO];
6001 [delegate_ removeProgressHUD:hud_];
6011 if (error_ != nil) {
6018 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6019 switch ([response statusCode]) {
6025 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6026 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6028 error_ = [error retain];
6029 [self _endConnection:connection];
6032 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6033 [self _endConnection:connection];
6036 - (NSString *) title { return UCLocalize("SOURCES"); }
6038 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6039 NSMutableURLRequest *request = [NSMutableURLRequest
6040 requestWithURL:[NSURL URLWithString:href]
6041 cachePolicy:NSURLRequestUseProtocolCachePolicy
6042 timeoutInterval:120.0
6045 [request setHTTPMethod:method];
6047 if (Machine_ != NULL)
6048 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6049 if (UniqueID_ != nil)
6050 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6052 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6054 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6057 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6058 NSString *context([alert context]);
6060 if ([context isEqualToString:@"source"]) {
6063 NSString *href = [[alert textField] text];
6065 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6067 if (![href hasSuffix:@"/"])
6068 href_ = [href stringByAppendingString:@"/"];
6071 href_ = [href_ retain];
6073 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6074 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6075 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6076 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6080 hud_ = [[delegate_ addProgressHUD] retain];
6081 [hud_ setText:UCLocalize("VERIFYING_URL")];
6090 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6091 } else if ([context isEqualToString:@"trivial"])
6092 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6093 else if ([context isEqualToString:@"urlerror"])
6094 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6095 else if ([context isEqualToString:@"warning"]) {
6110 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6114 - (id) initWithDatabase:(Database *)database {
6115 if ((self = [super init]) != nil) {
6116 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6117 [self updateButtonsForEditingStatus:NO animated:NO];
6119 database_ = database;
6120 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6122 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6123 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6124 [[self view] addSubview:list_];
6126 [list_ setDataSource:self];
6127 [list_ setDelegate:self];
6133 - (void) reloadData {
6135 if (!list.ReadMainList())
6138 [sources_ removeAllObjects];
6139 [sources_ addObjectsFromArray:[database_ sources]];
6141 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6144 int count([sources_ count]);
6146 for (int i = 0; i != count; i++) {
6147 if ([[sources_ objectAtIndex:i] record] == nil) break;
6151 [list_ setEditing:NO];
6152 [self updateButtonsForEditingStatus:NO animated:NO];
6156 - (void) addButtonClicked {
6157 /*[book_ pushPage:[[[AddSourceController alloc]
6162 UIAlertView *alert = [[[UIAlertView alloc]
6163 initWithTitle:UCLocalize("ENTER_APT_URL")
6166 cancelButtonTitle:UCLocalize("CANCEL")
6167 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6170 [alert setContext:@"source"];
6171 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6173 [alert setNumberOfRows:1];
6174 [alert addTextFieldWithValue:@"http://" label:@""];
6176 UITextInputTraits *traits = [[alert textField] textInputTraits];
6177 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6178 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6179 [traits setKeyboardType:UIKeyboardTypeURL];
6180 // XXX: UIReturnKeyDone
6181 [traits setReturnKeyType:UIReturnKeyNext];
6186 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6187 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
6188 initWithTitle:UCLocalize("ADD")
6189 style:UIBarButtonItemStylePlain
6191 action:@selector(addButtonClicked)
6193 [[self navigationItem] setLeftBarButtonItem:editing ? leftItem : [[self navigationItem] backBarButtonItem] animated:animated];
6196 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6197 initWithTitle:editing ? UCLocalize("DONE") : UCLocalize("EDIT")
6198 style:editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6200 action:@selector(editButtonClicked)
6202 [[self navigationItem] setRightBarButtonItem:rightItem animated:animated];
6203 [rightItem release];
6205 if (IsWildcat_ && !editing) {
6206 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6207 initWithTitle:UCLocalize("SETTINGS")
6208 style:UIBarButtonItemStylePlain
6210 action:@selector(settingsButtonClicked)
6212 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6213 [settingsItem release];
6217 - (void) settingsButtonClicked {
6218 [delegate_ showSettings];
6221 - (void) editButtonClicked {
6222 [list_ setEditing:![list_ isEditing] animated:YES];
6224 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6230 /* Installed Controller {{{ */
6231 @interface InstalledController : FilteredPackageController {
6235 - (id) initWithDatabase:(Database *)database;
6237 - (void) updateRoleButton;
6238 - (void) queueStatusDidChange;
6242 @implementation InstalledController
6248 - (NSString *) title { return UCLocalize("INSTALLED"); }
6250 - (id) initWithDatabase:(Database *)database {
6251 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6252 [self updateRoleButton];
6253 [self queueStatusDidChange];
6258 - (void) queueButtonClicked {
6263 - (void) queueStatusDidChange {
6266 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6267 initWithTitle:UCLocalize("QUEUE")
6268 style:UIBarButtonItemStyleDone
6270 action:@selector(queueButtonClicked)
6272 if (Queuing_) [[self navigationItem] setLeftBarButtonItem:queueItem];
6273 else [[self navigationItem] setLeftBarButtonItem:nil];
6274 [queueItem release];
6279 - (void) reloadData {
6280 [packages_ reloadData];
6283 - (void) updateRoleButton {
6284 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6285 initWithTitle:expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")
6286 style:expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6288 action:@selector(roleButtonClicked)
6290 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) [[self navigationItem] setRightBarButtonItem:rightItem];
6291 [rightItem release];
6294 - (void) roleButtonClicked {
6295 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6296 [packages_ reloadData];
6299 [self updateRoleButton];
6302 - (void) setDelegate:(id)delegate {
6303 [super setDelegate:delegate];
6304 [packages_ setDelegate:delegate];
6310 /* Home Controller {{{ */
6311 @interface HomeController : CYBrowserController {
6316 @implementation HomeController
6318 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6319 [super _setMoreHeaders:request];
6321 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6322 if (UniqueID_ != nil)
6323 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6326 - (void) aboutButtonClicked {
6327 UIAlertView *alert = [[[UIAlertView alloc] init] autorelease];
6328 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6329 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6330 [alert setCancelButtonIndex:0];
6333 @"Copyright (C) 2008-2010\n"
6334 "Jay Freeman (saurik)\n"
6335 "saurik@saurik.com\n"
6336 "http://www.saurik.com/"
6342 - (void) viewWillAppear:(BOOL)animated {
6343 [super viewWillAppear:animated];
6344 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6347 - (void) viewWillDisappear:(BOOL)animated {
6348 [super viewWillDisappear:animated];
6349 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6353 if ((self = [super init]) != nil) {
6354 UIBarButtonItem *aboutItem = [[UIBarButtonItem alloc]
6355 initWithTitle:UCLocalize("ABOUT")
6356 style:UIBarButtonItemStylePlain
6358 action:@selector(aboutButtonClicked)
6360 [[self navigationItem] setLeftBarButtonItem:aboutItem];
6361 [aboutItem release];
6367 /* Manage Controller {{{ */
6368 @interface ManageController : CYBrowserController {
6371 - (void) queueStatusDidChange;
6374 @implementation ManageController
6377 if ((self = [super init]) != nil) {
6378 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6380 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6381 initWithTitle:UCLocalize("SETTINGS")
6382 style:UIBarButtonItemStylePlain
6384 action:@selector(settingsButtonClicked)
6386 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6387 [settingsItem release];
6389 [self queueStatusDidChange];
6393 - (void) settingsButtonClicked {
6394 [delegate_ showSettings];
6398 - (void) queueButtonClicked {
6402 - (void) applyLoadingTitle {
6403 // No "Loading" title.
6406 - (void) applyRightButton {
6411 - (void) queueStatusDidChange {
6413 if (!IsWildcat_ && Queuing_) {
6414 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6415 initWithTitle:UCLocalize("QUEUE")
6416 style:UIBarButtonItemStyleDone
6418 action:@selector(queueButtonClicked)
6420 [[self navigationItem] setRightBarButtonItem:queueItem];
6422 [queueItem release];
6424 [[self navigationItem] setRightBarButtonItem:nil];
6429 - (bool) isLoading {
6436 /* Refresh Bar {{{ */
6437 @interface RefreshBar : UINavigationBar {
6438 UIProgressIndicator *indicator_;
6439 UITextLabel *prompt_;
6440 UIProgressBar *progress_;
6441 UINavigationButton *cancel_;
6446 @implementation RefreshBar
6448 - (void) positionViews {
6449 CGRect frame = [cancel_ frame];
6450 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6451 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6452 [cancel_ setFrame:frame];
6454 CGSize prgsize = {75, 100};
6456 [self frame].size.width - prgsize.width - 10,
6457 ([self frame].size.height - prgsize.height) / 2
6459 [progress_ setFrame:prgrect];
6461 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6462 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6463 CGRect indrect = {{indoffset, indoffset}, indsize};
6464 [indicator_ setFrame:indrect];
6466 CGSize prmsize = {215, indsize.height + 4};
6468 indoffset * 2 + indsize.width,
6469 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6471 [prompt_ setFrame:prmrect];
6474 - (void)setFrame:(CGRect)frame {
6475 [super setFrame:frame];
6477 [self positionViews];
6480 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6481 if ((self = [super initWithFrame:frame])) {
6482 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6484 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6485 [self setBarStyle:UIBarStyleBlack];
6487 UIBarStyle barstyle([self _barStyle:NO]);
6488 bool ugly(barstyle == UIBarStyleDefault);
6490 UIProgressIndicatorStyle style = ugly ?
6491 UIProgressIndicatorStyleMediumBrown :
6492 UIProgressIndicatorStyleMediumWhite;
6494 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6495 [indicator_ setStyle:style];
6496 [indicator_ startAnimation];
6497 [self addSubview:indicator_];
6499 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6500 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6501 [prompt_ setBackgroundColor:[UIColor clearColor]];
6502 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6503 [self addSubview:prompt_];
6505 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6506 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6507 [progress_ setStyle:0];
6508 [self addSubview:progress_];
6510 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6511 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6512 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6513 [cancel_ setBarStyle:barstyle];
6515 [self positionViews];
6520 [cancel_ removeFromSuperview];
6524 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6525 [progress_ setProgress:0];
6526 [self addSubview:cancel_];
6530 [cancel_ removeFromSuperview];
6533 - (void) setPrompt:(NSString *)prompt {
6534 [prompt_ setText:prompt];
6537 - (void) setProgress:(float)progress {
6538 [progress_ setProgress:progress];
6544 @class CYNavigationController;
6546 /* Cydia Tab Bar Controller {{{ */
6547 @interface CYTabBarController : UITabBarController {
6548 Database *database_;
6553 @implementation CYTabBarController
6555 /* XXX: some logic should probably go here related to
6556 freeing the view controllers on tab change */
6558 - (void) reloadData {
6559 size_t count([[self viewControllers] count]);
6560 for (size_t i(0); i != count; ++i) {
6561 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6566 - (id) initWithDatabase:(Database *)database {
6567 if ((self = [super init]) != nil) {
6568 database_ = database;
6575 /* Cydia Navigation Controller {{{ */
6576 @interface CYNavigationController : UINavigationController {
6577 _transient Database *database_;
6578 id<UINavigationControllerDelegate> delegate_;
6581 - (id) initWithDatabase:(Database *)database;
6582 - (void) reloadData;
6587 @implementation CYNavigationController
6589 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6590 // Inherit autorotation settings for modal parents.
6591 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6592 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6594 return [super shouldAutorotateToInterfaceOrientation:orientation];
6602 - (void) reloadData {
6603 size_t count([[self viewControllers] count]);
6604 for (size_t i(0); i != count; ++i) {
6605 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6610 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6611 delegate_ = delegate;
6614 - (id) initWithDatabase:(Database *)database {
6615 if ((self = [super init]) != nil) {
6616 database_ = database;
6622 /* Cydia:// Protocol {{{ */
6623 @interface CydiaURLProtocol : NSURLProtocol {
6628 @implementation CydiaURLProtocol
6630 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6631 NSURL *url([request URL]);
6634 NSString *scheme([[url scheme] lowercaseString]);
6635 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6640 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6644 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6645 id<NSURLProtocolClient> client([self client]);
6647 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6649 NSData *data(UIImagePNGRepresentation(icon));
6651 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6652 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6653 [client URLProtocol:self didLoadData:data];
6654 [client URLProtocolDidFinishLoading:self];
6658 - (void) startLoading {
6659 id<NSURLProtocolClient> client([self client]);
6660 NSURLRequest *request([self request]);
6662 NSURL *url([request URL]);
6663 NSString *href([url absoluteString]);
6665 NSString *path([href substringFromIndex:8]);
6666 NSRange slash([path rangeOfString:@"/"]);
6669 if (slash.location == NSNotFound) {
6673 command = [path substringToIndex:slash.location];
6674 path = [path substringFromIndex:(slash.location + 1)];
6677 Database *database([Database sharedInstance]);
6679 if ([command isEqualToString:@"package-icon"]) {
6682 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6683 Package *package([database packageWithName:path]);
6686 UIImage *icon([package icon]);
6687 [self _returnPNGWithImage:icon forRequest:request];
6688 } else if ([command isEqualToString:@"source-icon"]) {
6691 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6692 NSString *source(Simplify(path));
6693 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6695 icon = [UIImage applicationImageNamed:@"unknown.png"];
6696 [self _returnPNGWithImage:icon forRequest:request];
6697 } else if ([command isEqualToString:@"uikit-image"]) {
6700 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6701 UIImage *icon(_UIImageWithName(path));
6702 [self _returnPNGWithImage:icon forRequest:request];
6703 } else if ([command isEqualToString:@"section-icon"]) {
6706 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6707 NSString *section(Simplify(path));
6708 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6710 icon = [UIImage applicationImageNamed:@"unknown.png"];
6711 [self _returnPNGWithImage:icon forRequest:request];
6713 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6717 - (void) stopLoading {
6723 /* Sections Controller {{{ */
6724 @interface SectionsController : CYViewController <
6725 UITableViewDataSource,
6728 _transient Database *database_;
6729 NSMutableArray *sections_;
6730 NSMutableArray *filtered_;
6736 - (id) initWithDatabase:(Database *)database;
6737 - (void) reloadData;
6740 - (void) editButtonClicked;
6744 @implementation SectionsController
6747 [list_ setDataSource:nil];
6748 [list_ setDelegate:nil];
6750 [sections_ release];
6751 [filtered_ release];
6753 [accessory_ release];
6757 - (void) viewDidAppear:(BOOL)animated {
6758 [super viewDidAppear:animated];
6759 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6762 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6763 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6767 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6768 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6771 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6775 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6776 static NSString *reuseIdentifier = @"SectionCell";
6778 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6779 if (cell == nil) cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6780 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6785 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6786 Section *section = [self sectionAtIndexPath:indexPath];
6787 NSString *name = [section name];
6790 if ([indexPath row] == 0) {
6793 title = UCLocalize("ALL_PACKAGES");
6796 name = [NSString stringWithString:name];
6797 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6800 title = UCLocalize("NO_SECTION");
6804 FilteredPackageController *table = [[[FilteredPackageController alloc]
6805 initWithDatabase:database_
6807 filter:@selector(isVisibleInSection:)
6811 [table setDelegate:delegate_];
6813 [[self navigationController] pushViewController:table animated:YES];
6816 - (NSString *) title { return UCLocalize("SECTIONS"); }
6818 - (id) initWithDatabase:(Database *)database {
6819 if ((self = [super init]) != nil) {
6820 database_ = database;
6822 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6824 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6825 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6827 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6828 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6829 [list_ setRowHeight:45.0f];
6830 [[self view] addSubview:list_];
6832 [list_ setDataSource:self];
6833 [list_ setDelegate:self];
6839 - (void) reloadData {
6840 NSArray *packages = [database_ packages];
6842 [sections_ removeAllObjects];
6843 [filtered_ removeAllObjects];
6846 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6847 SectionMap sections;
6848 sections.resize(64);
6850 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6854 for (Package *package in packages) {
6855 NSString *name([package section]);
6856 NSString *key(name == nil ? @"" : name);
6861 _profile(SectionsView$reloadData$Section)
6862 section = §ions[key];
6863 if (*section == nil) {
6864 _profile(SectionsView$reloadData$Section$Allocate)
6865 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6870 [*section addToCount];
6872 _profile(SectionsView$reloadData$Filter)
6873 if (![package valid] || ![package visible])
6877 [*section addToRow];
6881 _profile(SectionsView$reloadData$Section)
6882 section = [sections objectForKey:key];
6883 if (section == nil) {
6884 _profile(SectionsView$reloadData$Section$Allocate)
6885 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6886 [sections setObject:section forKey:key];
6891 [section addToCount];
6893 _profile(SectionsView$reloadData$Filter)
6894 if (![package valid] || ![package visible])
6904 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6905 [sections_ addObject:i->second];
6907 [sections_ addObjectsFromArray:[sections allValues]];
6910 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6912 for (Section *section in sections_) {
6913 size_t count([section row]);
6917 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6918 [section setCount:count];
6919 [filtered_ addObject:section];
6922 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6923 initWithTitle:[sections_ count] == 0 ? nil : UCLocalize("EDIT")
6924 style:UIBarButtonItemStylePlain
6926 action:@selector(editButtonClicked)
6928 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] != nil];
6929 [rightItem release];
6935 - (void) resetView {
6937 [self editButtonClicked];
6940 - (void) editButtonClicked {
6941 if ((editing_ = !editing_))
6944 [delegate_ updateData];
6946 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6947 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6948 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6951 - (UIView *) accessoryView {
6957 /* Changes Controller {{{ */
6958 @interface ChangesController : CYViewController <
6959 UITableViewDataSource,
6962 _transient Database *database_;
6963 NSMutableArray *packages_;
6964 NSMutableArray *sections_;
6967 BOOL hasSentFirstLoad_;
6970 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6971 - (void) reloadData;
6975 @implementation ChangesController
6978 [list_ setDelegate:nil];
6979 [list_ setDataSource:nil];
6981 [packages_ release];
6982 [sections_ release];
6987 - (void) viewDidAppear:(BOOL)animated {
6988 [super viewDidAppear:animated];
6989 if (!hasSentFirstLoad_) {
6990 hasSentFirstLoad_ = YES;
6991 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6993 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6997 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6998 NSInteger count([sections_ count]);
6999 return count == 0 ? 1 : count;
7002 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7003 if ([sections_ count] == 0)
7005 return [[sections_ objectAtIndex:section] name];
7008 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7009 if ([sections_ count] == 0)
7011 return [[sections_ objectAtIndex:section] count];
7014 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7015 Section *section([sections_ objectAtIndex:[path section]]);
7016 NSInteger row([path row]);
7017 return [packages_ objectAtIndex:([section row] + row)];
7020 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7021 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7023 cell = [[[PackageCell alloc] init] autorelease];
7024 [cell setPackage:[self packageAtIndexPath:path]];
7028 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7029 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7032 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7033 Package *package([self packageAtIndexPath:path]);
7034 PackageController *view([delegate_ packageController]);
7035 [view setDelegate:delegate_];
7036 [view setPackage:package];
7037 [[self navigationController] pushViewController:view animated:YES];
7041 - (void) refreshButtonClicked {
7042 [delegate_ beginUpdate];
7043 [[self navigationItem] setLeftBarButtonItem:nil];
7046 - (void) upgradeButtonClicked {
7047 [delegate_ distUpgrade];
7050 - (NSString *) title { return UCLocalize("CHANGES"); }
7052 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7053 if ((self = [super init]) != nil) {
7054 database_ = database;
7055 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7057 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
7058 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7060 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7061 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7062 [list_ setRowHeight:73.0f];
7063 [[self view] addSubview:list_];
7065 [list_ setDataSource:self];
7066 [list_ setDelegate:self];
7068 delegate_ = delegate;
7072 - (void) _reloadPackages:(NSArray *)packages {
7074 for (Package *package in packages)
7076 [package uninstalled] && [package valid] && [package visible] ||
7077 [package upgradableAndEssential:YES]
7079 [packages_ addObject:package];
7082 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7086 - (void) reloadData {
7087 NSArray *packages = [database_ packages];
7089 [packages_ removeAllObjects];
7090 [sections_ removeAllObjects];
7092 UIProgressHUD *hud([delegate_ addProgressHUD]);
7094 [hud setText:@"Loading Changes"];
7095 NSLog(@"HUD:%@::%@", delegate_, hud);
7096 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7097 [delegate_ removeProgressHUD:hud];
7099 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7100 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7101 Section *section = nil;
7105 bool unseens = false;
7107 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7109 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7110 Package *package = [packages_ objectAtIndex:offset];
7112 BOOL uae = [package upgradableAndEssential:YES];
7118 _profile(ChangesController$reloadData$Remember)
7119 seen = [package seen];
7122 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7127 name = UCLocalize("UNKNOWN");
7129 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7133 _profile(ChangesController$reloadData$Allocate)
7134 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7135 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7136 [sections_ addObject:section];
7140 [section addToCount];
7141 } else if ([package ignored])
7142 [ignored addToCount];
7145 [upgradable addToCount];
7150 CFRelease(formatter);
7153 Section *last = [sections_ lastObject];
7154 size_t count = [last count];
7155 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7156 [sections_ removeLastObject];
7159 if ([ignored count] != 0)
7160 [sections_ insertObject:ignored atIndex:0];
7162 [sections_ insertObject:upgradable atIndex:0];
7166 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7167 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7168 style:UIBarButtonItemStylePlain
7170 action:@selector(upgradeButtonClicked)
7172 if (upgrades_ > 0) [[self navigationItem] setRightBarButtonItem:rightItem];
7173 [rightItem release];
7175 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
7176 initWithTitle:UCLocalize("REFRESH")
7177 style:UIBarButtonItemStylePlain
7179 action:@selector(refreshButtonClicked)
7181 if (![delegate_ updating]) [[self navigationItem] setLeftBarButtonItem:leftItem];
7187 /* Search Controller {{{ */
7188 @interface SearchController : FilteredPackageController <
7191 UISearchBar *search_;
7194 - (id) initWithDatabase:(Database *)database;
7195 - (void) reloadData;
7199 @implementation SearchController
7206 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7207 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7208 [search_ resignFirstResponder];
7212 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7213 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7217 - (NSString *) title { return nil; }
7219 - (id) initWithDatabase:(Database *)database {
7220 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7223 - (void)viewDidAppear:(BOOL)animated {
7224 [super viewDidAppear:animated];
7226 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7227 [search_ layoutSubviews];
7228 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7229 UITextField *textField = [search_ searchField];
7230 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7231 [search_ setDelegate:self];
7232 [textField setEnablesReturnKeyAutomatically:NO];
7233 [[self navigationItem] setTitleView:textField];
7237 - (void) _reloadData {
7240 - (void) reloadData {
7241 _profile(SearchController$reloadData)
7242 [packages_ reloadData];
7245 [packages_ resetCursor];
7248 - (void) didSelectPackage:(Package *)package {
7249 [search_ resignFirstResponder];
7250 [super didSelectPackage:package];
7255 /* Settings Controller {{{ */
7256 @interface SettingsController : CYViewController <
7257 UITableViewDataSource,
7260 _transient Database *database_;
7263 UITableView *table_;
7264 id subscribedSwitch_;
7266 UITableViewCell *subscribedCell_;
7267 UITableViewCell *ignoredCell_;
7270 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7274 @implementation SettingsController
7278 if (package_ != nil)
7281 [subscribedSwitch_ release];
7282 [ignoredSwitch_ release];
7283 [subscribedCell_ release];
7284 [ignoredCell_ release];
7289 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7290 if (package_ == nil)
7296 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7297 if (package_ == nil)
7303 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7304 return UCLocalize("SHOW_ALL_CHANGES_EX");
7307 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7308 if (package_ == nil)
7311 NSMutableDictionary *metadata([package_ metadata]);
7314 if (NSNumber *number = [metadata objectForKey:key])
7315 before = [number boolValue];
7319 if (value != before) {
7320 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7322 [delegate_ updateData];
7326 - (void) onSubscribed:(id)control {
7327 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7330 - (void) onIgnored:(id)control {
7331 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
7334 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7335 if (package_ == nil)
7338 switch ([indexPath row]) {
7339 case 0: return subscribedCell_;
7340 case 1: return ignoredCell_;
7348 - (NSString *) title { return UCLocalize("SETTINGS"); }
7350 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7351 if ((self = [super init])) {
7352 database_ = database;
7353 name_ = [package retain];
7355 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7357 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7358 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7359 [table_ setAllowsSelection:NO];
7360 [[self view] addSubview:table_];
7362 subscribedSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7363 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7364 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7366 ignoredSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7367 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7368 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7370 subscribedCell_ = [[UITableViewCell alloc] init];
7371 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7372 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7374 ignoredCell_ = [[UITableViewCell alloc] init];
7375 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7376 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7378 [table_ setDataSource:self];
7379 [table_ setDelegate:self];
7384 - (void) reloadData {
7385 if (package_ != nil)
7386 [package_ autorelease];
7387 package_ = [database_ packageWithName:name_];
7388 if (package_ != nil) {
7390 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7391 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7394 [table_ reloadData];
7400 /* Signature Controller {{{ */
7401 @interface SignatureController : CYBrowserController {
7402 _transient Database *database_;
7406 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7410 @implementation SignatureController
7417 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7419 [super webView:sender didClearWindowObject:window forFrame:frame];
7422 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7423 if ((self = [super init]) != nil) {
7424 database_ = database;
7425 package_ = [package retain];
7430 - (void) reloadData {
7431 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7436 /* Role Controller {{{ */
7437 @interface RoleController : CYViewController <
7438 UITableViewDataSource,
7441 _transient Database *database_;
7443 UITableView *table_;
7444 UISegmentedControl *segment_;
7448 - (void) showDoneButton;
7449 - (void) resizeSegmentedControl;
7453 @implementation RoleController
7457 [container_ release];
7462 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7463 if ((self = [super init])) {
7464 database_ = database;
7465 roledelegate_ = delegate;
7467 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7469 NSArray *items = [NSArray arrayWithObjects:
7471 UCLocalize("HACKER"),
7472 UCLocalize("DEVELOPER"),
7474 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7475 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7476 [container_ addSubview:segment_];
7479 if ([Role_ isEqualToString:@"User"]) index = 0;
7480 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7481 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7483 [segment_ setSelectedSegmentIndex:index];
7484 [self showDoneButton];
7487 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7488 [self resizeSegmentedControl];
7490 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7491 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7492 [table_ setDelegate:self];
7493 [table_ setDataSource:self];
7494 [[self view] addSubview:table_];
7495 [table_ reloadData];
7499 - (void) resizeSegmentedControl {
7500 CGFloat width = [[self view] frame].size.width;
7501 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7504 - (void) viewWillAppear:(BOOL)animated {
7505 [super viewWillAppear:animated];
7507 [self resizeSegmentedControl];
7510 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7511 [self resizeSegmentedControl];
7514 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7515 [self resizeSegmentedControl];
7519 NSString *role(nil);
7521 switch ([segment_ selectedSegmentIndex]) {
7522 case 0: role = @"User"; break;
7523 case 1: role = @"Hacker"; break;
7524 case 2: role = @"Developer"; break;
7529 if (![role isEqualToString:Role_]) {
7530 bool rolling(Role_ == nil);
7533 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7537 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7542 [roledelegate_ loadData];
7544 [roledelegate_ updateData];
7548 - (void) segmentChanged:(UISegmentedControl *)control {
7549 [self showDoneButton];
7552 - (void) doneButtonClicked {
7554 [[self navigationController] dismissModalViewControllerAnimated:YES];
7557 - (void) showDoneButton {
7558 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7559 initWithTitle:UCLocalize("DONE")
7560 style:UIBarButtonItemStyleDone
7562 action:@selector(doneButtonClicked)
7564 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] == nil];
7565 [rightItem release];
7568 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7569 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7573 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7577 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7578 return nil; // This method is required by the protocol.
7581 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7583 return UCLocalize("ROLE_EX");
7585 return [NSString stringWithFormat:
7586 @"%@: %@\n%@: %@\n%@: %@",
7587 UCLocalize("USER"), UCLocalize("USER_EX"),
7588 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7589 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7594 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7595 if (section == 3) return 44.0f;
7599 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7600 if (section == 3) return container_;
7607 /* Cydia Container {{{ */
7608 @interface CYContainer : UIViewController <ProgressDelegate> {
7609 _transient Database *database_;
7610 RefreshBar *refreshbar_;
7615 UITabBarController *root_;
7618 - (void) setTabBarController:(UITabBarController *)controller;
7620 - (void) dropBar:(BOOL)animated;
7621 - (void) beginUpdate;
7622 - (void) raiseBar:(BOOL)animated;
7626 @implementation CYContainer
7628 // NOTE: UIWindow only sends the top controller these messages,
7629 // So we have to forward them on.
7631 - (void) viewDidAppear:(BOOL)animated {
7632 [super viewDidAppear:animated];
7633 [root_ viewDidAppear:animated];
7636 - (void) viewWillAppear:(BOOL)animated {
7637 [super viewWillAppear:animated];
7638 [root_ viewWillAppear:animated];
7641 - (void) viewDidDisappear:(BOOL)animated {
7642 [super viewDidDisappear:animated];
7643 [root_ viewDidDisappear:animated];
7646 - (void) viewWillDisappear:(BOOL)animated {
7647 [super viewWillDisappear:animated];
7648 [root_ viewWillDisappear:animated];
7651 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7655 - (void) setTabBarController:(UITabBarController *)controller {
7657 [[self view] addSubview:[root_ view]];
7660 - (void) setUpdate:(NSDate *)date {
7664 - (void) beginUpdate {
7666 [refreshbar_ start];
7671 detachNewThreadSelector:@selector(performUpdate)
7677 - (void) performUpdate { _pooled
7679 status.setDelegate(self);
7680 [database_ updateWithStatus:status];
7683 performSelectorOnMainThread:@selector(completeUpdate)
7689 - (void) completeUpdate {
7692 [self raiseBar:YES];
7694 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7697 - (void) cancelUpdate {
7698 [refreshbar_ cancel];
7699 [self completeUpdate];
7702 - (void) cancelPressed {
7703 [self cancelUpdate];
7710 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7711 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7714 - (void) startProgress {
7717 - (void) setProgressTitle:(NSString *)title {
7719 performSelectorOnMainThread:@selector(_setProgressTitle:)
7725 - (bool) isCancelling:(size_t)received {
7729 - (void) setProgressPercent:(float)percent {
7731 performSelectorOnMainThread:@selector(_setProgressPercent:)
7732 withObject:[NSNumber numberWithFloat:percent]
7737 - (void) addProgressOutput:(NSString *)output {
7739 performSelectorOnMainThread:@selector(_addProgressOutput:)
7745 - (void) _setProgressTitle:(NSString *)title {
7746 [refreshbar_ setPrompt:title];
7749 - (void) _setProgressPercent:(NSNumber *)percent {
7750 [refreshbar_ setProgress:[percent floatValue]];
7753 - (void) _addProgressOutput:(NSString *)output {
7756 - (void) setUpdateDelegate:(id)delegate {
7757 updatedelegate_ = delegate;
7760 - (void) dropBar:(BOOL)animated {
7761 if (dropped_) return;
7764 [[self view] addSubview:refreshbar_];
7766 if (animated) [UIView beginAnimations:nil context:NULL];
7767 CGRect barframe = [refreshbar_ frame];
7768 CGRect viewframe = [[root_ view] frame];
7769 viewframe.origin.y += barframe.size.height;
7770 viewframe.size.height -= barframe.size.height;
7771 [[root_ view] setFrame:viewframe];
7772 if (animated) [UIView commitAnimations];
7774 // Ensure bar has the proper width for our view, it might have changed
7775 barframe.size.width = viewframe.size.width;
7776 [refreshbar_ setFrame:barframe];
7778 // XXX: fix Apple's layout bug
7779 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7782 - (void) raiseBar:(BOOL)animated {
7783 if (!dropped_) return;
7786 [refreshbar_ removeFromSuperview];
7788 if (animated) [UIView beginAnimations:nil context:NULL];
7789 CGRect barframe = [refreshbar_ frame];
7790 CGRect viewframe = [[root_ view] frame];
7791 viewframe.origin.y -= barframe.size.height;
7792 viewframe.size.height += barframe.size.height;
7793 [[root_ view] setFrame:viewframe];
7794 if (animated) [UIView commitAnimations];
7796 // XXX: fix Apple's layout bug
7797 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7800 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7801 // XXX: fix Apple's layout bug
7802 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7805 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7811 // XXX: fix Apple's layout bug
7812 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7816 [refreshbar_ release];
7820 - (id) initWithDatabase: (Database *)database {
7821 if ((self = [super init]) != nil) {
7822 database_ = database;
7824 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7826 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7843 @interface Cydia : UIApplication <
7844 ConfirmationControllerDelegate,
7845 ProgressControllerDelegate,
7847 UINavigationControllerDelegate
7850 CYContainer *container_;
7854 NSMutableArray *essential_;
7855 NSMutableArray *broken_;
7857 Database *database_;
7861 UIKeyboard *keyboard_;
7862 UIProgressHUD *hud_;
7864 SectionsController *sections_;
7865 ChangesController *changes_;
7866 ManageController *manage_;
7867 SearchController *search_;
7868 SourceTable *sources_;
7869 InstalledController *installed_;
7872 #if RecyclePackageViews
7873 NSMutableArray *details_;
7879 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7880 - (void) setPage:(CYViewController *)page;
7885 static _finline void _setHomePage(Cydia *self) {
7886 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7889 @implementation Cydia
7891 - (void) beginUpdate {
7892 [container_ beginUpdate];
7896 return [container_ updating];
7899 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7904 if ([broken_ count] != 0) {
7905 int count = [broken_ count];
7907 UIAlertView *alert = [[[UIAlertView alloc]
7908 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7909 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7911 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7912 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
7915 [alert setContext:@"fixhalf"];
7917 } else if (!Ignored_ && [essential_ count] != 0) {
7918 int count = [essential_ count];
7920 UIAlertView *alert = [[[UIAlertView alloc]
7921 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7922 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
7924 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
7925 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
7928 [alert setContext:@"upgrade"];
7933 - (void) _saveConfig {
7936 NSString *error(nil);
7937 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7939 NSError *error(nil);
7940 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7941 NSLog(@"failure to save metadata data: %@", error);
7944 NSLog(@"failure to serialize metadata: %@", error);
7952 - (void) _updateData {
7955 /* XXX: this is just stupid */
7956 if (tag_ != 1 && sections_ != nil)
7957 [sections_ reloadData];
7958 if (tag_ != 2 && changes_ != nil)
7959 [changes_ reloadData];
7960 if (tag_ != 4 && search_ != nil)
7961 [search_ reloadData];
7963 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
7966 - (int)indexOfTabWithTag:(int)tag {
7968 for (UINavigationController *controller in [tabbar_ viewControllers]) {
7969 if ([[controller tabBarItem] tag] == tag) return i;
7976 - (void) _refreshIfPossible {
7977 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
7979 SCNetworkReachabilityFlags flags; {
7980 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
7981 SCNetworkReachabilityGetFlags(reachability, &flags);
7982 CFRelease(reachability);
7985 // XXX: this elaborate mess is what Apple is using to determine this? :(
7986 // XXX: do we care if the user has to intervene? maybe that's ok?
7988 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
7989 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
7990 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
7991 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
7992 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
7993 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
7997 if (loaded_ || ManualRefresh || !reachable) loaded:
7998 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8002 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8004 if (update != nil) {
8005 NSTimeInterval interval([update timeIntervalSinceNow]);
8006 if (interval <= 0 && interval > -(15*60))
8010 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8016 - (void) refreshIfPossible {
8017 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8020 - (void) _reloadData {
8021 UIProgressHUD *hud([self addProgressHUD]);
8022 [hud setText:(loaded_ ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
8024 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8027 [self removeProgressHUD:hud];
8031 [essential_ removeAllObjects];
8032 [broken_ removeAllObjects];
8034 NSArray *packages([database_ packages]);
8035 for (Package *package in packages) {
8037 [broken_ addObject:package];
8038 if ([package upgradableAndEssential:NO]) {
8039 if ([package essential])
8040 [essential_ addObject:package];
8046 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8047 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:badge];
8048 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:YES];
8050 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8051 [self setApplicationBadge:badge];
8053 [self setApplicationBadgeString:badge];
8055 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:nil];
8056 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:NO];
8058 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8059 [self removeApplicationBadge];
8060 else // XXX: maybe use setApplicationBadgeString also?
8061 [self setApplicationIconBadgeNumber:0];
8066 [self refreshIfPossible];
8069 - (void) updateData {
8070 [database_ setVisible];
8079 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8080 _assert(file != NULL);
8082 for (NSString *key in [Sources_ allKeys]) {
8083 NSDictionary *source([Sources_ objectForKey:key]);
8085 fprintf(file, "%s %s %s\n",
8086 [[source objectForKey:@"Type"] UTF8String],
8087 [[source objectForKey:@"URI"] UTF8String],
8088 [[source objectForKey:@"Distribution"] UTF8String]
8096 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8097 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8098 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8099 [container_ presentModalViewController:navigation animated:YES];
8102 detachNewThreadSelector:@selector(update_)
8105 title:UCLocalize("UPDATING_SOURCES")
8109 - (void) reloadData {
8110 @synchronized (self) {
8116 pkgProblemResolver *resolver = [database_ resolver];
8118 resolver->InstallProtect();
8119 if (!resolver->Resolve(true))
8123 - (CGRect) popUpBounds {
8124 return [[tabbar_ view] bounds];
8128 if (![database_ prepare])
8131 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8132 [page setDelegate:self];
8133 CYNavigationController *confirm_ = [[CYNavigationController alloc] initWithRootViewController:page];
8134 [confirm_ setDelegate:self];
8136 if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8137 [container_ presentModalViewController:confirm_ animated:YES];
8143 @synchronized (self) {
8148 - (void) clearPackage:(Package *)package {
8149 @synchronized (self) {
8156 - (void) installPackages:(NSArray *)packages {
8157 @synchronized (self) {
8158 for (Package *package in packages)
8165 - (void) installPackage:(Package *)package {
8166 @synchronized (self) {
8173 - (void) removePackage:(Package *)package {
8174 @synchronized (self) {
8181 - (void) distUpgrade {
8182 @synchronized (self) {
8183 if (![database_ upgrade])
8190 @synchronized (self) {
8195 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8196 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8198 if (navigation != nil) {
8199 [navigation pushViewController:progress animated:YES];
8201 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8202 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8203 [container_ presentModalViewController:navigation animated:YES];
8207 detachNewThreadSelector:@selector(perform)
8210 title:UCLocalize("RUNNING")
8214 - (void) progressControllerIsComplete:(ProgressController *)progress {
8218 - (void) setPage:(CYViewController *)page {
8219 [page setDelegate:self];
8221 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8222 [navController setViewControllers:[NSArray arrayWithObject:page] animated:NO];
8223 for (CYNavigationController *page in [tabbar_ viewControllers]) {
8224 if (page != navController) [page setViewControllers:nil];
8228 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8229 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8230 [browser loadURL:url];
8234 - (SectionsController *) sectionsController {
8235 if (sections_ == nil)
8236 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8240 - (ChangesController *) changesController {
8241 if (changes_ == nil)
8242 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8246 - (ManageController *) manageController {
8247 if (manage_ == nil) {
8248 manage_ = (ManageController *) [[self
8249 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8250 withClass:[ManageController class]
8252 if (!IsWildcat_) queueDelegate_ = manage_;
8257 - (SearchController *) searchController {
8259 search_ = [[SearchController alloc] initWithDatabase:database_];
8263 - (SourceTable *) sourcesController {
8264 if (sources_ == nil)
8265 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8269 - (InstalledController *) installedController {
8270 if (installed_ == nil) {
8271 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8272 if (IsWildcat_) queueDelegate_ = installed_;
8277 - (void) tabBarController:(id)tabBarController didSelectViewController:(UIViewController *)viewController {
8278 int tag = [[viewController tabBarItem] tag];
8280 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8282 } else if (tag_ == 1) {
8283 [[self sectionsController] resetView];
8287 case kCydiaTag: _setHomePage(self); break;
8289 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8290 case kChangesTag: [self setPage:[self changesController]]; break;
8291 case kManageTag: [self setPage:[self manageController]]; break;
8292 case kInstalledTag: [self setPage:[self installedController]]; break;
8293 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8294 case kSearchTag: [self setPage:[self searchController]]; break;
8302 - (void) showSettings {
8303 RoleController *role = [[RoleController alloc] initWithDatabase:database_ delegate:self];
8304 CYNavigationController *nav = [[CYNavigationController alloc] initWithRootViewController:role];
8305 if (IsWildcat_) [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8306 [container_ presentModalViewController:nav animated:YES];
8309 - (void) setPackageController:(PackageController *)view {
8311 [view setPackage:nil];
8312 #if RecyclePackageViews
8313 if ([details_ count] < 3)
8314 [details_ addObject:view];
8319 - (PackageController *) _packageController {
8320 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8323 - (PackageController *) packageController {
8324 #if RecyclePackageViews
8325 PackageController *view;
8326 size_t count([details_ count]);
8329 view = [self _packageController];
8331 [details_ addObject:[self _packageController]];
8333 view = [[[details_ lastObject] retain] autorelease];
8334 [details_ removeLastObject];
8341 return [self _packageController];
8345 - (void) cancelAndClear:(bool)clear {
8346 @synchronized (self) {
8348 /* XXX: clear marks instead of reloading data */
8349 /*pkgCacheFile &cache([database_ cache]);
8350 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
8351 if (!cache[iterator].Keep()) cache->MarkKeep(iterator, false, false);
8357 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kManageTag] != -1 ? [self indexOfTabWithTag:kManageTag] : [self indexOfTabWithTag:kInstalledTag]] tabBarItem] setBadgeValue:nil];
8358 [queueDelegate_ queueStatusDidChange];*/
8363 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kManageTag] != -1 ? [self indexOfTabWithTag:kManageTag] : [self indexOfTabWithTag:kInstalledTag]] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8364 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8366 [queueDelegate_ queueStatusDidChange];
8371 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8372 NSString *context([alert context]);
8374 if ([context isEqualToString:@"fixhalf"]) {
8375 if (button == [alert firstOtherButtonIndex]) {
8376 @synchronized (self) {
8377 for (Package *broken in broken_) {
8380 NSString *id = [broken id];
8381 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8382 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8383 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8384 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8390 } else if (button == [alert cancelButtonIndex]) {
8391 [broken_ removeAllObjects];
8395 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8396 } else if ([context isEqualToString:@"upgrade"]) {
8397 if (button == [alert firstOtherButtonIndex]) {
8398 @synchronized (self) {
8399 for (Package *essential in essential_)
8400 [essential install];
8405 } else if (button == [alert firstOtherButtonIndex] + 1) {
8407 } else if (button == [alert cancelButtonIndex]) {
8411 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8415 - (void) system:(NSString *)command { _pooled
8416 system([command UTF8String]);
8419 - (void) applicationWillSuspend {
8421 [super applicationWillSuspend];
8424 - (void) applicationSuspend:(__GSEvent *)event {
8425 // FIXME: This needs to be fixed, but we no longer have a progress_.
8426 // What's the best solution?
8427 if (hud_ == nil)// && ![progress_ isRunning])
8428 [super applicationSuspend:event];
8431 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8433 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8436 - (void) _setSuspended:(BOOL)value {
8438 [super _setSuspended:value];
8441 - (UIProgressHUD *) addProgressHUD {
8442 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8443 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8445 [window_ setUserInteractionEnabled:NO];
8447 [[container_ view] addSubview:hud];
8451 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8453 [hud removeFromSuperview];
8454 [window_ setUserInteractionEnabled:YES];
8457 - (CYViewController *) pageForPackage:(NSString *)name {
8458 if (Package *package = [database_ packageWithName:name]) {
8459 PackageController *view([self packageController]);
8460 [view setPackage:package];
8463 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8464 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8465 return [self _pageForURL:url withClass:[CYBrowserController class]];
8469 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8473 NSString *href([url absoluteString]);
8474 if ([href hasPrefix:@"apptapp://package/"])
8475 return [self pageForPackage:[href substringFromIndex:18]];
8477 NSString *scheme([[url scheme] lowercaseString]);
8478 if (![scheme isEqualToString:@"cydia"])
8480 NSString *path([url absoluteString]);
8481 if ([path length] < 8)
8483 path = [path substringFromIndex:8];
8484 if (![path hasPrefix:@"/"])
8485 path = [@"/" stringByAppendingString:path];
8487 if ([path isEqualToString:@"/add-source"])
8488 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8489 else if ([path isEqualToString:@"/storage"])
8490 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8491 else if ([path isEqualToString:@"/sources"])
8492 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8493 else if ([path isEqualToString:@"/packages"])
8494 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8495 else if ([path hasPrefix:@"/url/"])
8496 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8497 else if ([path hasPrefix:@"/launch/"])
8498 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8499 else if ([path hasPrefix:@"/package-settings/"])
8500 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8501 else if ([path hasPrefix:@"/package-signature/"])
8502 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8503 else if ([path hasPrefix:@"/package/"])
8504 return [self pageForPackage:[path substringFromIndex:9]];
8505 else if ([path hasPrefix:@"/files/"]) {
8506 NSString *name = [path substringFromIndex:7];
8508 if (Package *package = [database_ packageWithName:name]) {
8509 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8510 [files setPackage:package];
8518 - (void) applicationOpenURL:(NSURL *)url {
8519 [super applicationOpenURL:url];
8521 if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
8522 [self setPage:page];
8524 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8528 - (void) applicationWillResignActive:(UIApplication *)application {
8529 // Stop refreshing if you get a phone call or lock the device.
8530 if ([container_ updating]) [container_ cancelUpdate];
8532 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8533 [super applicationWillResignActive:application];
8536 - (void) applicationDidFinishLaunching:(id)unused {
8537 [CYBrowserController _initialize];
8539 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8541 Font12_ = [[UIFont systemFontOfSize:12] retain];
8542 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8543 Font14_ = [[UIFont systemFontOfSize:14] retain];
8544 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8545 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8549 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8550 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8552 UIScreen *screen([UIScreen mainScreen]);
8554 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8555 [window_ orderFront:self];
8556 [window_ makeKey:self];
8557 [window_ setHidden:NO];
8559 database_ = [Database sharedInstance];
8562 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8563 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8564 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8565 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8566 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8567 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8568 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8569 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8570 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8573 [self setIdleTimerDisabled:YES];
8575 hud_ = [self addProgressHUD];
8576 [hud_ setText:@"Reorganizing:\n\nWill Automatically\nClose When Done"];
8577 [self setStatusBarShowsProgress:YES];
8579 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8581 [self setStatusBarShowsProgress:NO];
8582 [self removeProgressHUD:hud_];
8585 if (ExecFork() == 0) {
8586 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8587 perror("launchctl stop");
8595 NSMutableArray *items([NSMutableArray arrayWithObjects:
8596 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8597 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8598 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8599 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8603 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8604 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8606 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8609 NSMutableArray *controllers([NSMutableArray array]);
8611 for (UITabBarItem *item in items) {
8612 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8613 [controller setTabBarItem:item];
8614 [controllers addObject:controller];
8617 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8618 [tabbar_ setViewControllers:controllers];
8619 [tabbar_ setDelegate:self];
8620 [tabbar_ setSelectedIndex:0];
8622 container_ = [[CYContainer alloc] initWithDatabase:database_];
8623 [container_ setUpdateDelegate:self];
8624 [container_ setTabBarController:tabbar_];
8625 [window_ addSubview:[container_ view]];
8627 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8632 [self showSettings];
8636 [UIKeyboard initImplementationNow];
8640 #if RecyclePackageViews
8641 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8642 [details_ addObject:[self _packageController]];
8643 [details_ addObject:[self _packageController]];
8651 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8652 if (item != nil && IsWildcat_) {
8653 [sheet showFromBarButtonItem:item animated:YES];
8655 [sheet showInView:window_];
8662 id Alloc_(id self, SEL selector) {
8663 id object = alloc_(self, selector);
8664 lprintf("[%s]A-%p\n", self->isa->name, object);
8669 id Dealloc_(id self, SEL selector) {
8670 id object = dealloc_(self, selector);
8671 lprintf("[%s]D-%p\n", self->isa->name, object);
8675 Class $WebDefaultUIKitDelegate;
8677 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8678 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8679 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8680 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8683 static NSNumber *shouldPlayKeyboardSounds;
8687 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8689 case 1104: // Keyboard Button Clicked
8690 case 1105: // Keyboard Delete Repeated
8691 if (shouldPlayKeyboardSounds == nil) {
8692 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8693 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8696 if (![shouldPlayKeyboardSounds boolValue])
8700 _UIHardware$_playSystemSound$(self, _cmd, sound);
8704 int main(int argc, char *argv[]) { _pooled
8707 if (Class $UIDevice = objc_getClass("UIDevice")) {
8708 UIDevice *device([$UIDevice currentDevice]);
8709 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8713 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8715 /* Library Hacks {{{ */
8716 class_addMethod(objc_getClass("WebScriptObject"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &WebScriptObject$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8717 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8719 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8720 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8721 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8722 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8723 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8726 $UIHardware = objc_getClass("UIHardware");
8727 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8728 if (UIHardware$_playSystemSound$ != NULL) {
8729 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8730 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8733 /* Set Locale {{{ */
8734 Locale_ = CFLocaleCopyCurrent();
8735 Languages_ = [NSLocale preferredLanguages];
8736 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8737 //NSLog(@"%@", [Languages_ description]);
8740 if (Languages_ == nil || [Languages_ count] == 0)
8741 // XXX: consider just setting to C and then falling through?
8744 lang = [[Languages_ objectAtIndex:0] UTF8String];
8745 setenv("LANG", lang, true);
8748 //std::setlocale(LC_ALL, lang);
8749 NSLog(@"Setting Language: %s", lang);
8752 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8754 /* Parse Arguments {{{ */
8755 bool substrate(false);
8761 for (int argi(1); argi != argc; ++argi)
8762 if (strcmp(argv[argi], "--") == 0) {
8764 argv[argi] = argv[0];
8770 for (int argi(1); argi != arge; ++argi)
8771 if (strcmp(args[argi], "--substrate") == 0)
8774 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8778 App_ = [[NSBundle mainBundle] bundlePath];
8779 Home_ = NSHomeDirectory();
8785 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8786 alloc_ = alloc->method_imp;
8787 alloc->method_imp = (IMP) &Alloc_;*/
8789 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8790 dealloc_ = dealloc->method_imp;
8791 dealloc->method_imp = (IMP) &Dealloc_;*/
8793 /* System Information {{{ */
8797 size = sizeof(maxproc);
8798 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8799 perror("sysctlbyname(\"kern.maxproc\", ?)");
8800 else if (maxproc < 64) {
8802 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8803 perror("sysctlbyname(\"kern.maxproc\", #)");
8806 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8807 char *osversion = new char[size];
8808 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8809 perror("sysctlbyname(\"kern.osversion\", ?)");
8811 System_ = [NSString stringWithUTF8String:osversion];
8813 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8814 char *machine = new char[size];
8815 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8816 perror("sysctlbyname(\"hw.machine\", ?)");
8820 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8821 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8822 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8823 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8827 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8828 NSData *data((NSData *) ecid);
8829 size_t length([data length]);
8830 uint8_t bytes[length];
8831 [data getBytes:bytes];
8832 char string[length * 2 + 1];
8833 for (size_t i(0); i != length; ++i)
8834 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8835 ChipID_ = [NSString stringWithUTF8String:string];
8839 IOObjectRelease(service);
8843 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8845 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8846 Build_ = [system objectForKey:@"ProductBuildVersion"];
8847 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8848 Product_ = [info objectForKey:@"SafariProductVersion"];
8849 Safari_ = [info objectForKey:@"CFBundleVersion"];
8852 /* Load Database {{{ */
8854 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8856 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8859 if (Metadata_ == NULL)
8860 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8862 Settings_ = [Metadata_ objectForKey:@"Settings"];
8864 Packages_ = [Metadata_ objectForKey:@"Packages"];
8865 Sections_ = [Metadata_ objectForKey:@"Sections"];
8866 Sources_ = [Metadata_ objectForKey:@"Sources"];
8868 Token_ = [Metadata_ objectForKey:@"Token"];
8871 if (Settings_ != nil)
8872 Role_ = [Settings_ objectForKey:@"Role"];
8874 if (Packages_ == nil) {
8875 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8876 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8879 if (Sections_ == nil) {
8880 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8881 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8884 if (Sources_ == nil) {
8885 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8886 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8891 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8894 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8896 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
8897 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
8898 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8899 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8900 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8901 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8903 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
8905 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8906 unlink("/tmp/.cydia.fw");
8908 } else if (access("/User", F_OK) != 0 || version < 2) {
8911 system("/usr/libexec/cydia/firmware.sh");
8915 _assert([[NSFileManager defaultManager]
8916 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8917 withIntermediateDirectories:YES
8922 if (access("/tmp/cydia.chk", F_OK) == 0) {
8923 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8924 _assert(errno == ENOENT);
8925 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8926 _assert(errno == ENOENT);
8929 /* APT Initialization {{{ */
8930 _assert(pkgInitConfig(*_config));
8931 _assert(pkgInitSystem(*_config, _system));
8934 _config->Set("APT::Acquire::Translation", lang);
8935 _config->Set("Acquire::http::Timeout", 15);
8936 _config->Set("Acquire::http::MaxParallel", 3);
8938 /* Color Choices {{{ */
8939 space_ = CGColorSpaceCreateDeviceRGB();
8941 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8942 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8943 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8944 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8945 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8946 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8947 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8948 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8949 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8951 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8952 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8954 /* UIKit Configuration {{{ */
8955 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8956 if ($GSFontSetUseLegacyFontMetrics != NULL)
8957 $GSFontSetUseLegacyFontMetrics(YES);
8959 // XXX: I have a feeling this was important
8960 //UIKeyboardDisableAutomaticAppearance();
8963 Colon_ = UCLocalize("COLON_DELIMITED");
8964 Error_ = UCLocalize("ERROR");
8965 Warning_ = UCLocalize("WARNING");
8968 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
8970 CGColorSpaceRelease(space_);