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 <UIKit/UIKit.h>
63 #include "iPhonePrivate.h"
65 #include <IOKit/IOKitLib.h>
67 #include <WebCore/WebCoreThread.h>
74 #include <ext/stdio_filebuf.h>
78 #include <apt-pkg/acquire.h>
79 #include <apt-pkg/acquire-item.h>
80 #include <apt-pkg/algorithms.h>
81 #include <apt-pkg/cachefile.h>
82 #include <apt-pkg/clean.h>
83 #include <apt-pkg/configuration.h>
84 #include <apt-pkg/debindexfile.h>
85 #include <apt-pkg/debmetaindex.h>
86 #include <apt-pkg/error.h>
87 #include <apt-pkg/init.h>
88 #include <apt-pkg/mmap.h>
89 #include <apt-pkg/pkgrecords.h>
90 #include <apt-pkg/sha1.h>
91 #include <apt-pkg/sourcelist.h>
92 #include <apt-pkg/sptr.h>
93 #include <apt-pkg/strutl.h>
94 #include <apt-pkg/tagfile.h>
96 #include <apr-1/apr_pools.h>
98 #include <sys/types.h>
100 #include <sys/sysctl.h>
101 #include <sys/param.h>
102 #include <sys/mount.h>
109 #include <mach-o/nlist.h>
119 #include <ext/hash_map>
121 #include "UICaboodle/BrowserView.h"
122 #include "UICaboodle/ResetView.h"
124 #include "substrate.h"
126 // Apple's sample Reachability code, ASPL licensed.
127 #include "Reachability.h"
134 #define _timestamp ({ \
136 gettimeofday(&tv, NULL); \
137 tv.tv_sec * 1000000 + tv.tv_usec; \
140 typedef std::vector<class ProfileTime *> TimeList;
150 ProfileTime(const char *name) :
154 times_.push_back(this);
157 void AddTime(uint64_t time) {
164 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
176 ProfileTimer(ProfileTime &time) :
183 time_.AddTime(_timestamp - start_);
188 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
190 std::cerr << "========" << std::endl;
193 #define _profile(name) { \
194 static ProfileTime name(#name); \
195 ProfileTimer _ ## name(name);
200 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
202 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
204 void NSLogPoint(const char *fix, const CGPoint &point) {
205 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
208 void NSLogRect(const char *fix, const CGRect &rect) {
209 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
212 static _finline NSString *CydiaURL(NSString *path) {
214 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
215 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
216 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
217 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
218 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
219 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
222 static _finline void UpdateExternalStatus(uint64_t newStatus) {
224 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
225 notify_set_state(notify_token, newStatus);
226 notify_cancel(notify_token);
228 notify_post("com.saurik.Cydia.status");
231 /* [NSObject yieldToSelector:(withObject:)] {{{*/
232 @interface NSObject (Cydia)
233 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
234 - (id) yieldToSelector:(SEL)selector;
237 @implementation NSObject (Cydia)
242 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
243 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
244 id object([[context objectAtIndex:1] nonretainedObjectValue]);
245 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
247 /* XXX: deal with exceptions */
248 id value([self performSelector:selector withObject:object]);
250 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
251 [context removeAllObjects];
252 if ([signature methodReturnLength] != 0 && value != nil)
253 [context addObject:value];
258 performSelectorOnMainThread:@selector(doNothing)
264 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
265 /*return [self performSelector:selector withObject:object];*/
267 volatile bool stopped(false);
269 NSMutableArray *context([NSMutableArray arrayWithObjects:
270 [NSValue valueWithPointer:selector],
271 [NSValue valueWithNonretainedObject:object],
272 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
275 NSThread *thread([[[NSThread alloc]
277 selector:@selector(_yieldToContext:)
283 NSRunLoop *loop([NSRunLoop currentRunLoop]);
284 NSDate *future([NSDate distantFuture]);
286 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
288 return [context count] == 0 ? nil : [context objectAtIndex:0];
291 - (id) yieldToSelector:(SEL)selector {
292 return [self yieldToSelector:selector withObject:nil];
298 @interface CYActionSheet : UIAlertView {
302 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
305 @implementation CYActionSheet
307 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
308 if ((self = [super init])) {
309 [self setTitle:title];
310 [self setDelegate:self];
311 for (NSString *button in buttons) [self addButtonWithTitle:button];
312 [self setCancelButtonIndex:index];
316 - (void)_updateFrameForDisplay {
317 [super _updateFrameForDisplay];
318 if ([self cancelButtonIndex] == -1) {
319 NSArray *buttons = [self buttons];
320 if ([buttons count]) {
321 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
322 for (UIThreePartButton *button in buttons)
323 [button setBackground:background forState:0];
328 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
329 button_ = buttonIndex + 1;
333 [self dismissWithClickedButtonIndex:-1 animated:YES];
336 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
337 [self setRunsModal:YES];
345 /* NSForcedOrderingSearch doesn't work on the iPhone */
346 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
347 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
348 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
350 /* Information Dictionaries {{{ */
351 @interface NSMutableArray (Cydia)
352 - (void) addInfoDictionary:(NSDictionary *)info;
355 @implementation NSMutableArray (Cydia)
357 - (void) addInfoDictionary:(NSDictionary *)info {
358 [self addObject:info];
363 @interface NSMutableDictionary (Cydia)
364 - (void) addInfoDictionary:(NSDictionary *)info;
367 @implementation NSMutableDictionary (Cydia)
369 - (void) addInfoDictionary:(NSDictionary *)info {
370 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
376 #define lprintf(args...) fprintf(stderr, args)
379 #define TraceLogging (1 && !ForRelease)
380 #define HistogramInsertionSort (0 && !ForRelease)
381 #define ProfileTimes (0 && !ForRelease)
382 #define ForSaurik (0 && !ForRelease)
383 #define LogBrowser (0 && !ForRelease)
384 #define TrackResize (0 && !ForRelease)
385 #define ManualRefresh (0 && !ForRelease)
386 #define ShowInternals (0 && !ForRelease)
387 #define IgnoreInstall (0 && !ForRelease)
388 #define RecycleWebViews 0
389 #define RecyclePackageViews (1 && ForRelease)
390 #define AlwaysReload (1 && !ForRelease)
394 #define _trace(args...)
399 #define _profile(name) {
402 #define PrintTimes() do {} while (false)
406 typedef uint32_t (*SKRadixFunction)(id, void *);
408 @interface NSMutableArray (Radix)
409 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
410 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
418 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
419 struct RadixItem_ *lhs(swap), *rhs(swap + count);
421 static const size_t width = 32;
422 static const size_t bits = 11;
423 static const size_t slots = 1 << bits;
424 static const size_t passes = (width + (bits - 1)) / bits;
426 size_t *hist(new size_t[slots]);
428 for (size_t pass(0); pass != passes; ++pass) {
429 memset(hist, 0, sizeof(size_t) * slots);
431 for (size_t i(0); i != count; ++i) {
432 uint32_t key(lhs[i].key);
434 key &= _not(uint32_t) >> width - bits;
439 for (size_t i(0); i != slots; ++i) {
440 size_t local(offset);
445 for (size_t i(0); i != count; ++i) {
446 uint32_t key(lhs[i].key);
448 key &= _not(uint32_t) >> width - bits;
449 rhs[hist[key]++] = lhs[i];
452 RadixItem_ *tmp(lhs);
459 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
460 for (size_t i(0); i != count; ++i)
461 [values addObject:[self objectAtIndex:lhs[i].index]];
462 [self setArray:values];
467 @implementation NSMutableArray (Radix)
469 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
470 size_t count([self count]);
475 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
476 [invocation setSelector:selector];
477 [invocation setArgument:&object atIndex:2];
479 /* XXX: this is an unsafe optimization of doomy hell */
480 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
481 _assert(method != NULL);
482 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
483 _assert(imp != NULL);
486 struct RadixItem_ *swap(new RadixItem_[count * 2]);
488 for (size_t i(0); i != count; ++i) {
489 RadixItem_ &item(swap[i]);
492 id object([self objectAtIndex:i]);
495 [invocation setTarget:object];
497 [invocation getReturnValue:&item.key];
499 item.key = imp(object, selector, object);
503 RadixSort_(self, count, swap);
506 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
507 size_t count([self count]);
508 struct RadixItem_ *swap(new RadixItem_[count * 2]);
510 for (size_t i(0); i != count; ++i) {
511 RadixItem_ &item(swap[i]);
514 id object([self objectAtIndex:i]);
515 item.key = function(object, argument);
518 RadixSort_(self, count, swap);
523 /* Insertion Sort {{{ */
525 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
526 const char *ptr = (const char *)list;
528 CFIndex half = count / 2;
529 const char *probe = ptr + elementSize * half;
530 CFComparisonResult cr = comparator(element, probe, context);
531 if (0 == cr) return (probe - (const char *)list) / elementSize;
532 ptr = (cr < 0) ? ptr : probe + elementSize;
533 count = (cr < 0) ? half : (half + (count & 1) - 1);
535 return (ptr - (const char *)list) / elementSize;
538 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
539 const char *ptr = (const char *)list;
541 CFIndex half = count / 2;
542 const char *probe = ptr + elementSize * half;
543 CFComparisonResult cr = comparator(element, probe, context);
544 if (0 == cr) return (probe - (const char *)list) / elementSize;
545 ptr = (cr < 0) ? ptr : probe + elementSize;
546 count = (cr < 0) ? half : (half + (count & 1) - 1);
548 return (ptr - (const char *)list) / elementSize;
551 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
552 if (range.length == 0)
554 const void **values(new const void *[range.length]);
555 CFArrayGetValues(array, range, values);
557 #if HistogramInsertionSort
558 uint32_t total(0), *offsets(new uint32_t[range.length]);
561 for (CFIndex index(1); index != range.length; ++index) {
562 const void *value(values[index]);
563 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
564 CFIndex correct(index);
565 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
568 if (correct != index) {
569 size_t offset(index - correct);
570 #if HistogramInsertionSort
574 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
576 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
577 values[correct] = value;
581 CFArrayReplaceValues(array, range, values, range.length);
584 #if HistogramInsertionSort
585 for (CFIndex index(0); index != range.length; ++index)
586 if (offsets[index] != 0)
587 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
588 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
595 /* Apple Bug Fixes {{{ */
596 @implementation UIWebDocumentView (Cydia)
598 - (void) _setScrollerOffset:(CGPoint)offset {
599 UIScroller *scroller([self _scroller]);
601 CGSize size([scroller contentSize]);
602 CGSize bounds([scroller bounds].size);
605 max.x = size.width - bounds.width;
606 max.y = size.height - bounds.height;
614 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
615 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
617 [scroller setOffset:offset];
623 NSUInteger WebScriptObject$countByEnumeratingWithState$objects$count$(WebScriptObject *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
624 size_t length([self count] - state->state);
627 else if (length > count)
629 for (size_t i(0); i != length; ++i)
630 objects[i] = [self objectAtIndex:state->state++];
631 state->itemsPtr = objects;
632 state->mutationsPtr = (unsigned long *) self;
636 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
637 size_t length([self length] - state->state);
640 else if (length > count)
642 for (size_t i(0); i != length; ++i)
643 objects[i] = [self item:state->state++];
644 state->itemsPtr = objects;
645 state->mutationsPtr = (unsigned long *) self;
649 /* Cydia NSString Additions {{{ */
650 @interface NSString (Cydia)
651 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
652 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
653 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
654 - (NSComparisonResult) compareByPath:(NSString *)other;
655 - (NSString *) stringByCachingURLWithCurrentCDN;
656 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
659 @implementation NSString (Cydia)
661 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
662 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
665 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
666 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
667 memcpy(data, bytes, length);
668 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
671 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
672 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
675 - (NSComparisonResult) compareByPath:(NSString *)other {
676 NSString *prefix = [self commonPrefixWithString:other options:0];
677 size_t length = [prefix length];
679 NSRange lrange = NSMakeRange(length, [self length] - length);
680 NSRange rrange = NSMakeRange(length, [other length] - length);
682 lrange = [self rangeOfString:@"/" options:0 range:lrange];
683 rrange = [other rangeOfString:@"/" options:0 range:rrange];
685 NSComparisonResult value;
687 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
688 value = NSOrderedSame;
689 else if (lrange.location == NSNotFound)
690 value = NSOrderedAscending;
691 else if (rrange.location == NSNotFound)
692 value = NSOrderedDescending;
694 value = NSOrderedSame;
696 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
697 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
698 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
699 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
701 NSComparisonResult result = [lpath compare:rpath];
702 return result == NSOrderedSame ? value : result;
705 - (NSString *) stringByCachingURLWithCurrentCDN {
707 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
708 withString:@"://cache.cydia.saurik.com/"
712 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
713 return [(id)CFURLCreateStringByAddingPercentEscapes(
718 kCFStringEncodingUTF8
725 /* C++ NSString Wrapper Cache {{{ */
732 _finline void clear_() {
733 if (cache_ != NULL) {
740 _finline bool empty() const {
744 _finline size_t size() const {
748 _finline char *data() const {
752 _finline void clear() {
757 _finline CYString() :
764 _finline ~CYString() {
768 void operator =(const CYString &rhs) {
772 if (rhs.cache_ == nil)
775 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
778 void set(apr_pool_t *pool, const char *data, size_t size) {
784 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
785 memcpy(temp, data, size);
792 _finline void set(apr_pool_t *pool, const char *data) {
793 set(pool, data, data == NULL ? 0 : strlen(data));
796 _finline void set(apr_pool_t *pool, const std::string &rhs) {
797 set(pool, rhs.data(), rhs.size());
800 bool operator ==(const CYString &rhs) const {
801 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
804 operator CFStringRef() {
805 if (cache_ == NULL) {
808 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
810 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
814 _finline operator id() {
815 return (NSString *) static_cast<CFStringRef>(*this);
819 /* C++ NSString Algorithm Adapters {{{ */
821 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
824 struct NSStringMapHash :
825 std::unary_function<NSString *, size_t>
827 _finline size_t operator ()(NSString *value) const {
828 return CFStringHashNSString((CFStringRef) value);
832 struct NSStringMapLess :
833 std::binary_function<NSString *, NSString *, bool>
835 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
836 return [lhs compare:rhs] == NSOrderedAscending;
840 struct NSStringMapEqual :
841 std::binary_function<NSString *, NSString *, bool>
843 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
844 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
845 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
846 //[lhs isEqualToString:rhs];
851 /* Perl-Compatible RegEx {{{ */
861 Pcre(const char *regex) :
866 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
869 lprintf("%d:%s\n", offset, error);
873 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
874 matches_ = new int[(capture_ + 1) * 3];
882 NSString *operator [](size_t match) {
883 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
886 bool operator ()(NSString *data) {
887 // XXX: length is for characters, not for bytes
888 return operator ()([data UTF8String], [data length]);
891 bool operator ()(const char *data, size_t size) {
893 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
897 /* Mime Addresses {{{ */
898 @interface Address : NSObject {
904 - (NSString *) address;
906 - (void) setAddress:(NSString *)address;
908 + (Address *) addressWithString:(NSString *)string;
909 - (Address *) initWithString:(NSString *)string;
912 @implementation Address
921 - (NSString *) name {
925 - (NSString *) address {
929 - (void) setAddress:(NSString *)address {
931 [address_ autorelease];
935 address_ = [address retain];
938 + (Address *) addressWithString:(NSString *)string {
939 return [[[Address alloc] initWithString:string] autorelease];
942 + (NSArray *) _attributeKeys {
943 return [NSArray arrayWithObjects:@"address", @"name", nil];
946 - (NSArray *) attributeKeys {
947 return [[self class] _attributeKeys];
950 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
951 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
954 - (Address *) initWithString:(NSString *)string {
955 if ((self = [super init]) != nil) {
956 const char *data = [string UTF8String];
957 size_t size = [string length];
959 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
961 if (address_r(data, size)) {
962 name_ = [address_r[1] retain];
963 address_ = [address_r[2] retain];
965 name_ = [string retain];
973 /* CoreGraphics Primitives {{{ */
984 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
987 Set(space, red, green, blue, alpha);
992 CGColorRelease(color_);
999 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1001 float color[] = {red, green, blue, alpha};
1002 color_ = CGColorCreate(space, color);
1005 operator CGColorRef() {
1011 /* Random Global Variables {{{ */
1012 static const int PulseInterval_ = 50000;
1013 static const int ButtonBarWidth_ = 60;
1014 static const int ButtonBarHeight_ = 48;
1015 static const float KeyboardTime_ = 0.3f;
1018 static NSArray *Finishes_;
1020 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1021 #define NotifyConfig_ "/etc/notify.conf"
1023 static bool Queuing_;
1025 static CGColor Blue_;
1026 static CGColor Blueish_;
1027 static CGColor Black_;
1028 static CGColor Off_;
1029 static CGColor White_;
1030 static CGColor Gray_;
1031 static CGColor Green_;
1032 static CGColor Purple_;
1033 static CGColor Purplish_;
1035 static UIColor *InstallingColor_;
1036 static UIColor *RemovingColor_;
1038 static NSString *App_;
1039 static NSString *Home_;
1041 static BOOL Advanced_;
1042 static BOOL Ignored_;
1044 static UIFont *Font12_;
1045 static UIFont *Font12Bold_;
1046 static UIFont *Font14_;
1047 static UIFont *Font18Bold_;
1048 static UIFont *Font22Bold_;
1050 static const char *Machine_ = NULL;
1051 static const NSString *System_ = NULL;
1052 static const NSString *SerialNumber_ = nil;
1053 static const NSString *ChipID_ = nil;
1054 static const NSString *Token_ = nil;
1055 static const NSString *UniqueID_ = nil;
1056 static const NSString *Build_ = nil;
1057 static const NSString *Product_ = nil;
1058 static const NSString *Safari_ = nil;
1060 static CFLocaleRef Locale_;
1061 static NSArray *Languages_;
1062 static CGColorSpaceRef space_;
1064 static NSDictionary *SectionMap_;
1065 static NSMutableDictionary *Metadata_;
1066 static _transient NSMutableDictionary *Settings_;
1067 static _transient NSString *Role_;
1068 static _transient NSMutableDictionary *Packages_;
1069 static _transient NSMutableDictionary *Sections_;
1070 static _transient NSMutableDictionary *Sources_;
1071 static bool Changed_;
1072 static NSDate *now_;
1074 static bool IsWildcat_;
1077 static NSMutableArray *Documents_;
1081 /* Display Helpers {{{ */
1082 inline float Interpolate(float begin, float end, float fraction) {
1083 return (end - begin) * fraction + begin;
1086 /* XXX: localize this! */
1087 NSString *SizeString(double size) {
1088 bool negative = size < 0;
1093 while (size > 1024) {
1098 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1100 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1103 static _finline CFStringRef CFCString(const char *value) {
1104 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1107 const char *StripVersion_(const char *version) {
1108 const char *colon(strchr(version, ':'));
1110 version = colon + 1;
1114 CFStringRef StripVersion(const char *version) {
1115 const char *colon(strchr(version, ':'));
1117 version = colon + 1;
1118 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1120 return CFCString(version);
1123 NSString *LocalizeSection(NSString *section) {
1124 static Pcre title_r("^(.*?) \\((.*)\\)$");
1125 if (title_r(section)) {
1126 NSString *parent(title_r[1]);
1127 NSString *child(title_r[2]);
1129 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1130 LocalizeSection(parent),
1131 LocalizeSection(child)
1135 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1138 NSString *Simplify(NSString *title) {
1139 const char *data = [title UTF8String];
1140 size_t size = [title length];
1142 static Pcre square_r("^\\[(.*)\\]$");
1143 if (square_r(data, size))
1144 return Simplify(square_r[1]);
1146 static Pcre paren_r("^\\((.*)\\)$");
1147 if (paren_r(data, size))
1148 return Simplify(paren_r[1]);
1150 static Pcre title_r("^(.*?) \\((.*)\\)$");
1151 if (title_r(data, size))
1152 return Simplify(title_r[1]);
1158 NSString *GetLastUpdate() {
1159 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1162 return UCLocalize("NEVER_OR_UNKNOWN");
1164 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1165 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1167 CFRelease(formatter);
1169 return [(NSString *) formatted autorelease];
1172 bool isSectionVisible(NSString *section) {
1173 NSDictionary *metadata([Sections_ objectForKey:section]);
1174 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1175 return hidden == nil || ![hidden boolValue];
1180 /* Delegate Prototypes {{{ */
1184 @interface NSObject (ProgressDelegate)
1187 @protocol ProgressDelegate
1188 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1189 - (void) setProgressTitle:(NSString *)title;
1190 - (void) setProgressPercent:(float)percent;
1191 - (void) startProgress;
1192 - (void) addProgressOutput:(NSString *)output;
1193 - (bool) isCancelling:(size_t)received;
1196 @protocol ConfigurationDelegate
1197 - (void) repairWithSelector:(SEL)selector;
1198 - (void) setConfigurationData:(NSString *)data;
1201 @class PackageController;
1203 @protocol CydiaDelegate
1204 - (void) setPackageController:(PackageController *)view;
1205 - (void) clearPackage:(Package *)package;
1206 - (void) installPackage:(Package *)package;
1207 - (void) installPackages:(NSArray *)packages;
1208 - (void) removePackage:(Package *)package;
1209 - (void) beginUpdate;
1211 - (void) distUpgrade;
1213 - (void) updateData;
1215 - (void) showSettings;
1216 - (UIProgressHUD *) addProgressHUD;
1217 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1218 - (UCViewController *) pageForPackage:(NSString *)name;
1219 - (PackageController *) packageController;
1220 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1224 /* Status Delegation {{{ */
1226 public pkgAcquireStatus
1229 _transient NSObject<ProgressDelegate> *delegate_;
1237 void setDelegate(id delegate) {
1238 delegate_ = delegate;
1241 NSObject<ProgressDelegate> *getDelegate() const {
1245 virtual bool MediaChange(std::string media, std::string drive) {
1249 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1252 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1253 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1254 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1257 virtual void Done(pkgAcquire::ItemDesc &item) {
1260 virtual void Fail(pkgAcquire::ItemDesc &item) {
1262 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1263 item.Owner->Status == pkgAcquire::Item::StatDone
1267 std::string &error(item.Owner->ErrorText);
1271 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1272 NSArray *fields([description componentsSeparatedByString:@" "]);
1273 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1275 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1276 withObject:[NSArray arrayWithObjects:
1277 [NSString stringWithUTF8String:error.c_str()],
1284 virtual bool Pulse(pkgAcquire *Owner) {
1285 bool value = pkgAcquireStatus::Pulse(Owner);
1288 double(CurrentBytes + CurrentItems) /
1289 double(TotalBytes + TotalItems)
1292 [delegate_ setProgressPercent:percent];
1293 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1296 virtual void Start() {
1297 [delegate_ startProgress];
1300 virtual void Stop() {
1304 /* Progress Delegation {{{ */
1309 _transient id<ProgressDelegate> delegate_;
1313 virtual void Update() {
1314 /*if (abs(Percent - percent_) > 2)
1315 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1319 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1320 [delegate_ setProgressPercent:(Percent / 100)];*/
1330 void setDelegate(id delegate) {
1331 delegate_ = delegate;
1334 id getDelegate() const {
1338 virtual void Done() {
1340 //[delegate_ setProgressPercent:1];
1345 /* Database Interface {{{ */
1346 typedef std::map< unsigned long, _H<Source> > SourceMap;
1348 @interface Database : NSObject {
1354 pkgCacheFile cache_;
1355 pkgDepCache::Policy *policy_;
1356 pkgRecords *records_;
1357 pkgProblemResolver *resolver_;
1358 pkgAcquire *fetcher_;
1360 SPtr<pkgPackageManager> manager_;
1361 pkgSourceList *list_;
1364 NSMutableArray *packages_;
1366 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1375 + (Database *) sharedInstance;
1378 - (void) _readCydia:(NSNumber *)fd;
1379 - (void) _readStatus:(NSNumber *)fd;
1380 - (void) _readOutput:(NSNumber *)fd;
1384 - (Package *) packageWithName:(NSString *)name;
1386 - (pkgCacheFile &) cache;
1387 - (pkgDepCache::Policy *) policy;
1388 - (pkgRecords *) records;
1389 - (pkgProblemResolver *) resolver;
1390 - (pkgAcquire &) fetcher;
1391 - (pkgSourceList &) list;
1392 - (NSArray *) packages;
1393 - (NSArray *) sources;
1394 - (void) reloadData;
1402 - (void) setVisible;
1404 - (void) updateWithStatus:(Status &)status;
1406 - (void) setDelegate:(id)delegate;
1407 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1410 /* Delegate Helpers {{{ */
1411 @implementation NSObject (ProgressDelegate)
1413 - (void) _setProgressErrorPackage:(NSArray *)args {
1414 [self performSelector:@selector(setProgressError:forPackage:)
1415 withObject:[args objectAtIndex:0]
1416 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1420 - (void) _setProgressErrorTitle:(NSArray *)args {
1421 [self performSelector:@selector(setProgressError:withTitle:)
1422 withObject:[args objectAtIndex:0]
1423 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1427 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1428 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1429 withObject:[NSArray arrayWithObjects:error, title, nil]
1434 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1435 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1436 // XXX: holy typecast batman!
1437 [(id<ProgressDelegate>)self setProgressError:error withTitle:(package == nil ? id : [package name])];
1443 /* Source Class {{{ */
1444 @interface Source : NSObject {
1445 CYString depiction_;
1446 CYString description_;
1452 CYString distribution_;
1457 NSString *authority_;
1459 CYString defaultIcon_;
1461 NSDictionary *record_;
1465 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1467 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1469 - (NSString *) depictionForPackage:(NSString *)package;
1470 - (NSString *) supportForPackage:(NSString *)package;
1472 - (NSDictionary *) record;
1476 - (NSString *) distribution;
1477 - (NSString *) type;
1479 - (NSString *) host;
1481 - (NSString *) name;
1482 - (NSString *) description;
1483 - (NSString *) label;
1484 - (NSString *) origin;
1485 - (NSString *) version;
1487 - (NSString *) defaultIcon;
1491 @implementation Source
1495 distribution_.clear();
1498 description_.clear();
1504 defaultIcon_.clear();
1506 if (record_ != nil) {
1516 if (authority_ != nil) {
1517 [authority_ release];
1527 + (NSArray *) _attributeKeys {
1528 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1531 - (NSArray *) attributeKeys {
1532 return [[self class] _attributeKeys];
1535 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1536 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1539 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1542 trusted_ = index->IsTrusted();
1544 uri_.set(pool, index->GetURI());
1545 distribution_.set(pool, index->GetDist());
1546 type_.set(pool, index->GetType());
1548 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1549 if (dindex != NULL) {
1551 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1554 pkgTagFile tags(&fd);
1556 pkgTagSection section;
1563 {"default-icon", &defaultIcon_},
1564 {"depiction", &depiction_},
1565 {"description", &description_},
1567 {"origin", &origin_},
1568 {"support", &support_},
1569 {"version", &version_},
1572 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1573 const char *start, *end;
1575 if (section.Find(names[i].name_, start, end)) {
1576 CYString &value(*names[i].value_);
1577 value.set(pool, start, end - start);
1583 record_ = [Sources_ objectForKey:[self key]];
1585 record_ = [record_ retain];
1587 NSURL *url([NSURL URLWithString:uri_]);
1591 host_ = [[host_ lowercaseString] retain];
1596 authority_ = [url path];
1598 if (authority_ != nil)
1599 authority_ = [authority_ retain];
1602 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1603 if ((self = [super init]) != nil) {
1604 [self setMetaIndex:index inPool:pool];
1608 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1609 NSDictionary *lhr = [self record];
1610 NSDictionary *rhr = [source record];
1613 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1615 NSString *lhs = [self name];
1616 NSString *rhs = [source name];
1618 if ([lhs length] != 0 && [rhs length] != 0) {
1619 unichar lhc = [lhs characterAtIndex:0];
1620 unichar rhc = [rhs characterAtIndex:0];
1622 if (isalpha(lhc) && !isalpha(rhc))
1623 return NSOrderedAscending;
1624 else if (!isalpha(lhc) && isalpha(rhc))
1625 return NSOrderedDescending;
1628 return [lhs compare:rhs options:LaxCompareOptions_];
1631 - (NSString *) depictionForPackage:(NSString *)package {
1632 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1635 - (NSString *) supportForPackage:(NSString *)package {
1636 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1639 - (NSDictionary *) record {
1647 - (NSString *) uri {
1651 - (NSString *) distribution {
1652 return distribution_;
1655 - (NSString *) type {
1659 - (NSString *) key {
1660 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1663 - (NSString *) host {
1667 - (NSString *) name {
1668 return origin_.empty() ? authority_ : origin_;
1671 - (NSString *) description {
1672 return description_;
1675 - (NSString *) label {
1676 return label_.empty() ? authority_ : label_;
1679 - (NSString *) origin {
1683 - (NSString *) version {
1687 - (NSString *) defaultIcon {
1688 return defaultIcon_;
1693 /* Relationship Class {{{ */
1694 @interface Relationship : NSObject {
1699 - (NSString *) type;
1701 - (NSString *) name;
1705 @implementation Relationship
1713 - (NSString *) type {
1721 - (NSString *) name {
1728 /* Package Class {{{ */
1729 @interface Package : NSObject {
1733 pkgCache::VerIterator version_;
1734 pkgCache::PkgIterator iterator_;
1735 _transient Database *database_;
1736 pkgCache::VerFileIterator file_;
1743 NSString *section$_;
1750 CYString installed_;
1756 CYString depiction_;
1767 NSMutableArray *tags_;
1770 NSArray *relationships_;
1772 NSMutableDictionary *metadata_;
1773 _transient NSDate *firstSeen_;
1774 _transient NSDate *lastSeen_;
1778 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1779 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1781 - (pkgCache::PkgIterator) iterator;
1784 - (NSString *) section;
1785 - (NSString *) simpleSection;
1787 - (NSString *) longSection;
1788 - (NSString *) shortSection;
1792 - (Address *) maintainer;
1794 - (NSString *) longDescription;
1795 - (NSString *) shortDescription;
1798 - (NSMutableDictionary *) metadata;
1800 - (BOOL) subscribed;
1803 - (NSString *) latest;
1804 - (NSString *) installed;
1805 - (BOOL) uninstalled;
1808 - (BOOL) upgradableAndEssential:(BOOL)essential;
1811 - (BOOL) unfiltered;
1815 - (BOOL) halfConfigured;
1816 - (BOOL) halfInstalled;
1818 - (NSString *) mode;
1820 - (void) setVisible;
1823 - (NSString *) name;
1825 - (NSString *) homepage;
1826 - (NSString *) depiction;
1827 - (Address *) author;
1829 - (NSString *) support;
1831 - (NSArray *) files;
1832 - (NSArray *) relationships;
1833 - (NSArray *) warnings;
1834 - (NSArray *) applications;
1836 - (Source *) source;
1837 - (NSString *) role;
1839 - (BOOL) matches:(NSString *)text;
1841 - (bool) hasSupportingRole;
1842 - (BOOL) hasTag:(NSString *)tag;
1843 - (NSString *) primaryPurpose;
1844 - (NSArray *) purposes;
1845 - (bool) isCommercial;
1847 - (CYString &) cyname;
1849 - (uint32_t) compareBySection:(NSArray *)sections;
1851 - (uint32_t) compareForChanges;
1856 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1857 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1858 - (bool) isInstalledAndVisible:(NSNumber *)number;
1859 - (bool) isVisibleInSection:(NSString *)section;
1860 - (bool) isVisibleInSource:(Source *)source;
1864 uint32_t PackageChangesRadix(Package *self, void *) {
1869 uint32_t timestamp : 30;
1870 uint32_t ignored : 1;
1871 uint32_t upgradable : 1;
1875 bool upgradable([self upgradableAndEssential:YES]);
1876 value.bits.upgradable = upgradable ? 1 : 0;
1879 value.bits.timestamp = 0;
1880 value.bits.ignored = [self ignored] ? 0 : 1;
1881 value.bits.upgradable = 1;
1883 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1884 value.bits.ignored = 0;
1885 value.bits.upgradable = 0;
1888 return _not(uint32_t) - value.key;
1891 _finline static void Stifle(uint8_t &value) {
1894 uint32_t PackagePrefixRadix(Package *self, void *context) {
1895 size_t offset(reinterpret_cast<size_t>(context));
1896 CYString &name([self cyname]);
1898 size_t size(name.size());
1901 char *text(name.data());
1904 if (!isdigit(text[0]))
1908 while (size != digits && isdigit(text[digits]))
1918 if (offset == 0 && zeros != 0) {
1919 memset(data, '0', zeros);
1920 memcpy(data + zeros, text, 4 - zeros);
1922 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1923 if (size <= offset - zeros)
1926 text += offset - zeros;
1927 size -= offset - zeros;
1930 memcpy(data, text, 4);
1932 memcpy(data, text, size);
1933 memset(data + size, 0, 4 - size);
1936 for (size_t i(0); i != 4; ++i)
1937 if (isalpha(data[i]))
1942 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1944 /* XXX: ntohl may be more honest */
1945 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1948 CYString &(*PackageName)(Package *self, SEL sel);
1950 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1951 _profile(PackageNameCompare)
1952 CYString &lhi(PackageName(lhs, @selector(cyname)));
1953 CYString &rhi(PackageName(rhs, @selector(cyname)));
1954 CFStringRef lhn(lhi), rhn(rhi);
1957 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1958 else if (rhn == NULL)
1959 return NSOrderedDescending;
1961 _profile(PackageNameCompare$NumbersLast)
1962 if (!lhi.empty() && !rhi.empty()) {
1963 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1964 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1965 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1966 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1967 return lha ? NSOrderedAscending : NSOrderedDescending;
1971 CFIndex length = CFStringGetLength(lhn);
1973 _profile(PackageNameCompare$Compare)
1974 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1979 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1980 return PackageNameCompare(*lhs, *rhs, context);
1983 struct PackageNameOrdering :
1984 std::binary_function<Package *, Package *, bool>
1986 _finline bool operator ()(Package *lhs, Package *rhs) const {
1987 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1991 @implementation Package
1993 - (NSString *) description {
1994 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2000 if (section$_ != nil)
2001 [section$_ release];
2006 if (sponsor$_ != nil)
2007 [sponsor$_ release];
2008 if (author$_ != nil)
2015 if (relationships_ != nil)
2016 [relationships_ release];
2017 if (metadata_ != nil)
2018 [metadata_ release];
2023 + (NSString *) webScriptNameForSelector:(SEL)selector {
2024 if (selector == @selector(hasTag:))
2030 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2031 return [self webScriptNameForSelector:selector] == nil;
2034 + (NSArray *) _attributeKeys {
2035 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];
2038 - (NSArray *) attributeKeys {
2039 return [[self class] _attributeKeys];
2042 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2043 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2053 _profile(Package$parse)
2054 pkgRecords::Parser *parser;
2056 _profile(Package$parse$Lookup)
2057 parser = &[database_ records]->Lookup(file_);
2062 _profile(Package$parse$Find)
2068 {"depiction", &depiction_},
2069 {"homepage", &homepage_},
2070 {"website", &website},
2072 {"support", &support_},
2073 {"sponsor", &sponsor_},
2074 {"author", &author_},
2077 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2078 const char *start, *end;
2080 if (parser->Find(names[i].name_, start, end)) {
2081 CYString &value(*names[i].value_);
2082 _profile(Package$parse$Value)
2083 value.set(pool_, start, end - start);
2089 _profile(Package$parse$Tagline)
2090 const char *start, *end;
2091 if (parser->ShortDesc(start, end)) {
2092 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2095 while (stop != start && stop[-1] == '\r')
2097 tagline_.set(pool_, start, stop - start);
2101 _profile(Package$parse$Retain)
2102 if (homepage_.empty())
2103 homepage_ = website;
2104 if (homepage_ == depiction_)
2110 - (void) setVisible {
2111 visible_ = required_ && [self unfiltered];
2114 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2115 if ((self = [super init]) != nil) {
2116 _profile(Package$initWithVersion)
2117 @synchronized (database) {
2118 era_ = [database era];
2122 iterator_ = version.ParentPkg();
2123 database_ = database;
2125 _profile(Package$initWithVersion$Latest)
2126 latest_ = (NSString *) StripVersion(version_.VerStr());
2129 pkgCache::VerIterator current;
2130 _profile(Package$initWithVersion$Versions)
2131 current = iterator_.CurrentVer();
2133 installed_.set(pool_, StripVersion_(current.VerStr()));
2135 if (!version_.end())
2136 file_ = version_.FileList();
2138 pkgCache &cache([database_ cache]);
2139 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2143 _profile(Package$initWithVersion$Name)
2144 id_.set(pool_, iterator_.Name());
2145 name_.set(pool, iterator_.Display());
2149 _profile(Package$initWithVersion$Source)
2150 source_ = [database_ getSource:file_.File()];
2159 _profile(Package$initWithVersion$Tags)
2160 pkgCache::TagIterator tag(iterator_.TagList());
2162 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2164 const char *name(tag.Name());
2165 [tags_ addObject:(NSString *)CFCString(name)];
2166 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2167 role_ = (NSString *) CFCString(name + 6);
2168 if (required_ && strncmp(name, "require::", 9) == 0 && (
2173 } while (!tag.end());
2177 bool changed(false);
2178 NSString *key([id_ lowercaseString]);
2180 _profile(Package$initWithVersion$Metadata)
2181 metadata_ = [Packages_ objectForKey:key];
2183 if (metadata_ == nil) {
2186 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2187 firstSeen_, @"FirstSeen",
2188 latest_, @"LastVersion",
2193 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2194 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2196 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2197 subscribed_ = [subscribed boolValue];
2199 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2201 if (firstSeen_ == nil) {
2202 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2203 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2207 if (version == nil) {
2208 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2210 } else if (![version isEqualToString:latest_]) {
2211 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2213 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2218 metadata_ = [metadata_ retain];
2221 [Packages_ setObject:metadata_ forKey:key];
2226 _profile(Package$initWithVersion$Section)
2227 section_.set(pool_, iterator_.Section());
2230 obsolete_ = [self hasTag:@"cydia::obsolete"];
2231 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2233 } _end } return self;
2236 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2237 @synchronized ([Database class]) {
2238 pkgCache::VerIterator version;
2240 _profile(Package$packageWithIterator$GetCandidateVer)
2241 version = [database policy]->GetCandidateVer(iterator);
2247 return [[[Package alloc]
2248 initWithVersion:version
2255 - (pkgCache::PkgIterator) iterator {
2259 - (NSString *) section {
2260 if (section$_ == nil) {
2261 if (section_.empty())
2264 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2265 NSString *name(section_);
2268 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2269 if (NSString *rename = [value objectForKey:@"Rename"]) {
2274 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2278 - (NSString *) simpleSection {
2279 if (NSString *section = [self section])
2280 return Simplify(section);
2285 - (NSString *) longSection {
2286 return LocalizeSection([self section]);
2289 - (NSString *) shortSection {
2290 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2293 - (NSString *) uri {
2296 pkgIndexFile *index;
2297 pkgCache::PkgFileIterator file(file_.File());
2298 if (![database_ list].FindIndex(file, index))
2300 return [NSString stringWithUTF8String:iterator_->Path];
2301 //return [NSString stringWithUTF8String:file.Site()];
2302 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2306 - (Address *) maintainer {
2309 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2310 const std::string &maintainer(parser->Maintainer());
2311 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2315 return version_.end() ? 0 : version_->InstalledSize;
2318 - (NSString *) longDescription {
2321 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2322 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2324 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2325 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2326 if ([lines count] < 2)
2329 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2330 for (size_t i(1), e([lines count]); i != e; ++i) {
2331 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2332 [trimmed addObject:trim];
2335 return [trimmed componentsJoinedByString:@"\n"];
2338 - (NSString *) shortDescription {
2343 _profile(Package$index)
2344 CFStringRef name((CFStringRef) [self name]);
2345 if (CFStringGetLength(name) == 0)
2347 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2348 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2350 return toupper(character);
2354 - (NSMutableDictionary *) metadata {
2359 if (subscribed_ && lastSeen_ != nil)
2364 - (BOOL) subscribed {
2369 NSDictionary *metadata([self metadata]);
2370 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2371 return [ignored boolValue];
2376 - (NSString *) latest {
2380 - (NSString *) installed {
2384 - (BOOL) uninstalled {
2385 return installed_.empty();
2389 return !version_.end();
2392 - (BOOL) upgradableAndEssential:(BOOL)essential {
2393 _profile(Package$upgradableAndEssential)
2394 pkgCache::VerIterator current(iterator_.CurrentVer());
2396 return essential && essential_ && visible_;
2398 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2402 - (BOOL) essential {
2407 return [database_ cache][iterator_].InstBroken();
2410 - (BOOL) unfiltered {
2411 NSString *section([self section]);
2412 return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
2420 unsigned char current(iterator_->CurrentState);
2421 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2424 - (BOOL) halfConfigured {
2425 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2428 - (BOOL) halfInstalled {
2429 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2433 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2434 return state.Mode != pkgDepCache::ModeKeep;
2437 - (NSString *) mode {
2438 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2440 switch (state.Mode) {
2441 case pkgDepCache::ModeDelete:
2442 if ((state.iFlags & pkgDepCache::Purge) != 0)
2446 case pkgDepCache::ModeKeep:
2447 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2448 return @"REINSTALL";
2449 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2453 case pkgDepCache::ModeInstall:
2454 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2455 return @"REINSTALL";
2456 else*/ switch (state.Status) {
2458 return @"DOWNGRADE";
2464 return @"NEW_INSTALL";
2475 - (NSString *) name {
2476 return name_.empty() ? id_ : name_;
2479 - (UIImage *) icon {
2480 NSString *section = [self simpleSection];
2484 if ([icon_ hasPrefix:@"file:///"])
2485 // XXX: correct escaping
2486 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2487 if (icon == nil) if (section != nil)
2488 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2489 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2490 if ([dicon hasPrefix:@"file:///"])
2491 // XXX: correct escaping
2492 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2494 icon = [UIImage applicationImageNamed:@"unknown.png"];
2498 - (NSString *) homepage {
2502 - (NSString *) depiction {
2503 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2506 - (Address *) sponsor {
2507 if (sponsor$_ == nil) {
2508 if (sponsor_.empty())
2510 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2514 - (Address *) author {
2515 if (author$_ == nil) {
2516 if (author_.empty())
2518 author$_ = [[Address addressWithString:author_] retain];
2522 - (NSString *) support {
2523 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2526 - (NSArray *) files {
2527 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2528 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2531 fin.open([path UTF8String]);
2536 while (std::getline(fin, line))
2537 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2542 - (NSArray *) relationships {
2543 return relationships_;
2546 - (NSArray *) warnings {
2547 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2548 const char *name(iterator_.Name());
2550 size_t length(strlen(name));
2551 if (length < 2) invalid:
2552 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2553 else for (size_t i(0); i != length; ++i)
2555 /* XXX: technically this is not allowed */
2556 (name[i] < 'A' || name[i] > 'Z') &&
2557 (name[i] < 'a' || name[i] > 'z') &&
2558 (name[i] < '0' || name[i] > '9') &&
2559 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2562 if (strcmp(name, "cydia") != 0) {
2565 bool _private = false;
2568 bool repository = [[self section] isEqualToString:@"Repositories"];
2570 if (NSArray *files = [self files])
2571 for (NSString *file in files)
2572 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2574 else if (!user && [file isEqualToString:@"/User"])
2576 else if (!_private && [file isEqualToString:@"/private"])
2578 else if (!stash && [file isEqualToString:@"/var/stash"])
2581 /* XXX: this is not sensitive enough. only some folders are valid. */
2582 if (cydia && !repository)
2583 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2585 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2587 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2589 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2592 return [warnings count] == 0 ? nil : warnings;
2595 - (NSArray *) applications {
2596 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2598 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2600 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2601 if (NSArray *files = [self files])
2602 for (NSString *file in files)
2603 if (application_r(file)) {
2604 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2605 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2606 if ([id isEqualToString:me])
2609 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2611 display = application_r[1];
2613 NSString *bundle([file stringByDeletingLastPathComponent]);
2614 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2615 if (icon == nil || [icon length] == 0)
2617 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2619 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2620 [applications addObject:application];
2622 [application addObject:id];
2623 [application addObject:display];
2624 [application addObject:url];
2627 return [applications count] == 0 ? nil : applications;
2630 - (Source *) source {
2632 @synchronized (database_) {
2633 if ([database_ era] != era_ || file_.end())
2636 source_ = [database_ getSource:file_.File()];
2648 - (NSString *) role {
2652 - (BOOL) matches:(NSString *)text {
2658 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2659 if (range.location != NSNotFound)
2662 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2663 if (range.location != NSNotFound)
2666 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2667 if (range.location != NSNotFound)
2673 - (bool) hasSupportingRole {
2676 if ([role_ isEqualToString:@"enduser"])
2678 if ([Role_ isEqualToString:@"User"])
2680 if ([role_ isEqualToString:@"hacker"])
2682 if ([Role_ isEqualToString:@"Hacker"])
2684 if ([role_ isEqualToString:@"developer"])
2686 if ([Role_ isEqualToString:@"Developer"])
2691 - (BOOL) hasTag:(NSString *)tag {
2692 return tags_ == nil ? NO : [tags_ containsObject:tag];
2695 - (NSString *) primaryPurpose {
2696 for (NSString *tag in tags_)
2697 if ([tag hasPrefix:@"purpose::"])
2698 return [tag substringFromIndex:9];
2702 - (NSArray *) purposes {
2703 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2704 for (NSString *tag in tags_)
2705 if ([tag hasPrefix:@"purpose::"])
2706 [purposes addObject:[tag substringFromIndex:9]];
2707 return [purposes count] == 0 ? nil : purposes;
2710 - (bool) isCommercial {
2711 return [self hasTag:@"cydia::commercial"];
2714 - (CYString &) cyname {
2715 return name_.empty() ? id_ : name_;
2718 - (uint32_t) compareBySection:(NSArray *)sections {
2719 NSString *section([self section]);
2720 for (size_t i(0), e([sections count]); i != e; ++i) {
2721 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2725 return _not(uint32_t);
2728 - (uint32_t) compareForChanges {
2733 uint32_t timestamp : 30;
2734 uint32_t ignored : 1;
2735 uint32_t upgradable : 1;
2739 bool upgradable([self upgradableAndEssential:YES]);
2740 value.bits.upgradable = upgradable ? 1 : 0;
2743 value.bits.timestamp = 0;
2744 value.bits.ignored = [self ignored] ? 0 : 1;
2745 value.bits.upgradable = 1;
2747 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2748 value.bits.ignored = 0;
2749 value.bits.upgradable = 0;
2752 return _not(uint32_t) - value.key;
2756 pkgProblemResolver *resolver = [database_ resolver];
2757 resolver->Clear(iterator_);
2758 resolver->Protect(iterator_);
2762 pkgProblemResolver *resolver = [database_ resolver];
2763 resolver->Clear(iterator_);
2764 resolver->Protect(iterator_);
2765 pkgCacheFile &cache([database_ cache]);
2766 cache->MarkInstall(iterator_, false);
2767 pkgDepCache::StateCache &state((*cache)[iterator_]);
2768 if (!state.Install())
2769 cache->SetReInstall(iterator_, true);
2773 pkgProblemResolver *resolver = [database_ resolver];
2774 resolver->Clear(iterator_);
2775 resolver->Protect(iterator_);
2776 resolver->Remove(iterator_);
2777 [database_ cache]->MarkDelete(iterator_, true);
2780 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2781 _profile(Package$isUnfilteredAndSearchedForBy)
2784 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2785 value &= [self unfiltered];
2788 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2789 value &= [self matches:search];
2796 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2797 if ([search length] == 0)
2800 _profile(Package$isUnfilteredAndSelectedForBy)
2803 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2804 value &= [self unfiltered];
2807 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2808 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2815 - (bool) isInstalledAndVisible:(NSNumber *)number {
2816 return (![number boolValue] || [self visible]) && ![self uninstalled];
2819 - (bool) isVisibleInSection:(NSString *)name {
2820 NSString *section = [self section];
2825 section == nil && [name length] == 0 ||
2826 [name isEqualToString:section]
2830 - (bool) isVisibleInSource:(Source *)source {
2831 return [self source] == source && [self visible];
2836 /* Section Class {{{ */
2837 @interface Section : NSObject {
2842 NSString *localized_;
2845 - (NSComparisonResult) compareByLocalized:(Section *)section;
2846 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2847 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2848 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2849 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2850 - (NSString *) name;
2857 - (void) addToCount;
2859 - (void) setCount:(size_t)count;
2860 - (NSString *) localized;
2864 @implementation Section
2868 if (localized_ != nil)
2869 [localized_ release];
2873 - (NSComparisonResult) compareByLocalized:(Section *)section {
2874 NSString *lhs(localized_);
2875 NSString *rhs([section localized]);
2877 /*if ([lhs length] != 0 && [rhs length] != 0) {
2878 unichar lhc = [lhs characterAtIndex:0];
2879 unichar rhc = [rhs characterAtIndex:0];
2881 if (isalpha(lhc) && !isalpha(rhc))
2882 return NSOrderedAscending;
2883 else if (!isalpha(lhc) && isalpha(rhc))
2884 return NSOrderedDescending;
2887 return [lhs compare:rhs options:LaxCompareOptions_];
2890 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2891 if ((self = [self initWithName:name localize:NO]) != nil) {
2892 if (localized != nil)
2893 localized_ = [localized retain];
2897 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2898 return [self initWithName:name row:0 localize:localize];
2901 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2902 if ((self = [super init]) != nil) {
2903 name_ = [name retain];
2907 localized_ = [LocalizeSection(name_) retain];
2911 /* XXX: localize the index thingees */
2912 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2913 if ((self = [super init]) != nil) {
2914 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2920 - (NSString *) name {
2940 - (void) addToCount {
2944 - (void) setCount:(size_t)count {
2948 - (NSString *) localized {
2955 static NSString *Colon_;
2956 static NSString *Error_;
2957 static NSString *Warning_;
2959 /* Database Implementation {{{ */
2960 @implementation Database
2962 + (Database *) sharedInstance {
2963 static Database *instance;
2964 if (instance == nil)
2965 instance = [[Database alloc] init];
2975 NSRecycleZone(zone_);
2976 // XXX: malloc_destroy_zone(zone_);
2977 apr_pool_destroy(pool_);
2981 - (void) _readCydia:(NSNumber *)fd { _pooled
2982 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2983 std::istream is(&ib);
2986 static Pcre finish_r("^finish:([^:]*)$");
2988 while (std::getline(is, line)) {
2989 const char *data(line.c_str());
2990 size_t size = line.size();
2991 lprintf("C:%s\n", data);
2993 if (finish_r(data, size)) {
2994 NSString *finish = finish_r[1];
2995 int index = [Finishes_ indexOfObject:finish];
2996 if (index != INT_MAX && index > Finish_)
3004 - (void) _readStatus:(NSNumber *)fd { _pooled
3005 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3006 std::istream is(&ib);
3009 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3010 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3012 while (std::getline(is, line)) {
3013 const char *data(line.c_str());
3014 size_t size(line.size());
3015 lprintf("S:%s\n", data);
3017 if (conffile_r(data, size)) {
3018 [delegate_ setConfigurationData:conffile_r[1]];
3019 } else if (strncmp(data, "status: ", 8) == 0) {
3020 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3021 [delegate_ setProgressTitle:string];
3022 } else if (pmstatus_r(data, size)) {
3023 std::string type([pmstatus_r[1] UTF8String]);
3024 NSString *id = pmstatus_r[2];
3026 float percent([pmstatus_r[3] floatValue]);
3027 [delegate_ setProgressPercent:(percent / 100)];
3029 NSString *string = pmstatus_r[4];
3031 if (type == "pmerror")
3032 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3033 withObject:[NSArray arrayWithObjects:string, id, nil]
3036 else if (type == "pmstatus") {
3037 [delegate_ setProgressTitle:string];
3038 } else if (type == "pmconffile")
3039 [delegate_ setConfigurationData:string];
3041 lprintf("E:unknown pmstatus\n");
3043 lprintf("E:unknown status\n");
3049 - (void) _readOutput:(NSNumber *)fd { _pooled
3050 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3051 std::istream is(&ib);
3054 while (std::getline(is, line)) {
3055 lprintf("O:%s\n", line.c_str());
3056 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3066 - (Package *) packageWithName:(NSString *)name {
3067 @synchronized ([Database class]) {
3068 if (static_cast<pkgDepCache *>(cache_) == NULL)
3070 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3071 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3074 - (Database *) init {
3075 if ((self = [super init]) != nil) {
3082 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3083 apr_pool_create(&pool_, NULL);
3085 packages_ = [[NSMutableArray alloc] init];
3089 _assert(pipe(fds) != -1);
3092 _config->Set("APT::Keep-Fds::", cydiafd_);
3093 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3096 detachNewThreadSelector:@selector(_readCydia:)
3098 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3101 _assert(pipe(fds) != -1);
3105 detachNewThreadSelector:@selector(_readStatus:)
3107 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3110 _assert(pipe(fds) != -1);
3111 _assert(dup2(fds[0], 0) != -1);
3112 _assert(close(fds[0]) != -1);
3114 input_ = fdopen(fds[1], "a");
3116 _assert(pipe(fds) != -1);
3117 _assert(dup2(fds[1], 1) != -1);
3118 _assert(close(fds[1]) != -1);
3121 detachNewThreadSelector:@selector(_readOutput:)
3123 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3128 - (pkgCacheFile &) cache {
3132 - (pkgDepCache::Policy *) policy {
3136 - (pkgRecords *) records {
3140 - (pkgProblemResolver *) resolver {
3144 - (pkgAcquire &) fetcher {
3148 - (pkgSourceList &) list {
3152 - (NSArray *) packages {
3156 - (NSArray *) sources {
3157 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3158 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3159 [sources addObject:i->second];
3163 - (NSArray *) issues {
3164 if (cache_->BrokenCount() == 0)
3167 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3169 for (Package *package in packages_) {
3170 if (![package broken])
3172 pkgCache::PkgIterator pkg([package iterator]);
3174 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3175 [entry addObject:[package name]];
3176 [issues addObject:entry];
3178 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3182 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3183 pkgCache::DepIterator start;
3184 pkgCache::DepIterator end;
3185 dep.GlobOr(start, end); // ++dep
3187 if (!cache_->IsImportantDep(end))
3189 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3192 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3193 [entry addObject:failure];
3194 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3196 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3197 if (Package *package = [self packageWithName:name])
3198 name = [package name];
3199 [failure addObject:name];
3201 pkgCache::PkgIterator target(start.TargetPkg());
3202 if (target->ProvidesList != 0)
3203 [failure addObject:@"?"];
3205 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3207 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3208 else if (!cache_[target].CandidateVerIter(cache_).end())
3209 [failure addObject:@"-"];
3210 else if (target->ProvidesList == 0)
3211 [failure addObject:@"!"];
3213 [failure addObject:@"%"];
3217 if (start.TargetVer() != 0)
3218 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3229 - (bool) popErrorWithTitle:(NSString *)title {
3231 std::string message;
3233 while (!_error->empty()) {
3235 bool warning(!_error->PopMessage(error));
3239 size_t size(error.size());
3240 if (size == 0 || error[size - 1] != '\n')
3242 error.resize(size - 1);
3244 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3246 if (!message.empty())
3251 if (fatal && !message.empty())
3252 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3257 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3258 return [self popErrorWithTitle:title] || !success;
3261 - (void) reloadData { _pooled
3262 @synchronized ([Database class]) {
3263 @synchronized (self) {
3267 [packages_ removeAllObjects];
3293 apr_pool_clear(pool_);
3294 NSRecycleZone(zone_);
3296 int chk(creat("/tmp/cydia.chk", 0644));
3300 NSString *title(UCLocalize("DATABASE"));
3303 if (!cache_.Open(progress_, true)) { pop:
3305 bool warning(!_error->PopMessage(error));
3306 lprintf("cache_.Open():[%s]\n", error.c_str());
3308 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3309 [delegate_ repairWithSelector:@selector(configure)];
3310 else if (error == "The package lists or status file could not be parsed or opened.")
3311 [delegate_ repairWithSelector:@selector(update)];
3312 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3313 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3314 // else if (error == "The list of sources could not be read.")
3316 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3325 unlink("/tmp/cydia.chk");
3327 now_ = [[NSDate date] retain];
3329 policy_ = new pkgDepCache::Policy();
3330 records_ = new pkgRecords(cache_);
3331 resolver_ = new pkgProblemResolver(cache_);
3332 fetcher_ = new pkgAcquire(&status_);
3335 list_ = new pkgSourceList();
3336 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3339 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3340 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3344 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3347 if (cache_->BrokenCount() != 0) {
3348 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3351 if (cache_->BrokenCount() != 0) {
3352 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3356 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3362 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3363 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3364 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3365 // XXX: this could be more intelligent
3366 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3367 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3369 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3376 /*std::vector<Package *> packages;
3377 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3378 [packages_ release];
3383 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3384 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3385 //packages.push_back(package);
3386 [packages_ addObject:package];
3390 /*if (packages.empty())
3391 packages_ = [[NSArray alloc] init];
3393 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3396 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3397 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3398 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3406 /*if (!packages.empty())
3407 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3408 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3410 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3412 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3414 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3420 - (void) configure {
3421 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3422 system([dpkg UTF8String]);
3426 // XXX: I don't remember this condition
3431 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3433 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3435 if ([self popErrorWithTitle:title])
3439 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3442 public pkgArchiveCleaner
3445 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3450 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3457 fetcher_->Shutdown();
3459 pkgRecords records(cache_);
3461 lock_ = new FileFd();
3462 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3464 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3466 if ([self popErrorWithTitle:title])
3470 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3473 manager_ = (_system->CreatePM(cache_));
3474 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3481 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3483 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3485 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3487 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3488 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3491 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3496 bool failed = false;
3497 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3498 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3500 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3503 std::string uri = (*item)->DescURI();
3504 std::string error = (*item)->ErrorText;
3506 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3509 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3510 withObject:[NSArray arrayWithObjects:
3511 [NSString stringWithUTF8String:error.c_str()],
3523 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3525 if (_error->PendingError()) {
3530 if (result == pkgPackageManager::Failed) {
3535 if (result != pkgPackageManager::Completed) {
3540 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3542 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3544 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3545 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3548 if (![before isEqualToArray:after])
3553 NSString *title(UCLocalize("UPGRADE"));
3554 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3560 [self updateWithStatus:status_];
3563 - (void) setVisible {
3564 for (Package *package in packages_)
3565 [package setVisible];
3568 - (void) updateWithStatus:(Status &)status {
3569 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3570 NSString *title(UCLocalize("REFRESHING_DATA"));
3573 if (!list.ReadMainList())
3574 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3577 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3578 if ([self popErrorWithTitle:title])
3581 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3582 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */;
3584 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3588 - (void) setDelegate:(id)delegate {
3589 delegate_ = delegate;
3590 status_.setDelegate(delegate);
3591 progress_.setDelegate(delegate);
3594 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3595 SourceMap::const_iterator i(sources_.find(file->ID));
3596 return i == sources_.end() ? nil : i->second;
3602 /* Confirmation Controller {{{ */
3603 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3604 if (!iterator.end())
3605 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3606 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3608 pkgCache::PkgIterator package(dep.TargetPkg());
3611 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3619 /* Web Scripting {{{ */
3620 @interface CydiaObject : NSObject {
3625 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3628 @implementation CydiaObject
3631 [indirect_ release];
3635 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3636 if ((self = [super init]) != nil) {
3637 indirect_ = [indirect retain];
3641 - (void) setDelegate:(id)delegate {
3642 delegate_ = delegate;
3645 + (NSArray *) _attributeKeys {
3646 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3649 - (NSArray *) attributeKeys {
3650 return [[self class] _attributeKeys];
3653 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3654 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3657 - (NSString *) device {
3658 return [[UIDevice currentDevice] uniqueIdentifier];
3661 #if 0 // XXX: implement!
3662 - (NSString *) mac {
3663 if (![indirect_ promptForSensitive:@"Mac Address"])
3667 - (NSString *) serial {
3668 if (![indirect_ promptForSensitive:@"Serial #"])
3672 - (NSString *) firewire {
3673 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3677 - (NSString *) imei {
3678 if (![indirect_ promptForSensitive:@"IMEI"])
3683 + (NSString *) webScriptNameForSelector:(SEL)selector {
3684 if (selector == @selector(close))
3686 else if (selector == @selector(getInstalledPackages))
3687 return @"getInstalledPackages";
3688 else if (selector == @selector(getPackageById:))
3689 return @"getPackageById";
3690 else if (selector == @selector(installPackages:))
3691 return @"installPackages";
3692 else if (selector == @selector(setAutoPopup:))
3693 return @"setAutoPopup";
3694 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3695 return @"setButtonImage";
3696 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3697 return @"setButtonTitle";
3698 else if (selector == @selector(setFinishHook:))
3699 return @"setFinishHook";
3700 else if (selector == @selector(setPopupHook:))
3701 return @"setPopupHook";
3702 else if (selector == @selector(setSpecial:))
3703 return @"setSpecial";
3704 else if (selector == @selector(setToken:))
3706 else if (selector == @selector(setViewportWidth:))
3707 return @"setViewportWidth";
3708 else if (selector == @selector(supports:))
3710 else if (selector == @selector(stringWithFormat:arguments:))
3712 else if (selector == @selector(localizedStringForKey:value:table:))
3714 else if (selector == @selector(du:))
3716 else if (selector == @selector(statfs:))
3722 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3723 return [self webScriptNameForSelector:selector] == nil;
3726 - (BOOL) supports:(NSString *)feature {
3727 return [feature isEqualToString:@"window.open"];
3730 - (NSArray *) getInstalledPackages {
3731 NSArray *packages([[Database sharedInstance] packages]);
3732 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3733 for (Package *package in packages)
3734 if ([package installed] != nil)
3735 [installed addObject:package];
3739 - (Package *) getPackageById:(NSString *)id {
3740 Package *package([[Database sharedInstance] packageWithName:id]);
3745 - (NSArray *) statfs:(NSString *)path {
3748 if (path == nil || statfs([path UTF8String], &stat) == -1)
3751 return [NSArray arrayWithObjects:
3752 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3753 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3754 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3758 - (NSNumber *) du:(NSString *)path {
3759 NSNumber *value(nil);
3762 _assert(pipe(fds) != -1);
3764 pid_t pid(ExecFork());
3766 _assert(dup2(fds[1], 1) != -1);
3767 _assert(close(fds[0]) != -1);
3768 _assert(close(fds[1]) != -1);
3769 /* XXX: this should probably not use du */
3770 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3775 _assert(close(fds[1]) != -1);
3777 if (FILE *du = fdopen(fds[0], "r")) {
3779 while (fgets(line, sizeof(line), du) != NULL) {
3780 size_t length(strlen(line));
3781 while (length != 0 && line[length - 1] == '\n')
3782 line[--length] = '\0';
3783 if (char *tab = strchr(line, '\t')) {
3785 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3790 } else _assert(close(fds[0]));
3794 if (waitpid(pid, &status, 0) == -1)
3797 else _assert(false);
3806 - (void) installPackages:(NSArray *)packages {
3807 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3810 - (void) setAutoPopup:(BOOL)popup {
3811 [indirect_ setAutoPopup:popup];
3814 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3815 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3818 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3819 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3822 - (void) setSpecial:(id)function {
3823 [indirect_ setSpecial:function];
3826 - (void) setToken:(NSString *)token {
3829 Token_ = [token retain];
3831 [Metadata_ setObject:Token_ forKey:@"Token"];
3835 - (void) setFinishHook:(id)function {
3836 [indirect_ setFinishHook:function];
3839 - (void) setPopupHook:(id)function {
3840 [indirect_ setPopupHook:function];
3843 - (void) setViewportWidth:(float)width {
3844 [indirect_ setViewportWidth:width];
3847 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3848 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3849 unsigned count([arguments count]);
3851 for (unsigned i(0); i != count; ++i)
3852 values[i] = [arguments objectAtIndex:i];
3853 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3856 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3857 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3859 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3861 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3867 /* Cydia View Controller {{{ */
3868 @interface CYViewController : UCViewController { }
3871 @implementation CYViewController
3875 @interface CYBrowserController : BrowserController {
3876 CydiaObject *cydia_;
3881 @implementation CYBrowserController
3888 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3891 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3892 [super webView:sender didClearWindowObject:window forFrame:frame];
3894 WebDataSource *source([frame dataSource]);
3895 NSURLResponse *response([source response]);
3896 NSURL *url([response URL]);
3897 NSString *scheme([url scheme]);
3899 NSHTTPURLResponse *http;
3900 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3901 http = (NSHTTPURLResponse *) response;
3905 NSDictionary *headers([http allHeaderFields]);
3906 NSString *host([url host]);
3907 [self setHeaders:headers forHost:host];
3910 [host isEqualToString:@"cydia.saurik.com"] ||
3911 [host hasSuffix:@".cydia.saurik.com"] ||
3912 [scheme isEqualToString:@"file"]
3914 [window setValue:cydia_ forKey:@"cydia"];
3917 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3918 if (System_ != NULL)
3919 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3920 if (Machine_ != NULL)
3921 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3923 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3925 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3928 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3929 NSMutableURLRequest *copy = [request mutableCopy];
3930 [self _setMoreHeaders:copy];
3934 - (void) setDelegate:(id)delegate {
3935 [super setDelegate:delegate];
3936 [cydia_ setDelegate:delegate];
3940 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3941 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3943 WebView *webview([document_ webView]);
3945 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3947 NSString *application = package == nil ? @"Cydia" : [NSString
3948 stringWithFormat:@"Cydia/%@",
3953 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3955 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3956 if (Product_ != nil)
3957 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3959 [webview setApplicationNameForUserAgent:application];
3965 @protocol ConfirmationControllerDelegate
3966 - (void) cancelAndClear:(bool)clear;
3967 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3971 @interface ConfirmationController : CYBrowserController {
3972 _transient Database *database_;
3973 UIAlertView *essential_;
3980 - (id) initWithDatabase:(Database *)database;
3984 @implementation ConfirmationController
3991 if (essential_ != nil)
3992 [essential_ release];
3996 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3997 NSString *context([alert context]);
3999 if ([context isEqualToString:@"remove"]) {
4000 if (button == [alert cancelButtonIndex]) {
4001 [self dismissModalViewControllerAnimated:YES];
4002 } else if (button == [alert firstOtherButtonIndex]) {
4005 [delegate_ confirmWithNavigationController:[self navigationController]];
4008 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4009 } else if ([context isEqualToString:@"unable"]) {
4010 [self dismissModalViewControllerAnimated:YES];
4011 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4013 [super alertView:alert clickedButtonAtIndex:button];
4017 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4018 [self dismissModalViewControllerAnimated:YES];
4019 [delegate_ cancelAndClear:NO];
4024 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4025 [super webView:sender didClearWindowObject:window forFrame:frame];
4026 [window setValue:changes_ forKey:@"changes"];
4027 [window setValue:issues_ forKey:@"issues"];
4028 [window setValue:sizes_ forKey:@"sizes"];
4029 [window setValue:self forKey:@"queue"];
4032 - (id) initWithDatabase:(Database *)database {
4033 if ((self = [super init]) != nil) {
4034 database_ = database;
4036 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4038 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4039 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4040 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4041 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4042 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4046 pkgDepCache::Policy *policy([database_ policy]);
4048 pkgCacheFile &cache([database_ cache]);
4049 NSArray *packages = [database_ packages];
4050 for (Package *package in packages) {
4051 pkgCache::PkgIterator iterator = [package iterator];
4052 pkgDepCache::StateCache &state(cache[iterator]);
4054 NSString *name([package name]);
4056 if (state.NewInstall())
4057 [installing addObject:name];
4058 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4059 [reinstalling addObject:name];
4060 else if (state.Upgrade())
4061 [upgrading addObject:name];
4062 else if (state.Downgrade())
4063 [downgrading addObject:name];
4064 else if (state.Delete()) {
4065 if ([package essential])
4067 [removing addObject:name];
4070 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4071 substrate_ |= DepSubstrate(iterator.CurrentVer());
4076 else if (Advanced_) {
4077 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4079 essential_ = [[UIAlertView alloc]
4080 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4081 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4083 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4084 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4087 [essential_ setContext:@"remove"];
4089 essential_ = [[UIAlertView alloc]
4090 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4091 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4093 cancelButtonTitle:UCLocalize("OKAY")
4094 otherButtonTitles:nil
4097 [essential_ setContext:@"unable"];
4100 changes_ = [[NSArray alloc] initWithObjects:
4108 issues_ = [database_ issues];
4110 issues_ = [issues_ retain];
4112 sizes_ = [[NSArray alloc] initWithObjects:
4113 SizeString([database_ fetcher].FetchNeeded()),
4114 SizeString([database_ fetcher].PartialPresent()),
4117 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4119 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
4120 initWithTitle:UCLocalize("CANCEL")
4121 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4122 style:UIBarButtonItemStylePlain
4124 action:@selector(cancelButtonClicked)
4126 [[self navigationItem] setLeftBarButtonItem:leftItem];
4131 - (void) applyRightButton {
4132 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
4133 initWithTitle:UCLocalize("CONFIRM")
4134 style:UIBarButtonItemStylePlain
4136 action:@selector(confirmButtonClicked)
4138 #if !AlwaysReload && !IgnoreInstall
4139 if (issues_ == nil && ![self isLoading]) [[self navigationItem] setRightBarButtonItem:rightItem];
4140 else [super applyRightButton];
4142 [[self navigationItem] setRightBarButtonItem:nil];
4144 [rightItem release];
4147 - (void) cancelButtonClicked {
4148 [self dismissModalViewControllerAnimated:YES];
4149 [delegate_ cancelAndClear:YES];
4153 - (void) confirmButtonClicked {
4157 if (essential_ != nil)
4162 [delegate_ confirmWithNavigationController:[self navigationController]];
4170 /* Progress Data {{{ */
4171 @interface ProgressData : NSObject {
4177 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4184 @implementation ProgressData
4186 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4187 if ((self = [super init]) != nil) {
4188 selector_ = selector;
4208 /* Progress Controller {{{ */
4209 @interface ProgressController : CYViewController <
4210 ConfigurationDelegate,
4213 _transient Database *database_;
4214 UIProgressBar *progress_;
4215 UITextView *output_;
4216 UITextLabel *status_;
4217 UIPushButton *close_;
4219 SHA1SumValue springlist_;
4220 SHA1SumValue notifyconf_;
4224 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4226 - (void) _retachThread;
4227 - (void) _detachNewThreadData:(ProgressData *)data;
4228 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4234 @protocol ProgressControllerDelegate
4235 - (void) progressControllerIsComplete:(ProgressController *)sender;
4238 @implementation ProgressController
4241 [database_ setDelegate:nil];
4242 [progress_ release];
4251 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4252 if ((self = [super init]) != nil) {
4253 database_ = database;
4254 [database_ setDelegate:self];
4255 delegate_ = delegate;
4257 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4259 progress_ = [[UIProgressBar alloc] init];
4260 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4261 [progress_ setStyle:0];
4263 status_ = [[UITextLabel alloc] init];
4264 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4265 [status_ setColor:[UIColor whiteColor]];
4266 [status_ setBackgroundColor:[UIColor clearColor]];
4267 [status_ setCentersHorizontally:YES];
4268 //[status_ setFont:font];
4270 output_ = [[UITextView alloc] init];
4272 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4273 //[output_ setTextFont:@"Courier New"];
4274 [output_ setFont:[[output_ font] fontWithSize:12]];
4275 [output_ setTextColor:[UIColor whiteColor]];
4276 [output_ setBackgroundColor:[UIColor clearColor]];
4277 [output_ setMarginTop:0];
4278 [output_ setAllowsRubberBanding:YES];
4279 [output_ setEditable:NO];
4280 [[self view] addSubview:output_];
4282 close_ = [[UIPushButton alloc] init];
4283 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4284 [close_ setAutosizesToFit:NO];
4285 [close_ setDrawsShadow:YES];
4286 [close_ setStretchBackground:YES];
4287 [close_ setEnabled:YES];
4288 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4289 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4290 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4291 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4295 - (void) positionViews {
4296 CGRect bounds = [[self view] bounds];
4297 CGSize prgsize = [UIProgressBar defaultSize];
4300 (bounds.size.width - prgsize.width) / 2,
4301 bounds.size.height - prgsize.height - 64
4304 float closewidth = bounds.size.width - 20;
4305 if (closewidth > 300) closewidth = 300;
4307 [progress_ setFrame:prgrect];
4308 [status_ setFrame:CGRectMake(
4310 bounds.size.height - prgsize.height - 94,
4311 bounds.size.width - 20,
4314 [output_ setFrame:CGRectMake(
4317 bounds.size.width - 20,
4318 bounds.size.height - 106
4320 [close_ setFrame:CGRectMake(
4321 (bounds.size.width - closewidth) / 2,
4322 bounds.size.height - prgsize.height - 94,
4328 - (void) viewWillAppear:(BOOL)animated {
4329 [super viewDidAppear:animated];
4330 [[self navigationItem] setHidesBackButton:YES];
4331 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4333 [self positionViews];
4336 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4337 [self positionViews];
4340 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4341 NSString *context([alert context]);
4343 if ([context isEqualToString:@"conffile"]) {
4344 FILE *input = [database_ input];
4345 if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
4346 else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
4351 - (void) closeButtonPushed {
4354 UpdateExternalStatus(0);
4358 [self dismissModalViewControllerAnimated:YES];
4362 [delegate_ terminateWithSuccess];
4363 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4364 [delegate_ suspendWithAnimation:YES];
4366 [delegate_ suspend];*/
4370 system("launchctl stop com.apple.SpringBoard");
4374 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4383 - (void) _retachThread {
4384 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4386 [[self view] addSubview:close_];
4387 [progress_ removeFromSuperview];
4388 [status_ removeFromSuperview];
4390 [database_ popErrorWithTitle:title_];
4391 [delegate_ progressControllerIsComplete:self];
4395 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4398 MMap mmap(file, MMap::ReadOnly);
4400 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4401 if (!(notifyconf_ == sha1.Result()))
4408 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4411 MMap mmap(file, MMap::ReadOnly);
4413 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4414 if (!(springlist_ == sha1.Result()))
4420 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4421 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4422 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4423 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4424 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4427 system("su -c /usr/bin/uicache mobile");
4429 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4431 [delegate_ setStatusBarShowsProgress:NO];
4434 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4435 [[data target] performSelector:[data selector] withObject:[data object]];
4438 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4441 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4442 UpdateExternalStatus(1);
4449 title_ = [title retain];
4451 [[self navigationItem] setTitle:title_];
4453 [status_ setText:nil];
4454 [output_ setText:@""];
4455 [progress_ setProgress:0];
4457 [close_ removeFromSuperview];
4458 [[self view] addSubview:progress_];
4459 [[self view] addSubview:status_];
4461 [delegate_ setStatusBarShowsProgress:YES];
4466 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4469 MMap mmap(file, MMap::ReadOnly);
4471 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4472 notifyconf_ = sha1.Result();
4478 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4481 MMap mmap(file, MMap::ReadOnly);
4483 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4484 springlist_ = sha1.Result();
4489 detachNewThreadSelector:@selector(_detachNewThreadData:)
4491 withObject:[[ProgressData alloc]
4492 initWithSelector:selector
4499 - (void) repairWithSelector:(SEL)selector {
4501 detachNewThreadSelector:selector
4504 title:UCLocalize("REPAIRING")
4508 - (void) setConfigurationData:(NSString *)data {
4510 performSelectorOnMainThread:@selector(_setConfigurationData:)
4516 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4517 CYActionSheet *sheet([[[CYActionSheet alloc]
4519 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4520 defaultButtonIndex:0
4523 [sheet setMessage:error];
4524 [sheet yieldToPopupAlertAnimated:YES];
4528 - (void) setProgressTitle:(NSString *)title {
4530 performSelectorOnMainThread:@selector(_setProgressTitle:)
4536 - (void) setProgressPercent:(float)percent {
4538 performSelectorOnMainThread:@selector(_setProgressPercent:)
4539 withObject:[NSNumber numberWithFloat:percent]
4544 - (void) startProgress {
4547 - (void) addProgressOutput:(NSString *)output {
4549 performSelectorOnMainThread:@selector(_addProgressOutput:)
4555 - (bool) isCancelling:(size_t)received {
4559 - (void) _setConfigurationData:(NSString *)data {
4560 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4562 if (!conffile_r(data)) {
4563 lprintf("E:invalid conffile\n");
4567 NSString *ofile = conffile_r[1];
4568 //NSString *nfile = conffile_r[2];
4570 UIAlertView *alert = [[[UIAlertView alloc]
4571 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4572 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4574 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4575 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4576 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4580 [alert setContext:@"conffile"];
4584 - (void) _setProgressTitle:(NSString *)title {
4585 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4586 for (size_t i(0), e([words count]); i != e; ++i) {
4587 NSString *word([words objectAtIndex:i]);
4588 if (Package *package = [database_ packageWithName:word])
4589 [words replaceObjectAtIndex:i withObject:[package name]];
4592 [status_ setText:[words componentsJoinedByString:@" "]];
4595 - (void) _setProgressPercent:(NSNumber *)percent {
4596 [progress_ setProgress:[percent floatValue]];
4599 - (void) _addProgressOutput:(NSString *)output {
4600 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4601 CGSize size = [output_ contentSize];
4602 CGRect rect = {{0, size.height}, {size.width, 0}};
4603 [output_ scrollRectToVisible:rect animated:YES];
4606 - (BOOL) isRunning {
4613 /* Cell Content View {{{ */
4614 @protocol ContentDelegate
4615 - (void) drawContentRect:(CGRect)rect;
4618 @interface ContentView : UIView {
4619 _transient id<ContentDelegate> delegate_;
4624 @implementation ContentView
4625 - (id) initWithFrame:(CGRect)frame {
4626 if ((self = [super initWithFrame:frame]) != nil) {
4627 /* Fix landscape stretching. */
4628 [self setNeedsDisplayOnBoundsChange:YES];
4632 - (void) setDelegate:(id<ContentDelegate>)delegate {
4633 delegate_ = delegate;
4636 - (void) drawRect:(CGRect)rect {
4637 [super drawRect:rect];
4638 [delegate_ drawContentRect:rect];
4642 /* Package Cell {{{ */
4643 @interface PackageCell : UITableViewCell <
4648 NSString *description_;
4654 ContentView *content_;
4660 - (PackageCell *) init;
4661 - (void) setPackage:(Package *)package;
4663 + (int) heightForPackage:(Package *)package;
4664 - (void) drawContentRect:(CGRect)rect;
4668 @implementation PackageCell
4670 - (void) clearPackage {
4681 if (description_ != nil) {
4682 [description_ release];
4686 if (source_ != nil) {
4691 if (badge_ != nil) {
4696 if (placard_ != nil) {
4706 [self clearPackage];
4713 return faded_ ? [self selectionPercent] : fade_;
4716 - (PackageCell *) init {
4717 CGRect frame(CGRectMake(0, 0, 320, 74));
4718 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4719 UIView *content([self contentView]);
4720 CGRect bounds([content bounds]);
4722 content_ = [[ContentView alloc] initWithFrame:bounds];
4723 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4724 [content addSubview:content_];
4726 [content_ setDelegate:self];
4727 [content_ setOpaque:YES];
4728 if ([self respondsToSelector:@selector(selectionPercent)])
4733 - (void) _setBackgroundColor {
4735 if (NSString *mode = [package_ mode]) {
4736 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4737 color = remove ? RemovingColor_ : InstallingColor_;
4739 color = [UIColor whiteColor];
4741 [content_ setBackgroundColor:color];
4742 [self setNeedsDisplay];
4745 - (void) setPackage:(Package *)package {
4746 [self clearPackage];
4749 Source *source = [package source];
4751 icon_ = [[package icon] retain];
4752 name_ = [[package name] retain];
4755 description_ = [package longDescription];
4756 if (description_ == nil)
4757 description_ = [package shortDescription];
4758 if (description_ != nil)
4759 description_ = [description_ retain];
4761 commercial_ = [package isCommercial];
4763 package_ = [package retain];
4765 NSString *label = nil;
4766 bool trusted = false;
4768 if (source != nil) {
4769 label = [source label];
4770 trusted = [source trusted];
4771 } else if ([[package id] isEqualToString:@"firmware"])
4772 label = UCLocalize("APPLE");
4774 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4776 NSString *from(label);
4778 NSString *section = [package simpleSection];
4779 if (section != nil && ![section isEqualToString:label]) {
4780 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4781 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4784 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4785 source_ = [from retain];
4787 if (NSString *purpose = [package primaryPurpose])
4788 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4789 badge_ = [badge_ retain];
4791 if ([package installed] != nil)
4792 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4793 placard_ = [placard_ retain];
4795 [self _setBackgroundColor];
4796 [content_ setNeedsDisplay];
4799 - (void) drawContentRect:(CGRect)rect {
4800 bool selected([self isSelected]);
4801 float width([self bounds].size.width);
4804 CGContextRef context(UIGraphicsGetCurrentContext());
4805 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4806 CGContextFillRect(context, rect);
4811 rect.size = [icon_ size];
4813 rect.size.width /= 2;
4814 rect.size.height /= 2;
4816 rect.origin.x = 25 - rect.size.width / 2;
4817 rect.origin.y = 25 - rect.size.height / 2;
4819 [icon_ drawInRect:rect];
4822 if (badge_ != nil) {
4823 CGSize size = [badge_ size];
4825 [badge_ drawAtPoint:CGPointMake(
4826 36 - size.width / 2,
4827 36 - size.height / 2
4835 UISetColor(commercial_ ? Purple_ : Black_);
4836 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4837 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4840 UISetColor(commercial_ ? Purplish_ : Gray_);
4841 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4843 if (placard_ != nil)
4844 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4847 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4848 //[self _setBackgroundColor];
4849 [super setSelected:selected animated:fade];
4850 [content_ setNeedsDisplay];
4853 + (int) heightForPackage:(Package *)package {
4859 /* Section Cell {{{ */
4860 @interface SectionCell : UITableViewCell <
4868 ContentView *content_;
4873 - (void) setSection:(Section *)section editing:(BOOL)editing;
4877 @implementation SectionCell
4879 - (void) clearSection {
4880 if (basic_ != nil) {
4885 if (section_ != nil) {
4895 if (count_ != nil) {
4902 [self clearSection];
4910 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4911 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4912 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4913 switch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4914 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4916 UIView *content([self contentView]);
4917 CGRect bounds([content bounds]);
4919 content_ = [[ContentView alloc] initWithFrame:bounds];
4920 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4921 [content addSubview:content_];
4922 [content_ setBackgroundColor:[UIColor whiteColor]];
4924 [content_ setDelegate:self];
4928 - (void) onSwitch:(id)sender {
4929 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4930 if (metadata == nil) {
4931 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4932 [Sections_ setObject:metadata forKey:basic_];
4936 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4939 - (void) setSection:(Section *)section editing:(BOOL)editing {
4940 if (editing != editing_) {
4942 [switch_ removeFromSuperview];
4944 [self addSubview:switch_];
4948 [self clearSection];
4950 if (section == nil) {
4951 name_ = [UCLocalize("ALL_PACKAGES") retain];
4954 basic_ = [section name];
4956 basic_ = [basic_ retain];
4958 section_ = [section localized];
4959 if (section_ != nil)
4960 section_ = [section_ retain];
4962 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4963 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4966 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4969 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4970 [content_ setNeedsDisplay];
4973 - (void) setFrame:(CGRect)frame {
4974 [super setFrame:frame];
4976 CGRect rect([switch_ frame]);
4977 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4980 - (void) drawContentRect:(CGRect)rect {
4981 BOOL selected = [self isSelected];
4983 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4991 float width(rect.size.width);
4995 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4997 CGSize size = [count_ sizeWithFont:Font14_];
5001 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5007 /* File Table {{{ */
5008 @interface FileTable : CYViewController <
5009 UITableViewDataSource,
5012 _transient Database *database_;
5015 NSMutableArray *files_;
5019 - (id) initWithDatabase:(Database *)database;
5020 - (void) setPackage:(Package *)package;
5024 @implementation FileTable
5027 if (package_ != nil)
5036 - (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
5037 return files_ == nil ? 0 : [files_ count];
5040 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5044 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5045 static NSString *reuseIdentifier = @"Cell";
5047 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5049 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5050 [cell setFont:[UIFont systemFontOfSize:16]];
5052 [cell setText:[files_ objectAtIndex:indexPath.row]];
5053 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5058 - (id) initWithDatabase:(Database *)database {
5059 if ((self = [super init]) != nil) {
5060 database_ = database;
5062 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5064 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5066 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5067 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5068 [list_ setRowHeight:24.0f];
5069 [[self view] addSubview:list_];
5071 [list_ setDataSource:self];
5072 [list_ setDelegate:self];
5076 - (void) setPackage:(Package *)package {
5077 if (package_ != nil) {
5078 [package_ autorelease];
5087 [files_ removeAllObjects];
5089 if (package != nil) {
5090 package_ = [package retain];
5091 name_ = [[package id] retain];
5093 if (NSArray *files = [package files])
5094 [files_ addObjectsFromArray:files];
5096 if ([files_ count] != 0) {
5097 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5098 [files_ removeObjectAtIndex:0];
5099 [files_ sortUsingSelector:@selector(compareByPath:)];
5101 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5102 [stack addObject:@"/"];
5104 for (int i(0), e([files_ count]); i != e; ++i) {
5105 NSString *file = [files_ objectAtIndex:i];
5106 while (![file hasPrefix:[stack lastObject]])
5107 [stack removeLastObject];
5108 NSString *directory = [stack lastObject];
5109 [stack addObject:[file stringByAppendingString:@"/"]];
5110 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5111 ([stack count] - 2) * 3, "",
5112 [file substringFromIndex:[directory length]]
5121 - (void) reloadData {
5122 [self setPackage:[database_ packageWithName:name_]];
5127 /* Package Controller {{{ */
5128 @interface PackageController : CYBrowserController <
5129 UIActionSheetDelegate
5131 _transient Database *database_;
5135 NSMutableArray *buttons_;
5138 - (id) initWithDatabase:(Database *)database;
5139 - (void) setPackage:(Package *)package;
5143 @implementation PackageController
5146 if (package_ != nil)
5155 if ([self retainCount] == 1)
5156 [delegate_ setPackageController:self];
5160 /* XXX: this is not safe at all... localization of /fail/ */
5161 - (void) _clickButtonWithName:(NSString *)name {
5162 if ([name isEqualToString:UCLocalize("CLEAR")])
5163 [delegate_ clearPackage:package_];
5164 else if ([name isEqualToString:UCLocalize("INSTALL")])
5165 [delegate_ installPackage:package_];
5166 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5167 [delegate_ installPackage:package_];
5168 else if ([name isEqualToString:UCLocalize("REMOVE")])
5169 [delegate_ removePackage:package_];
5170 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5171 [delegate_ installPackage:package_];
5172 else _assert(false);
5175 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5176 NSString *context([sheet context]);
5178 if ([context isEqualToString:@"modify"]) {
5179 if (button != [sheet cancelButtonIndex]) {
5180 NSString *buttonName = [buttons_ objectAtIndex:button];
5181 [self _clickButtonWithName:buttonName];
5184 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5188 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
5189 return [super webView:sender didFinishLoadForFrame:frame];
5192 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5193 [super webView:sender didClearWindowObject:window forFrame:frame];
5194 [window setValue:package_ forKey:@"package"];
5197 - (bool) _allowJavaScriptPanel {
5202 - (void) _customButtonClicked {
5203 int count([buttons_ count]);
5208 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5210 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5211 [buttons addObjectsFromArray:buttons_];
5213 UIActionSheet *sheet = [[[UIActionSheet alloc]
5216 cancelButtonTitle:nil
5217 destructiveButtonTitle:nil
5218 otherButtonTitles:nil
5221 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5223 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5224 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5226 [sheet setContext:@"modify"];
5228 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5232 - (void) customButtonClicked {
5233 // Wait until it's done loading.
5234 if (![self isLoading])
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.
5247 - (id) initWithDatabase:(Database *)database {
5248 if ((self = [super init]) != nil) {
5249 database_ = database;
5250 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5251 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5255 - (void) setPackage:(Package *)package {
5256 if (package_ != nil) {
5257 [package_ autorelease];
5266 [buttons_ removeAllObjects];
5268 if (package != nil) {
5271 package_ = [package retain];
5272 name_ = [[package id] retain];
5273 commercial_ = [package isCommercial];
5275 if ([package_ mode] != nil)
5276 [buttons_ addObject:UCLocalize("CLEAR")];
5277 if ([package_ source] == nil);
5278 else if ([package_ upgradableAndEssential:NO])
5279 [buttons_ addObject:UCLocalize("UPGRADE")];
5280 else if ([package_ uninstalled])
5281 [buttons_ addObject:UCLocalize("INSTALL")];
5283 [buttons_ addObject:UCLocalize("REINSTALL")];
5284 if (![package_ uninstalled])
5285 [buttons_ addObject:UCLocalize("REMOVE")];
5287 if (special_ != NULL) {
5288 CGRect frame([document_ frame]);
5289 frame.size.height = 0;
5290 [document_ setFrame:frame];
5292 if ([scroller_ respondsToSelector:@selector(scrollPointVisibleAtTopLeft:)])
5293 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5295 [scroller_ scrollRectToVisible:CGRectZero animated:NO];
5298 [[[document_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5300 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5302 [self setFinishHook:nil];
5303 [self setPopupHook:nil];
5306 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5307 [super callFunction:special_];
5312 - (void) applyRightButton {
5313 int count = [buttons_ count];
5314 UIBarButtonItem *actionItem = [[UIBarButtonItem alloc]
5315 initWithTitle:count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0]
5316 style:UIBarButtonItemStylePlain
5318 action:@selector(customButtonClicked)
5320 if (![self isLoading]) [[self navigationItem] setRightBarButtonItem:actionItem];
5321 else [super applyRightButton];
5322 [actionItem release];
5325 - (bool) isLoading {
5326 return commercial_ ? [super isLoading] : false;
5329 - (void) reloadData {
5330 [self setPackage:[database_ packageWithName:name_]];
5335 /* Package Table {{{ */
5336 @interface PackageTable : UIView <
5337 UITableViewDataSource,
5340 _transient Database *database_;
5341 NSMutableArray *packages_;
5342 NSMutableArray *sections_;
5344 NSMutableArray *index_;
5345 NSMutableDictionary *indices_;
5351 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5353 - (void) setDelegate:(id)delegate;
5355 - (void) reloadData;
5356 - (void) resetCursor;
5358 - (UITableView *) list;
5360 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5362 - (void) deselectWithAnimation:(BOOL)animated;
5366 @implementation PackageTable
5369 [packages_ release];
5370 [sections_ release];
5378 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5379 NSInteger count([sections_ count]);
5380 return count == 0 ? 1 : count;
5383 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5384 if ([sections_ count] == 0)
5386 return [[sections_ objectAtIndex:section] name];
5389 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5390 if ([sections_ count] == 0)
5392 return [[sections_ objectAtIndex:section] count];
5395 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5396 Section *section([sections_ objectAtIndex:[path section]]);
5397 NSInteger row([path row]);
5398 Package *package([packages_ objectAtIndex:([section row] + row)]);
5402 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5403 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5405 cell = [[[PackageCell alloc] init] autorelease];
5406 [cell setPackage:[self packageAtIndexPath:path]];
5410 - (void) deselectWithAnimation:(BOOL)animated {
5411 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5414 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5415 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5418 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5419 Package *package([self packageAtIndexPath:path]);
5420 package = [database_ packageWithName:[package id]];
5421 [target_ performSelector:action_ withObject:package];
5425 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5426 return [packages_ count] > 20 ? index_ : nil;
5429 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5433 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5434 if ((self = [super initWithFrame:frame]) != nil) {
5435 database_ = database;
5440 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5441 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5443 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5444 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5446 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5447 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5448 [list_ setRowHeight:73.0f];
5449 [self addSubview:list_];
5451 [list_ setDataSource:self];
5452 [list_ setDelegate:self];
5456 - (void) setDelegate:(id)delegate {
5457 delegate_ = delegate;
5460 - (bool) hasPackage:(Package *)package {
5464 - (void) reloadData {
5465 NSArray *packages = [database_ packages];
5467 [packages_ removeAllObjects];
5468 [sections_ removeAllObjects];
5470 _profile(PackageTable$reloadData$Filter)
5471 for (Package *package in packages)
5472 if ([self hasPackage:package])
5473 [packages_ addObject:package];
5476 [index_ removeAllObjects];
5477 [indices_ removeAllObjects];
5479 Section *section = nil;
5481 _profile(PackageTable$reloadData$Section)
5482 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5486 _profile(PackageTable$reloadData$Section$Package)
5487 package = [packages_ objectAtIndex:offset];
5488 index = [package index];
5491 if (section == nil || [section index] != index) {
5492 _profile(PackageTable$reloadData$Section$Allocate)
5493 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5496 [index_ addObject:[section name]];
5497 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5499 _profile(PackageTable$reloadData$Section$Add)
5500 [sections_ addObject:section];
5504 [section addToCount];
5508 _profile(PackageTable$reloadData$List)
5513 - (void) resetCursor {
5514 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5517 - (UITableView *) list {
5521 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5522 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5527 /* Filtered Package Table {{{ */
5528 @interface FilteredPackageTable : PackageTable {
5534 - (void) setObject:(id)object;
5535 - (void) setObject:(id)object forFilter:(SEL)filter;
5537 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5541 @implementation FilteredPackageTable
5549 - (void) setFilter:(SEL)filter {
5552 /* XXX: this is an unsafe optimization of doomy hell */
5553 Method method(class_getInstanceMethod([Package class], filter));
5554 _assert(method != NULL);
5555 imp_ = method_getImplementation(method);
5556 _assert(imp_ != NULL);
5559 - (void) setObject:(id)object {
5565 object_ = [object retain];
5568 - (void) setObject:(id)object forFilter:(SEL)filter {
5569 [self setFilter:filter];
5570 [self setObject:object];
5573 - (bool) hasPackage:(Package *)package {
5574 _profile(FilteredPackageTable$hasPackage)
5575 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5579 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5580 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5581 [self setFilter:filter];
5582 object_ = [object retain];
5590 /* Filtered Package Controller {{{ */
5591 @interface FilteredPackageController : CYViewController {
5592 _transient Database *database_;
5593 FilteredPackageTable *packages_;
5597 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5601 @implementation FilteredPackageController
5604 [packages_ release];
5610 - (void) viewDidAppear:(BOOL)animated {
5611 [super viewDidAppear:animated];
5612 [packages_ deselectWithAnimation:animated];
5615 - (void) didSelectPackage:(Package *)package {
5616 PackageController *view([delegate_ packageController]);
5617 [view setPackage:package];
5618 [view setDelegate:delegate_];
5619 [[self navigationController] pushViewController:view animated:YES];
5622 - (id) title { return title_; }
5624 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5625 if ((self = [super init]) != nil) {
5626 database_ = database;
5627 title_ = [title copy];
5628 [[self navigationItem] setTitle:title_];
5630 packages_ = [[FilteredPackageTable alloc]
5631 initWithFrame:[[self view] bounds]
5634 action:@selector(didSelectPackage:)
5639 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5640 [[self view] addSubview:packages_];
5644 - (void) reloadData {
5645 [packages_ reloadData];
5648 - (void) setDelegate:(id)delegate {
5649 [super setDelegate:delegate];
5650 [packages_ setDelegate:delegate];
5657 /* Add Source Controller {{{ */
5658 @interface AddSourceController : CYViewController {
5659 _transient Database *database_;
5662 - (id) initWithDatabase:(Database *)database;
5666 @implementation AddSourceController
5668 - (id) initWithDatabase:(Database *)database {
5669 if ((self = [super init]) != nil) {
5670 database_ = database;
5676 /* Source Cell {{{ */
5677 @interface SourceCell : UITableViewCell <
5682 NSString *description_;
5684 ContentView *content_;
5687 - (void) setSource:(Source *)source;
5691 @implementation SourceCell
5693 - (void) clearSource {
5696 [description_ release];
5705 - (void) setSource:(Source *)source {
5709 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5711 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5712 icon_ = [icon_ retain];
5714 origin_ = [[source name] retain];
5715 label_ = [[source uri] retain];
5716 description_ = [[source description] retain];
5718 [content_ setNeedsDisplay];
5727 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5728 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5729 UIView *content([self contentView]);
5730 CGRect bounds([content bounds]);
5732 content_ = [[ContentView alloc] initWithFrame:bounds];
5733 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5734 [content_ setBackgroundColor:[UIColor whiteColor]];
5735 [content addSubview:content_];
5737 [content_ setDelegate:self];
5738 [content_ setOpaque:YES];
5742 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5743 [super setSelected:selected animated:animated];
5744 [content_ setNeedsDisplay];
5747 - (void) drawContentRect:(CGRect)rect {
5748 bool selected([self isSelected]);
5749 float width(rect.size.width);
5752 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5759 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5763 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5767 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5772 /* Source Table {{{ */
5773 @interface SourceTable : CYViewController <
5774 UITableViewDataSource,
5777 _transient Database *database_;
5779 NSMutableArray *sources_;
5783 UIProgressHUD *hud_;
5786 //NSURLConnection *installer_;
5787 NSURLConnection *trivial_;
5788 NSURLConnection *trivial_bz2_;
5789 NSURLConnection *trivial_gz_;
5790 //NSURLConnection *automatic_;
5795 - (id) initWithDatabase:(Database *)database;
5797 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5801 @implementation SourceTable
5803 - (void) _deallocConnection:(NSURLConnection *)connection {
5804 if (connection != nil) {
5805 [connection cancel];
5806 //[connection setDelegate:nil];
5807 [connection release];
5819 //[self _deallocConnection:installer_];
5820 [self _deallocConnection:trivial_];
5821 [self _deallocConnection:trivial_gz_];
5822 [self _deallocConnection:trivial_bz2_];
5823 //[self _deallocConnection:automatic_];
5830 - (void) viewDidAppear:(BOOL)animated {
5831 [super viewDidAppear:animated];
5832 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5835 - (int) numberOfSectionsInTableView:(UITableView *)tableView {
5836 return offset_ == 0 ? 1 : 2;
5839 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(int)section {
5840 switch (section + (offset_ == 0 ? 1 : 0)) {
5841 case 0: return UCLocalize("ENTERED_BY_USER");
5842 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5848 - (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
5849 int count = [sources_ count];
5851 case 0: return (offset_ == 0 ? count : offset_);
5852 case 1: return count - offset_;
5858 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5860 switch (indexPath.section) {
5861 case 0: idx = indexPath.row; break;
5862 case 1: idx = indexPath.row + offset_; break;
5866 return [sources_ objectAtIndex:idx];
5869 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5870 Source *source = [self sourceAtIndexPath:indexPath];
5871 return [source description] == nil ? 56 : 73;
5874 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5875 static NSString *cellIdentifier = @"SourceCell";
5877 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5878 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5879 [cell setSource:[self sourceAtIndexPath:indexPath]];
5884 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5885 return UITableViewCellAccessoryDisclosureIndicator;
5888 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5889 Source *source = [self sourceAtIndexPath:indexPath];
5891 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5892 initWithDatabase:database_
5893 title:[source label]
5894 filter:@selector(isVisibleInSource:)
5898 [packages setDelegate:delegate_];
5900 [[self navigationController] pushViewController:packages animated:YES];
5903 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5904 Source *source = [self sourceAtIndexPath:indexPath];
5905 return [source record] != nil;
5908 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5909 Source *source = [self sourceAtIndexPath:indexPath];
5910 [Sources_ removeObjectForKey:[source key]];
5911 [delegate_ syncData];
5915 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5918 @"./", @"Distribution",
5919 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5921 [delegate_ syncData];
5924 - (NSString *) getWarning {
5925 NSString *href(href_);
5926 NSRange colon([href rangeOfString:@"://"]);
5927 if (colon.location != NSNotFound)
5928 href = [href substringFromIndex:(colon.location + 3)];
5929 href = [href stringByAddingPercentEscapes];
5930 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5931 href = [href stringByCachingURLWithCurrentCDN];
5933 NSURL *url([NSURL URLWithString:href]);
5935 NSStringEncoding encoding;
5936 NSError *error(nil);
5938 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5939 return [warning length] == 0 ? nil : warning;
5943 - (void) _endConnection:(NSURLConnection *)connection {
5944 NSURLConnection **field = NULL;
5945 if (connection == trivial_)
5947 else if (connection == trivial_bz2_)
5948 field = &trivial_bz2_;
5949 else if (connection == trivial_gz_)
5950 field = &trivial_gz_;
5951 _assert(field != NULL);
5952 [connection release];
5957 trivial_bz2_ == nil &&
5963 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5966 UIAlertView *alert = [[[UIAlertView alloc]
5967 initWithTitle:UCLocalize("SOURCE_WARNING")
5970 cancelButtonTitle:UCLocalize("CANCEL")
5971 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5974 [alert setContext:@"warning"];
5975 [alert setNumberOfRows:1];
5979 } else if (error_ != nil) {
5980 UIAlertView *alert = [[[UIAlertView alloc]
5981 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5982 message:[error_ localizedDescription]
5984 cancelButtonTitle:UCLocalize("OK")
5985 otherButtonTitles:nil
5988 [alert setContext:@"urlerror"];
5991 UIAlertView *alert = [[[UIAlertView alloc]
5992 initWithTitle:UCLocalize("NOT_REPOSITORY")
5993 message:UCLocalize("NOT_REPOSITORY_EX")
5995 cancelButtonTitle:UCLocalize("OK")
5996 otherButtonTitles:nil
5999 [alert setContext:@"trivial"];
6003 [delegate_ setStatusBarShowsProgress:NO];
6004 [delegate_ removeProgressHUD:hud_];
6014 if (error_ != nil) {
6021 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6022 switch ([response statusCode]) {
6028 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6029 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6031 error_ = [error retain];
6032 [self _endConnection:connection];
6035 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6036 [self _endConnection:connection];
6039 - (id)title { return UCLocalize("SOURCES"); }
6041 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6042 NSMutableURLRequest *request = [NSMutableURLRequest
6043 requestWithURL:[NSURL URLWithString:href]
6044 cachePolicy:NSURLRequestUseProtocolCachePolicy
6045 timeoutInterval:120.0
6048 [request setHTTPMethod:method];
6050 if (Machine_ != NULL)
6051 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6052 if (UniqueID_ != nil)
6053 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6055 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6057 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6060 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6061 NSString *context([alert context]);
6063 if ([context isEqualToString:@"source"]) {
6066 NSString *href = [[alert textField] text];
6068 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6070 if (![href hasSuffix:@"/"])
6071 href_ = [href stringByAppendingString:@"/"];
6074 href_ = [href_ retain];
6076 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6077 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6078 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6079 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6083 hud_ = [[delegate_ addProgressHUD] retain];
6084 [hud_ setText:UCLocalize("VERIFYING_URL")];
6093 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6094 } else if ([context isEqualToString:@"trivial"])
6095 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6096 else if ([context isEqualToString:@"urlerror"])
6097 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6098 else if ([context isEqualToString:@"warning"]) {
6113 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6117 - (id) initWithDatabase:(Database *)database {
6118 if ((self = [super init]) != nil) {
6119 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6120 [self updateButtonsForEditingStatus:NO animated:NO];
6122 database_ = database;
6123 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6125 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6126 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6127 [[self view] addSubview:list_];
6129 [list_ setDataSource:self];
6130 [list_ setDelegate:self];
6136 - (void) reloadData {
6138 if (!list.ReadMainList())
6141 [sources_ removeAllObjects];
6142 [sources_ addObjectsFromArray:[database_ sources]];
6144 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6147 int count([sources_ count]);
6149 for (int i = 0; i != count; i++) {
6150 if ([[sources_ objectAtIndex:i] record] == nil) break;
6154 [list_ setEditing:NO];
6155 [self updateButtonsForEditingStatus:NO animated:NO];
6159 - (void) addButtonClicked {
6160 /*[book_ pushPage:[[[AddSourceController alloc]
6165 UIAlertView *alert = [[[UIAlertView alloc]
6166 initWithTitle:UCLocalize("ENTER_APT_URL")
6169 cancelButtonTitle:UCLocalize("CANCEL")
6170 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6173 [alert setContext:@"source"];
6174 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6176 [alert setNumberOfRows:1];
6177 [alert addTextFieldWithValue:@"http://" label:@""];
6179 UITextInputTraits *traits = [[alert textField] textInputTraits];
6180 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6181 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6182 [traits setKeyboardType:UIKeyboardTypeURL];
6183 // XXX: UIReturnKeyDone
6184 [traits setReturnKeyType:UIReturnKeyNext];
6189 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6190 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
6191 initWithTitle:UCLocalize("ADD")
6192 style:UIBarButtonItemStylePlain
6194 action:@selector(addButtonClicked)
6196 [[self navigationItem] setLeftBarButtonItem:editing ? leftItem : [[self navigationItem] backBarButtonItem] animated:animated];
6199 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6200 initWithTitle:editing ? UCLocalize("DONE") : UCLocalize("EDIT")
6201 style:editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6203 action:@selector(editButtonClicked)
6205 [[self navigationItem] setRightBarButtonItem:rightItem animated:animated];
6206 [rightItem release];
6208 if (IsWildcat_ && !editing) {
6209 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6210 initWithTitle:UCLocalize("SETTINGS")
6211 style:UIBarButtonItemStylePlain
6213 action:@selector(settingsButtonClicked)
6215 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6216 [settingsItem release];
6220 - (void) settingsButtonClicked {
6221 [delegate_ showSettings];
6224 - (void) editButtonClicked {
6225 [list_ setEditing:![list_ isEditing] animated:YES];
6227 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6233 /* Installed Controller {{{ */
6234 @interface InstalledController : FilteredPackageController {
6238 - (id) initWithDatabase:(Database *)database;
6240 - (void) updateRoleButton;
6241 - (void) queueStatusDidChange;
6245 @implementation InstalledController
6251 - (id) title { return UCLocalize("INSTALLED"); }
6253 - (id) initWithDatabase:(Database *)database {
6254 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6255 [self updateRoleButton];
6256 [self queueStatusDidChange];
6261 - (void) queueButtonClicked {
6266 - (void) queueStatusDidChange {
6269 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6270 initWithTitle:UCLocalize("QUEUE")
6271 style:UIBarButtonItemStyleDone
6273 action:@selector(queueButtonClicked)
6275 if (Queuing_) [[self navigationItem] setLeftBarButtonItem:queueItem];
6276 else [[self navigationItem] setLeftBarButtonItem:nil];
6277 [queueItem release];
6282 - (void) reloadData {
6283 [packages_ reloadData];
6286 - (void) updateRoleButton {
6287 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6288 initWithTitle:expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")
6289 style:expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6291 action:@selector(roleButtonClicked)
6293 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) [[self navigationItem] setRightBarButtonItem:rightItem];
6294 [rightItem release];
6297 - (void) roleButtonClicked {
6298 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6299 [packages_ reloadData];
6302 [self updateRoleButton];
6305 - (void) setDelegate:(id)delegate {
6306 [super setDelegate:delegate];
6307 [packages_ setDelegate:delegate];
6313 /* Home Controller {{{ */
6314 @interface HomeController : CYBrowserController {
6319 @implementation HomeController
6321 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6322 [super _setMoreHeaders:request];
6324 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6325 if (UniqueID_ != nil)
6326 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6329 - (void) aboutButtonClicked {
6330 UIAlertView *alert = [[[UIAlertView alloc] init] autorelease];
6331 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6332 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6333 [alert setCancelButtonIndex:0];
6336 @"Copyright (C) 2008-2010\n"
6337 "Jay Freeman (saurik)\n"
6338 "saurik@saurik.com\n"
6339 "http://www.saurik.com/"
6345 - (void) viewWillAppear:(BOOL)animated {
6346 [super viewWillAppear:animated];
6347 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6350 - (void) viewWillDisappear:(BOOL)animated {
6351 [super viewWillDisappear:animated];
6352 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6356 if ((self = [super init]) != nil) {
6357 UIBarButtonItem *aboutItem = [[UIBarButtonItem alloc]
6358 initWithTitle:UCLocalize("ABOUT")
6359 style:UIBarButtonItemStylePlain
6361 action:@selector(aboutButtonClicked)
6363 [[self navigationItem] setLeftBarButtonItem:aboutItem];
6364 [aboutItem release];
6370 /* Manage Controller {{{ */
6371 @interface ManageController : CYBrowserController {
6374 - (void) queueStatusDidChange;
6377 @implementation ManageController
6380 if ((self = [super init]) != nil) {
6381 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6383 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6384 initWithTitle:UCLocalize("SETTINGS")
6385 style:UIBarButtonItemStylePlain
6387 action:@selector(settingsButtonClicked)
6389 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6390 [settingsItem release];
6392 [self queueStatusDidChange];
6396 - (void) settingsButtonClicked {
6397 [delegate_ showSettings];
6401 - (void) queueButtonClicked {
6405 - (void) applyLoadingTitle {
6406 // No "Loading" title.
6409 - (void) applyRightButton {
6414 - (void) queueStatusDidChange {
6416 if (!IsWildcat_ && Queuing_) {
6417 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6418 initWithTitle:UCLocalize("QUEUE")
6419 style:UIBarButtonItemStyleDone
6421 action:@selector(queueButtonClicked)
6423 [[self navigationItem] setRightBarButtonItem:queueItem];
6425 [queueItem release];
6427 [[self navigationItem] setRightBarButtonItem:nil];
6432 - (bool) isLoading {
6439 /* Refresh Bar {{{ */
6440 @interface RefreshBar : UINavigationBar {
6441 UIProgressIndicator *indicator_;
6442 UITextLabel *prompt_;
6443 UIProgressBar *progress_;
6444 UINavigationButton *cancel_;
6449 @implementation RefreshBar
6451 - (void) positionViews {
6452 CGRect frame = [cancel_ frame];
6453 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6454 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6455 [cancel_ setFrame:frame];
6457 CGSize prgsize = {75, 100};
6459 [self frame].size.width - prgsize.width - 10,
6460 ([self frame].size.height - prgsize.height) / 2
6462 [progress_ setFrame:prgrect];
6464 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6465 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6466 CGRect indrect = {{indoffset, indoffset}, indsize};
6467 [indicator_ setFrame:indrect];
6469 CGSize prmsize = {215, indsize.height + 4};
6471 indoffset * 2 + indsize.width,
6472 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6474 [prompt_ setFrame:prmrect];
6477 - (void)setFrame:(CGRect)frame {
6478 [super setFrame:frame];
6480 [self positionViews];
6483 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6484 if ((self = [super initWithFrame:frame])) {
6485 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6487 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6488 [self setBarStyle:UIBarStyleBlack];
6490 UIBarStyle barstyle([self _barStyle:NO]);
6491 bool ugly(barstyle == UIBarStyleDefault);
6493 UIProgressIndicatorStyle style = ugly ?
6494 UIProgressIndicatorStyleMediumBrown :
6495 UIProgressIndicatorStyleMediumWhite;
6497 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6498 [indicator_ setStyle:style];
6499 [indicator_ startAnimation];
6500 [self addSubview:indicator_];
6502 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6503 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6504 [prompt_ setBackgroundColor:[UIColor clearColor]];
6505 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6506 [self addSubview:prompt_];
6508 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6509 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6510 [progress_ setStyle:0];
6511 [self addSubview:progress_];
6513 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6514 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6515 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6516 [cancel_ setBarStyle:barstyle];
6518 [self positionViews];
6523 [cancel_ removeFromSuperview];
6527 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6528 [progress_ setProgress:0];
6529 [self addSubview:cancel_];
6533 [cancel_ removeFromSuperview];
6536 - (void) setPrompt:(NSString *)prompt {
6537 [prompt_ setText:prompt];
6540 - (void) setProgress:(float)progress {
6541 [progress_ setProgress:progress];
6547 @class CYNavigationController;
6549 /* Cydia Tab Bar Controller {{{ */
6550 @interface CYTabBarController : UITabBarController {
6551 Database *database_;
6556 @implementation CYTabBarController
6558 /* XXX: some logic should probably go here related to
6559 freeing the view controllers on tab change */
6561 - (void) reloadData {
6562 size_t count([[self viewControllers] count]);
6563 for (size_t i(0); i != count; ++i) {
6564 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6569 - (id) initWithDatabase: (Database *)database {
6570 if ((self = [super init]) != nil) {
6571 database_ = database;
6578 /* Cydia Navigation Controller {{{ */
6579 @interface CYNavigationController : UINavigationController {
6580 _transient Database *database_;
6584 - (id) initWithDatabase:(Database *)database;
6585 - (void) reloadData;
6590 @implementation CYNavigationController
6592 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6593 // Inherit autorotation settings for modal parents.
6594 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6595 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6597 return [super shouldAutorotateToInterfaceOrientation:orientation];
6605 - (void) reloadData {
6606 size_t count([[self viewControllers] count]);
6607 for (size_t i(0); i != count; ++i) {
6608 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6613 - (void) setDelegate:(id)delegate {
6614 delegate_ = delegate;
6617 - (id) initWithDatabase:(Database *)database {
6618 if ((self = [super init]) != nil) {
6619 database_ = database;
6625 /* Cydia:// Protocol {{{ */
6626 @interface CydiaURLProtocol : NSURLProtocol {
6631 @implementation CydiaURLProtocol
6633 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6634 NSURL *url([request URL]);
6637 NSString *scheme([[url scheme] lowercaseString]);
6638 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6643 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6647 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6648 id<NSURLProtocolClient> client([self client]);
6650 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6652 NSData *data(UIImagePNGRepresentation(icon));
6654 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6655 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6656 [client URLProtocol:self didLoadData:data];
6657 [client URLProtocolDidFinishLoading:self];
6661 - (void) startLoading {
6662 id<NSURLProtocolClient> client([self client]);
6663 NSURLRequest *request([self request]);
6665 NSURL *url([request URL]);
6666 NSString *href([url absoluteString]);
6668 NSString *path([href substringFromIndex:8]);
6669 NSRange slash([path rangeOfString:@"/"]);
6672 if (slash.location == NSNotFound) {
6676 command = [path substringToIndex:slash.location];
6677 path = [path substringFromIndex:(slash.location + 1)];
6680 Database *database([Database sharedInstance]);
6682 if ([command isEqualToString:@"package-icon"]) {
6685 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6686 Package *package([database packageWithName:path]);
6689 UIImage *icon([package icon]);
6690 [self _returnPNGWithImage:icon forRequest:request];
6691 } else if ([command isEqualToString:@"source-icon"]) {
6694 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6695 NSString *source(Simplify(path));
6696 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6698 icon = [UIImage applicationImageNamed:@"unknown.png"];
6699 [self _returnPNGWithImage:icon forRequest:request];
6700 } else if ([command isEqualToString:@"uikit-image"]) {
6703 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6704 UIImage *icon(_UIImageWithName(path));
6705 [self _returnPNGWithImage:icon forRequest:request];
6706 } else if ([command isEqualToString:@"section-icon"]) {
6709 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6710 NSString *section(Simplify(path));
6711 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6713 icon = [UIImage applicationImageNamed:@"unknown.png"];
6714 [self _returnPNGWithImage:icon forRequest:request];
6716 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6720 - (void) stopLoading {
6726 /* Sections Controller {{{ */
6727 @interface SectionsController : CYViewController <
6728 UITableViewDataSource,
6731 _transient Database *database_;
6732 NSMutableArray *sections_;
6733 NSMutableArray *filtered_;
6739 - (id) initWithDatabase:(Database *)database;
6740 - (void) reloadData;
6743 - (void) editButtonClicked;
6747 @implementation SectionsController
6750 [list_ setDataSource:nil];
6751 [list_ setDelegate:nil];
6753 [sections_ release];
6754 [filtered_ release];
6756 [accessory_ release];
6760 - (void) viewDidAppear:(BOOL)animated {
6761 [super viewDidAppear:animated];
6762 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6765 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6766 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6770 - (int) tableView:(UITableView *)tableView numberOfRowsInSection:(int)section {
6771 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6774 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6778 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6779 static NSString *reuseIdentifier = @"SectionCell";
6781 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6782 if (cell == nil) cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6783 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6788 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6789 Section *section = [self sectionAtIndexPath:indexPath];
6790 NSString *name = [section name];
6793 if ([indexPath row] == 0) {
6796 title = UCLocalize("ALL_PACKAGES");
6799 name = [NSString stringWithString:name];
6800 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6803 title = UCLocalize("NO_SECTION");
6807 FilteredPackageController *table = [[[FilteredPackageController alloc]
6808 initWithDatabase:database_
6810 filter:@selector(isVisibleInSection:)
6814 [table setDelegate:delegate_];
6816 [[self navigationController] pushViewController:table animated:YES];
6819 - (id) title { return UCLocalize("SECTIONS"); }
6821 - (id) initWithDatabase:(Database *)database {
6822 if ((self = [super init]) != nil) {
6823 database_ = database;
6825 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6827 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6828 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6830 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6831 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6832 [list_ setRowHeight:45.0f];
6833 [[self view] addSubview:list_];
6835 [list_ setDataSource:self];
6836 [list_ setDelegate:self];
6842 - (void) reloadData {
6843 NSArray *packages = [database_ packages];
6845 [sections_ removeAllObjects];
6846 [filtered_ removeAllObjects];
6849 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6850 SectionMap sections;
6851 sections.resize(64);
6853 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6857 for (Package *package in packages) {
6858 NSString *name([package section]);
6859 NSString *key(name == nil ? @"" : name);
6864 _profile(SectionsView$reloadData$Section)
6865 section = §ions[key];
6866 if (*section == nil) {
6867 _profile(SectionsView$reloadData$Section$Allocate)
6868 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6873 [*section addToCount];
6875 _profile(SectionsView$reloadData$Filter)
6876 if (![package valid] || ![package visible])
6880 [*section addToRow];
6884 _profile(SectionsView$reloadData$Section)
6885 section = [sections objectForKey:key];
6886 if (section == nil) {
6887 _profile(SectionsView$reloadData$Section$Allocate)
6888 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6889 [sections setObject:section forKey:key];
6894 [section addToCount];
6896 _profile(SectionsView$reloadData$Filter)
6897 if (![package valid] || ![package visible])
6907 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6908 [sections_ addObject:i->second];
6910 [sections_ addObjectsFromArray:[sections allValues]];
6913 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6915 for (Section *section in sections_) {
6916 size_t count([section row]);
6920 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6921 [section setCount:count];
6922 [filtered_ addObject:section];
6925 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6926 initWithTitle:[sections_ count] == 0 ? nil : UCLocalize("EDIT")
6927 style:UIBarButtonItemStylePlain
6929 action:@selector(editButtonClicked)
6931 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] != nil];
6932 [rightItem release];
6938 - (void) resetView {
6940 [self editButtonClicked];
6943 - (void) editButtonClicked {
6944 if ((editing_ = !editing_))
6947 [delegate_ updateData];
6949 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6950 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6951 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6954 - (UIView *) accessoryView {
6960 /* Changes Controller {{{ */
6961 @interface ChangesController : CYViewController <
6962 UITableViewDataSource,
6965 _transient Database *database_;
6966 NSMutableArray *packages_;
6967 NSMutableArray *sections_;
6970 BOOL hasSentFirstLoad_;
6973 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6974 - (void) reloadData;
6978 @implementation ChangesController
6981 [list_ setDelegate:nil];
6982 [list_ setDataSource:nil];
6984 [packages_ release];
6985 [sections_ release];
6990 - (void) viewDidAppear:(BOOL)animated {
6991 [super viewDidAppear:animated];
6992 if (!hasSentFirstLoad_) {
6993 hasSentFirstLoad_ = YES;
6994 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6996 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7000 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7001 NSInteger count([sections_ count]);
7002 return count == 0 ? 1 : count;
7005 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7006 if ([sections_ count] == 0)
7008 return [[sections_ objectAtIndex:section] name];
7011 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7012 if ([sections_ count] == 0)
7014 return [[sections_ objectAtIndex:section] count];
7017 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7018 Section *section([sections_ objectAtIndex:[path section]]);
7019 NSInteger row([path row]);
7020 return [packages_ objectAtIndex:([section row] + row)];
7023 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7024 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7026 cell = [[[PackageCell alloc] init] autorelease];
7027 [cell setPackage:[self packageAtIndexPath:path]];
7031 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7032 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7035 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7036 Package *package([self packageAtIndexPath:path]);
7037 PackageController *view([delegate_ packageController]);
7038 [view setDelegate:delegate_];
7039 [view setPackage:package];
7040 [[self navigationController] pushViewController:view animated:YES];
7044 - (void) refreshButtonClicked {
7045 [delegate_ beginUpdate];
7046 [[self navigationItem] setLeftBarButtonItem:nil];
7049 - (void) upgradeButtonClicked {
7050 [delegate_ distUpgrade];
7053 - (id) title { return UCLocalize("CHANGES"); }
7055 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7056 if ((self = [super init]) != nil) {
7057 database_ = database;
7058 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7060 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
7061 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7063 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7064 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7065 [list_ setRowHeight:73.0f];
7066 [[self view] addSubview:list_];
7068 [list_ setDataSource:self];
7069 [list_ setDelegate:self];
7071 delegate_ = delegate;
7075 - (void) _reloadPackages:(NSArray *)packages {
7077 for (Package *package in packages)
7079 [package uninstalled] && [package valid] && [package visible] ||
7080 [package upgradableAndEssential:YES]
7082 [packages_ addObject:package];
7085 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7089 - (void) reloadData {
7090 NSArray *packages = [database_ packages];
7092 [packages_ removeAllObjects];
7093 [sections_ removeAllObjects];
7095 UIProgressHUD *hud([delegate_ addProgressHUD]);
7097 [hud setText:@"Loading Changes"];
7098 NSLog(@"HUD:%@::%@", delegate_, hud);
7099 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7100 [delegate_ removeProgressHUD:hud];
7102 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7103 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7104 Section *section = nil;
7108 bool unseens = false;
7110 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7112 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7113 Package *package = [packages_ objectAtIndex:offset];
7115 BOOL uae = [package upgradableAndEssential:YES];
7121 _profile(ChangesController$reloadData$Remember)
7122 seen = [package seen];
7125 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7130 name = UCLocalize("UNKNOWN");
7132 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7136 _profile(ChangesController$reloadData$Allocate)
7137 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7138 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7139 [sections_ addObject:section];
7143 [section addToCount];
7144 } else if ([package ignored])
7145 [ignored addToCount];
7148 [upgradable addToCount];
7153 CFRelease(formatter);
7156 Section *last = [sections_ lastObject];
7157 size_t count = [last count];
7158 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7159 [sections_ removeLastObject];
7162 if ([ignored count] != 0)
7163 [sections_ insertObject:ignored atIndex:0];
7165 [sections_ insertObject:upgradable atIndex:0];
7169 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7170 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7171 style:UIBarButtonItemStylePlain
7173 action:@selector(upgradeButtonClicked)
7175 if (upgrades_ > 0) [[self navigationItem] setRightBarButtonItem:rightItem];
7176 [rightItem release];
7178 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
7179 initWithTitle:UCLocalize("REFRESH")
7180 style:UIBarButtonItemStylePlain
7182 action:@selector(refreshButtonClicked)
7184 if (![delegate_ updating]) [[self navigationItem] setLeftBarButtonItem:leftItem];
7190 /* Search Controller {{{ */
7191 @interface SearchController : FilteredPackageController <
7194 UISearchBar *search_;
7197 - (id) initWithDatabase:(Database *)database;
7198 - (void) reloadData;
7202 @implementation SearchController
7209 - (void) searchBarSearchButtonClicked:(id)searchBar {
7210 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7211 [search_ resignFirstResponder];
7215 - (void) searchBar:(id)searchBar textDidChange:(NSString *)text {
7216 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7220 - (id) title { return nil; }
7222 - (id) initWithDatabase:(Database *)database {
7223 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7226 - (void)viewDidAppear:(BOOL)animated {
7227 [super viewDidAppear:animated];
7229 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7230 [search_ layoutSubviews];
7231 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7232 UITextField *textField = [search_ searchField];
7233 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7234 [search_ setDelegate:self];
7235 [textField setEnablesReturnKeyAutomatically:NO];
7236 [[self navigationItem] setTitleView:textField];
7240 - (void) _reloadData {
7243 - (void) reloadData {
7244 _profile(SearchController$reloadData)
7245 [packages_ reloadData];
7248 [packages_ resetCursor];
7251 - (void) didSelectPackage:(Package *)package {
7252 [search_ resignFirstResponder];
7253 [super didSelectPackage:package];
7258 /* Settings Controller {{{ */
7259 @interface SettingsController : CYViewController <
7260 UITableViewDataSource,
7263 _transient Database *database_;
7266 UITableView *table_;
7267 id subscribedSwitch_;
7269 UITableViewCell *subscribedCell_;
7270 UITableViewCell *ignoredCell_;
7273 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7277 @implementation SettingsController
7281 if (package_ != nil)
7284 [subscribedSwitch_ release];
7285 [ignoredSwitch_ release];
7286 [subscribedCell_ release];
7287 [ignoredCell_ release];
7292 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7293 if (package_ == nil)
7299 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7300 if (package_ == nil)
7306 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7307 return UCLocalize("SHOW_ALL_CHANGES_EX");
7310 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7311 if (package_ == nil)
7314 NSMutableDictionary *metadata([package_ metadata]);
7317 if (NSNumber *number = [metadata objectForKey:key])
7318 before = [number boolValue];
7322 if (value != before) {
7323 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7325 [delegate_ updateData];
7329 - (void) onSubscribed:(id)control {
7330 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7333 - (void) onIgnored:(id)control {
7334 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
7337 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7338 if (package_ == nil)
7341 switch ([indexPath row]) {
7342 case 0: return subscribedCell_;
7343 case 1: return ignoredCell_;
7351 - (id) title { return UCLocalize("SETTINGS"); }
7353 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7354 if ((self = [super init])) {
7355 database_ = database;
7356 name_ = [package retain];
7358 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7360 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7361 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7362 [table_ setAllowsSelection:NO];
7363 [[self view] addSubview:table_];
7365 subscribedSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7366 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7367 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7369 ignoredSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7370 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7371 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7373 subscribedCell_ = [[UITableViewCell alloc] init];
7374 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7375 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7377 ignoredCell_ = [[UITableViewCell alloc] init];
7378 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7379 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7381 [table_ setDataSource:self];
7382 [table_ setDelegate:self];
7387 - (void) reloadData {
7388 if (package_ != nil)
7389 [package_ autorelease];
7390 package_ = [database_ packageWithName:name_];
7391 if (package_ != nil) {
7393 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7394 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7397 [table_ reloadData];
7403 /* Signature Controller {{{ */
7404 @interface SignatureController : CYBrowserController {
7405 _transient Database *database_;
7409 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7413 @implementation SignatureController
7420 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7422 [super webView:sender didClearWindowObject:window forFrame:frame];
7425 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7426 if ((self = [super init]) != nil) {
7427 database_ = database;
7428 package_ = [package retain];
7433 - (void) reloadData {
7434 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7439 /* Role Controller {{{ */
7440 @interface RoleController : CYViewController <
7441 UITableViewDataSource,
7444 _transient Database *database_;
7446 UITableView *table_;
7447 UISegmentedControl *segment_;
7451 - (void) showDoneButton;
7452 - (void) resizeSegmentedControl;
7456 @implementation RoleController
7460 [container_ release];
7465 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7466 if ((self = [super init])) {
7467 database_ = database;
7468 roledelegate_ = delegate;
7470 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7472 NSArray *items = [NSArray arrayWithObjects:
7474 UCLocalize("HACKER"),
7475 UCLocalize("DEVELOPER"),
7477 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7478 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7479 [container_ addSubview:segment_];
7482 if ([Role_ isEqualToString:@"User"]) index = 0;
7483 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7484 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7486 [segment_ setSelectedSegmentIndex:index];
7487 [self showDoneButton];
7490 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7491 [self resizeSegmentedControl];
7493 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7494 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7495 [table_ setDelegate:self];
7496 [table_ setDataSource:self];
7497 [[self view] addSubview:table_];
7498 [table_ reloadData];
7502 - (void) resizeSegmentedControl {
7503 CGFloat width = [[self view] frame].size.width;
7504 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7507 - (void) viewWillAppear:(BOOL)animated {
7508 [super viewWillAppear:animated];
7510 [self resizeSegmentedControl];
7513 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7514 [self resizeSegmentedControl];
7517 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7518 [self resizeSegmentedControl];
7522 NSString *role(nil);
7524 switch ([segment_ selectedSegmentIndex]) {
7525 case 0: role = @"User"; break;
7526 case 1: role = @"Hacker"; break;
7527 case 2: role = @"Developer"; break;
7532 if (![role isEqualToString:Role_]) {
7533 bool rolling(Role_ == nil);
7536 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7540 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7545 [roledelegate_ loadData];
7547 [roledelegate_ updateData];
7551 - (void) segmentChanged:(UISegmentedControl *)control {
7552 [self showDoneButton];
7555 - (void) doneButtonClicked {
7557 [[self navigationController] dismissModalViewControllerAnimated:YES];
7560 - (void) showDoneButton {
7561 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7562 initWithTitle:UCLocalize("DONE")
7563 style:UIBarButtonItemStyleDone
7565 action:@selector(doneButtonClicked)
7567 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] == nil];
7568 [rightItem release];
7571 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7572 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7576 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7580 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7581 return nil; // This method is required by the protocol.
7584 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7586 return UCLocalize("ROLE_EX");
7588 return [NSString stringWithFormat:
7589 @"%@: %@\n%@: %@\n%@: %@",
7590 UCLocalize("USER"), UCLocalize("USER_EX"),
7591 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7592 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7597 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7598 if (section == 3) return 44.0f;
7602 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7603 if (section == 3) return container_;
7610 /* Cydia Container {{{ */
7611 @interface CYContainer : UIViewController <ProgressDelegate> {
7612 _transient Database *database_;
7613 RefreshBar *refreshbar_;
7618 UITabBarController *root_;
7621 - (void) setTabBarController:(UITabBarController *)controller;
7623 - (void) dropBar:(BOOL)animated;
7624 - (void) beginUpdate;
7625 - (void) raiseBar:(BOOL)animated;
7629 @implementation CYContainer
7631 // NOTE: UIWindow only sends the top controller these messages,
7632 // So we have to forward them on.
7634 - (void) viewDidAppear:(BOOL)animated {
7635 [super viewDidAppear:animated];
7636 [root_ viewDidAppear:animated];
7639 - (void) viewWillAppear:(BOOL)animated {
7640 [super viewWillAppear:animated];
7641 [root_ viewWillAppear:animated];
7644 - (void) viewDidDisappear:(BOOL)animated {
7645 [super viewDidDisappear:animated];
7646 [root_ viewDidDisappear:animated];
7649 - (void) viewWillDisappear:(BOOL)animated {
7650 [super viewWillDisappear:animated];
7651 [root_ viewWillDisappear:animated];
7654 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7655 return YES; /* XXX: return YES; */
7658 - (void) setTabBarController:(UITabBarController *)controller {
7660 [[self view] addSubview:[root_ view]];
7663 - (void) setUpdate:(NSDate *)date {
7667 - (void) beginUpdate {
7669 [refreshbar_ start];
7674 detachNewThreadSelector:@selector(performUpdate)
7680 - (void) performUpdate { _pooled
7682 status.setDelegate(self);
7683 [database_ updateWithStatus:status];
7686 performSelectorOnMainThread:@selector(completeUpdate)
7692 - (void) completeUpdate {
7695 [self raiseBar:YES];
7697 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7700 - (void) cancelUpdate {
7701 [refreshbar_ cancel];
7702 [self completeUpdate];
7705 - (void) cancelPressed {
7706 [self cancelUpdate];
7713 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7714 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7717 - (void) startProgress {
7720 - (void) setProgressTitle:(NSString *)title {
7722 performSelectorOnMainThread:@selector(_setProgressTitle:)
7728 - (bool) isCancelling:(size_t)received {
7732 - (void) setProgressPercent:(float)percent {
7734 performSelectorOnMainThread:@selector(_setProgressPercent:)
7735 withObject:[NSNumber numberWithFloat:percent]
7740 - (void) addProgressOutput:(NSString *)output {
7742 performSelectorOnMainThread:@selector(_addProgressOutput:)
7748 - (void) _setProgressTitle:(NSString *)title {
7749 [refreshbar_ setPrompt:title];
7752 - (void) _setProgressPercent:(NSNumber *)percent {
7753 [refreshbar_ setProgress:[percent floatValue]];
7756 - (void) _addProgressOutput:(NSString *)output {
7759 - (void) setUpdateDelegate:(id)delegate {
7760 updatedelegate_ = delegate;
7763 - (void) dropBar:(BOOL)animated {
7764 if (dropped_) return;
7767 [[self view] addSubview:refreshbar_];
7769 if (animated) [UIView beginAnimations:nil context:NULL];
7770 CGRect barframe = [refreshbar_ frame];
7771 CGRect viewframe = [[root_ view] frame];
7772 viewframe.origin.y += barframe.size.height + 20.0f;
7773 viewframe.size.height -= barframe.size.height + 20.0f;
7774 [[root_ view] setFrame:viewframe];
7775 if (animated) [UIView commitAnimations];
7777 // Ensure bar has the proper width for our view, it might have changed
7778 barframe.size.width = viewframe.size.width;
7779 [refreshbar_ setFrame:barframe];
7781 // XXX: fix Apple's layout bug
7782 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7785 - (void) raiseBar:(BOOL)animated {
7786 if (!dropped_) return;
7789 [refreshbar_ removeFromSuperview];
7791 if (animated) [UIView beginAnimations:nil context:NULL];
7792 CGRect barframe = [refreshbar_ frame];
7793 CGRect viewframe = [[root_ view] frame];
7794 viewframe.origin.y -= barframe.size.height + 20.0f;
7795 viewframe.size.height += barframe.size.height + 20.0f;
7796 [[root_ view] setFrame:viewframe];
7797 if (animated) [UIView commitAnimations];
7799 // XXX: fix Apple's layout bug
7800 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7803 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7804 // XXX: fix Apple's layout bug
7805 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7808 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7814 // XXX: fix Apple's layout bug
7815 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7819 [refreshbar_ release];
7823 - (id) initWithDatabase: (Database *)database {
7824 if ((self = [super init]) != nil) {
7825 database_ = database;
7827 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7829 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7846 @interface Cydia : UIApplication <
7847 ConfirmationControllerDelegate,
7848 ProgressControllerDelegate,
7852 CYContainer *container_;
7856 NSMutableArray *essential_;
7857 NSMutableArray *broken_;
7859 Database *database_;
7863 UIKeyboard *keyboard_;
7864 UIProgressHUD *hud_;
7866 SectionsController *sections_;
7867 ChangesController *changes_;
7868 ManageController *manage_;
7869 SearchController *search_;
7870 SourceTable *sources_;
7871 InstalledController *installed_;
7874 #if RecyclePackageViews
7875 NSMutableArray *details_;
7881 - (UCViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7882 - (void) setPage:(UCViewController *)page;
7887 static _finline void _setHomePage(Cydia *self) {
7888 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7891 @implementation Cydia
7893 - (void) beginUpdate {
7894 [container_ beginUpdate];
7898 return [container_ updating];
7901 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7906 if ([broken_ count] != 0) {
7907 int count = [broken_ count];
7909 UIAlertView *alert = [[[UIAlertView alloc]
7910 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7911 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7913 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7914 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
7917 [alert setContext:@"fixhalf"];
7919 } else if (!Ignored_ && [essential_ count] != 0) {
7920 int count = [essential_ count];
7922 UIAlertView *alert = [[[UIAlertView alloc]
7923 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7924 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
7926 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
7927 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
7930 [alert setContext:@"upgrade"];
7935 - (void) _saveConfig {
7938 NSString *error(nil);
7939 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7941 NSError *error(nil);
7942 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7943 NSLog(@"failure to save metadata data: %@", error);
7946 NSLog(@"failure to serialize metadata: %@", error);
7954 - (void) _updateData {
7957 /* XXX: this is just stupid */
7958 if (tag_ != 1 && sections_ != nil)
7959 [sections_ reloadData];
7960 if (tag_ != 2 && changes_ != nil)
7961 [changes_ reloadData];
7962 if (tag_ != 4 && search_ != nil)
7963 [search_ reloadData];
7965 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
7968 - (int)indexOfTabWithTag:(int)tag {
7970 for (UINavigationController *controller in [tabbar_ viewControllers]) {
7971 if ([[controller tabBarItem] tag] == tag) return i;
7978 - (void) _refreshIfPossible {
7979 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
7981 Reachability* reachability = [Reachability reachabilityWithHostName:@"cydia.saurik.com"];
7982 NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
7984 if (loaded_ || ManualRefresh || remoteHostStatus == NotReachable) loaded:
7985 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
7989 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
7991 if (update != nil) {
7992 NSTimeInterval interval([update timeIntervalSinceNow]);
7993 if (interval <= 0 && interval > -(15*60))
7997 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8003 - (void) refreshIfPossible {
8004 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8007 - (void) _reloadData {
8008 UIProgressHUD *hud([self addProgressHUD]);
8009 [hud setText:(loaded_ ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
8011 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8014 [self removeProgressHUD:hud];
8018 [essential_ removeAllObjects];
8019 [broken_ removeAllObjects];
8021 NSArray *packages([database_ packages]);
8022 for (Package *package in packages) {
8024 [broken_ addObject:package];
8025 if ([package upgradableAndEssential:NO]) {
8026 if ([package essential])
8027 [essential_ addObject:package];
8033 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8034 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:badge];
8035 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:YES];
8037 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8038 [self setApplicationBadge:badge];
8040 [self setApplicationBadgeString:badge];
8042 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setBadgeValue:nil];
8043 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem] setAnimatedBadge:NO];
8045 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8046 [self removeApplicationBadge];
8047 else // XXX: maybe use setApplicationBadgeString also?
8048 [self setApplicationIconBadgeNumber:0];
8053 [self refreshIfPossible];
8056 - (void) updateData {
8057 [database_ setVisible];
8066 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8067 _assert(file != NULL);
8069 for (NSString *key in [Sources_ allKeys]) {
8070 NSDictionary *source([Sources_ objectForKey:key]);
8072 fprintf(file, "%s %s %s\n",
8073 [[source objectForKey:@"Type"] UTF8String],
8074 [[source objectForKey:@"URI"] UTF8String],
8075 [[source objectForKey:@"Distribution"] UTF8String]
8083 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8084 UINavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8085 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8086 [container_ presentModalViewController:navigation animated:YES];
8089 detachNewThreadSelector:@selector(update_)
8092 title:UCLocalize("UPDATING_SOURCES")
8096 - (void) reloadData {
8097 @synchronized (self) {
8103 pkgProblemResolver *resolver = [database_ resolver];
8105 resolver->InstallProtect();
8106 if (!resolver->Resolve(true))
8110 - (CGRect) popUpBounds {
8111 return [[tabbar_ view] bounds];
8115 if (![database_ prepare])
8118 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8119 [page setDelegate:self];
8120 id confirm_ = [[CYNavigationController alloc] initWithRootViewController:page];
8121 [confirm_ setDelegate:self];
8123 if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8124 [container_ presentModalViewController:confirm_ animated:YES];
8130 @synchronized (self) {
8135 - (void) clearPackage:(Package *)package {
8136 @synchronized (self) {
8143 - (void) installPackages:(NSArray *)packages {
8144 @synchronized (self) {
8145 for (Package *package in packages)
8152 - (void) installPackage:(Package *)package {
8153 @synchronized (self) {
8160 - (void) removePackage:(Package *)package {
8161 @synchronized (self) {
8168 - (void) distUpgrade {
8169 @synchronized (self) {
8170 if (![database_ upgrade])
8177 @synchronized (self) {
8182 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8183 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8185 if (navigation != nil) {
8186 [navigation pushViewController:progress animated:YES];
8188 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8189 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8190 [container_ presentModalViewController:navigation animated:YES];
8194 detachNewThreadSelector:@selector(perform)
8197 title:UCLocalize("RUNNING")
8201 - (void) progressControllerIsComplete:(ProgressController *)progress {
8205 - (void) setPage:(UCViewController *)page {
8206 [page setDelegate:self];
8208 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8209 [navController setViewControllers:[NSArray arrayWithObject:page] animated:NO];
8210 for (CYNavigationController *page in [tabbar_ viewControllers]) {
8211 if (page != navController) [page setViewControllers:nil];
8215 - (UCViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8216 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8217 [browser loadURL:url];
8221 - (SectionsController *) sectionsController {
8222 if (sections_ == nil)
8223 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8227 - (ChangesController *) changesController {
8228 if (changes_ == nil)
8229 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8233 - (ManageController *) manageController {
8234 if (manage_ == nil) {
8235 manage_ = (ManageController *) [[self
8236 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8237 withClass:[ManageController class]
8239 if (!IsWildcat_) queueDelegate_ = manage_;
8244 - (SearchController *) searchController {
8246 search_ = [[SearchController alloc] initWithDatabase:database_];
8250 - (SourceTable *) sourcesController {
8251 if (sources_ == nil)
8252 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8256 - (InstalledController *) installedController {
8257 if (installed_ == nil) {
8258 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8259 if (IsWildcat_) queueDelegate_ = installed_;
8264 - (void) tabBarController:(id)tabBarController didSelectViewController:(UIViewController *)viewController {
8265 int tag = [[viewController tabBarItem] tag];
8267 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8269 } else if (tag_ == 1) {
8270 [[self sectionsController] resetView];
8274 case kCydiaTag: _setHomePage(self); break;
8276 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8277 case kChangesTag: [self setPage:[self changesController]]; break;
8278 case kManageTag: [self setPage:[self manageController]]; break;
8279 case kInstalledTag: [self setPage:[self installedController]]; break;
8280 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8281 case kSearchTag: [self setPage:[self searchController]]; break;
8289 - (void) showSettings {
8290 RoleController *role = [[RoleController alloc] initWithDatabase:database_ delegate:self];
8291 CYNavigationController *nav = [[CYNavigationController alloc] initWithRootViewController:role];
8292 if (IsWildcat_) [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8293 [container_ presentModalViewController:nav animated:YES];
8296 - (void) setPackageController:(PackageController *)view {
8298 [view setPackage:nil];
8299 #if RecyclePackageViews
8300 if ([details_ count] < 3)
8301 [details_ addObject:view];
8306 - (PackageController *) _packageController {
8307 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8310 - (PackageController *) packageController {
8311 #if RecyclePackageViews
8312 PackageController *view;
8313 size_t count([details_ count]);
8316 view = [self _packageController];
8318 [details_ addObject:[self _packageController]];
8320 view = [[[details_ lastObject] retain] autorelease];
8321 [details_ removeLastObject];
8328 return [self _packageController];
8332 - (void) cancelAndClear:(bool)clear {
8333 @synchronized (self) {
8335 /* XXX: clear marks instead of reloading data */
8336 /*pkgCacheFile &cache([database_ cache]);
8337 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
8338 if (!cache[iterator].Keep()) cache->MarkKeep(iterator, false, false);
8344 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kManageTag] != -1 ? [self indexOfTabWithTag:kManageTag] : [self indexOfTabWithTag:kInstalledTag]] tabBarItem] setBadgeValue:nil];
8345 [queueDelegate_ queueStatusDidChange];*/
8350 [[[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kManageTag] != -1 ? [self indexOfTabWithTag:kManageTag] : [self indexOfTabWithTag:kInstalledTag]] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8351 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8353 [queueDelegate_ queueStatusDidChange];
8358 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8359 NSString *context([alert context]);
8361 if ([context isEqualToString:@"fixhalf"]) {
8362 if (button == [alert firstOtherButtonIndex]) {
8363 @synchronized (self) {
8364 for (Package *broken in broken_) {
8367 NSString *id = [broken id];
8368 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8369 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8370 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8371 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8377 } else if (button == [alert cancelButtonIndex]) {
8378 [broken_ removeAllObjects];
8382 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8383 } else if ([context isEqualToString:@"upgrade"]) {
8384 if (button == [alert firstOtherButtonIndex]) {
8385 @synchronized (self) {
8386 for (Package *essential in essential_)
8387 [essential install];
8392 } else if (button == [alert firstOtherButtonIndex] + 1) {
8394 } else if (button == [alert cancelButtonIndex]) {
8398 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8402 - (void) system:(NSString *)command { _pooled
8403 system([command UTF8String]);
8406 - (void) applicationWillSuspend {
8408 [super applicationWillSuspend];
8411 - (void) applicationSuspend:(__GSEvent *)event {
8412 // FIXME: This needs to be fixed, but we no longer have a progress_.
8413 // What's the best solution?
8414 if (hud_ == nil)// && ![progress_ isRunning])
8415 [super applicationSuspend:event];
8418 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8420 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8423 - (void) _setSuspended:(BOOL)value {
8425 [super _setSuspended:value];
8428 - (UIProgressHUD *) addProgressHUD {
8429 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8430 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8432 [window_ setUserInteractionEnabled:NO];
8434 [[container_ view] addSubview:hud];
8438 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8440 [hud removeFromSuperview];
8441 [window_ setUserInteractionEnabled:YES];
8444 - (UCViewController *) pageForPackage:(NSString *)name {
8445 if (Package *package = [database_ packageWithName:name]) {
8446 PackageController *view([self packageController]);
8447 [view setPackage:package];
8450 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8451 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8452 return [self _pageForURL:url withClass:[CYBrowserController class]];
8456 - (UCViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8460 NSString *href([url absoluteString]);
8461 if ([href hasPrefix:@"apptapp://package/"])
8462 return [self pageForPackage:[href substringFromIndex:18]];
8464 NSString *scheme([[url scheme] lowercaseString]);
8465 if (![scheme isEqualToString:@"cydia"])
8467 NSString *path([url absoluteString]);
8468 if ([path length] < 8)
8470 path = [path substringFromIndex:8];
8471 if (![path hasPrefix:@"/"])
8472 path = [@"/" stringByAppendingString:path];
8474 if ([path isEqualToString:@"/add-source"])
8475 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8476 else if ([path isEqualToString:@"/storage"])
8477 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8478 else if ([path isEqualToString:@"/sources"])
8479 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8480 else if ([path isEqualToString:@"/packages"])
8481 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8482 else if ([path hasPrefix:@"/url/"])
8483 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8484 else if ([path hasPrefix:@"/launch/"])
8485 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8486 else if ([path hasPrefix:@"/package-settings/"])
8487 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8488 else if ([path hasPrefix:@"/package-signature/"])
8489 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8490 else if ([path hasPrefix:@"/package/"])
8491 return [self pageForPackage:[path substringFromIndex:9]];
8492 else if ([path hasPrefix:@"/files/"]) {
8493 NSString *name = [path substringFromIndex:7];
8495 if (Package *package = [database_ packageWithName:name]) {
8496 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8497 [files setPackage:package];
8505 - (void) applicationOpenURL:(NSURL *)url {
8506 [super applicationOpenURL:url];
8508 if (UCViewController *page = [self pageForURL:url hasTag:&tag]) {
8509 [self setPage:page];
8511 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8515 - (void) applicationWillResignActive:(UIApplication *)application {
8516 // Stop refreshing if you get a phone call or lock the device.
8517 if ([container_ updating]) [container_ cancelUpdate];
8519 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8520 [super applicationWillResignActive:application];
8523 - (void) applicationDidFinishLaunching:(id)unused {
8524 [CYBrowserController _initialize];
8526 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8528 Font12_ = [[UIFont systemFontOfSize:12] retain];
8529 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8530 Font14_ = [[UIFont systemFontOfSize:14] retain];
8531 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8532 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8536 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8537 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8539 UIScreen *screen([UIScreen mainScreen]);
8541 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8542 [window_ orderFront:self];
8543 [window_ makeKey:self];
8544 [window_ setHidden:NO];
8546 database_ = [Database sharedInstance];
8549 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8550 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8551 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8552 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8553 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8554 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8555 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8556 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8557 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8560 [self setIdleTimerDisabled:YES];
8562 hud_ = [self addProgressHUD];
8563 [hud_ setText:@"Reorganizing:\n\nWill Automatically\nClose When Done"];
8564 [self setStatusBarShowsProgress:YES];
8566 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8568 [self setStatusBarShowsProgress:NO];
8569 [self removeProgressHUD:hud_];
8572 if (ExecFork() == 0) {
8573 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8574 perror("launchctl stop");
8582 NSMutableArray *items([NSMutableArray arrayWithObjects:
8583 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8584 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8585 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8586 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8590 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8591 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8593 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8596 NSMutableArray *controllers([NSMutableArray array]);
8598 for (UITabBarItem *item in items) {
8599 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8600 [controller setTabBarItem:item];
8601 [controllers addObject:controller];
8604 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8605 [tabbar_ setViewControllers:controllers];
8606 [tabbar_ setDelegate:self];
8607 [tabbar_ setSelectedIndex:0];
8609 container_ = [[CYContainer alloc] initWithDatabase:database_];
8610 [container_ setUpdateDelegate:self];
8611 [container_ setTabBarController:tabbar_];
8612 [window_ addSubview:[container_ view]];
8614 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8619 [self showSettings];
8623 [UIKeyboard initImplementationNow];
8627 #if RecyclePackageViews
8628 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8629 [details_ addObject:[self _packageController]];
8630 [details_ addObject:[self _packageController]];
8638 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8639 if (item != nil && IsWildcat_) {
8640 [sheet showFromBarButtonItem:item animated:YES];
8642 [sheet showInView:window_];
8649 id Alloc_(id self, SEL selector) {
8650 id object = alloc_(self, selector);
8651 lprintf("[%s]A-%p\n", self->isa->name, object);
8656 id Dealloc_(id self, SEL selector) {
8657 id object = dealloc_(self, selector);
8658 lprintf("[%s]D-%p\n", self->isa->name, object);
8662 Class $WebDefaultUIKitDelegate;
8664 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8665 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8666 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8667 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8670 static NSNumber *shouldPlayKeyboardSounds;
8674 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8676 case 1104: // Keyboard Button Clicked
8677 case 1105: // Keyboard Delete Repeated
8678 if (shouldPlayKeyboardSounds == nil) {
8679 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8680 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8683 if (![shouldPlayKeyboardSounds boolValue])
8687 _UIHardware$_playSystemSound$(self, _cmd, sound);
8691 int main(int argc, char *argv[]) { _pooled
8694 if (Class $UIDevice = objc_getClass("UIDevice")) {
8695 UIDevice *device([$UIDevice currentDevice]);
8696 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8700 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8702 /* Library Hacks {{{ */
8703 class_addMethod(objc_getClass("WebScriptObject"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &WebScriptObject$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8704 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8706 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8707 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8708 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8709 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8710 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8713 $UIHardware = objc_getClass("UIHardware");
8714 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8715 if (UIHardware$_playSystemSound$ != NULL) {
8716 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8717 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8720 /* Set Locale {{{ */
8721 Locale_ = CFLocaleCopyCurrent();
8722 Languages_ = [NSLocale preferredLanguages];
8723 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8724 //NSLog(@"%@", [Languages_ description]);
8727 if (Languages_ == nil || [Languages_ count] == 0)
8728 // XXX: consider just setting to C and then falling through?
8731 lang = [[Languages_ objectAtIndex:0] UTF8String];
8732 setenv("LANG", lang, true);
8735 //std::setlocale(LC_ALL, lang);
8736 NSLog(@"Setting Language: %s", lang);
8739 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8741 /* Parse Arguments {{{ */
8742 bool substrate(false);
8748 for (int argi(1); argi != argc; ++argi)
8749 if (strcmp(argv[argi], "--") == 0) {
8751 argv[argi] = argv[0];
8757 for (int argi(1); argi != arge; ++argi)
8758 if (strcmp(args[argi], "--substrate") == 0)
8761 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8765 App_ = [[NSBundle mainBundle] bundlePath];
8766 Home_ = NSHomeDirectory();
8772 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8773 alloc_ = alloc->method_imp;
8774 alloc->method_imp = (IMP) &Alloc_;*/
8776 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8777 dealloc_ = dealloc->method_imp;
8778 dealloc->method_imp = (IMP) &Dealloc_;*/
8780 /* System Information {{{ */
8784 size = sizeof(maxproc);
8785 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8786 perror("sysctlbyname(\"kern.maxproc\", ?)");
8787 else if (maxproc < 64) {
8789 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8790 perror("sysctlbyname(\"kern.maxproc\", #)");
8793 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8794 char *osversion = new char[size];
8795 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8796 perror("sysctlbyname(\"kern.osversion\", ?)");
8798 System_ = [NSString stringWithUTF8String:osversion];
8800 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8801 char *machine = new char[size];
8802 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8803 perror("sysctlbyname(\"hw.machine\", ?)");
8807 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8808 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8809 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8810 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8814 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8815 NSData *data((NSData *) ecid);
8816 size_t length([data length]);
8817 uint8_t bytes[length];
8818 [data getBytes:bytes];
8819 char string[length * 2 + 1];
8820 for (size_t i(0); i != length; ++i)
8821 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8822 ChipID_ = [NSString stringWithUTF8String:string];
8826 IOObjectRelease(service);
8830 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8832 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8833 Build_ = [system objectForKey:@"ProductBuildVersion"];
8834 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8835 Product_ = [info objectForKey:@"SafariProductVersion"];
8836 Safari_ = [info objectForKey:@"CFBundleVersion"];
8839 /* Load Database {{{ */
8841 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8843 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8846 if (Metadata_ == NULL)
8847 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8849 Settings_ = [Metadata_ objectForKey:@"Settings"];
8851 Packages_ = [Metadata_ objectForKey:@"Packages"];
8852 Sections_ = [Metadata_ objectForKey:@"Sections"];
8853 Sources_ = [Metadata_ objectForKey:@"Sources"];
8855 Token_ = [Metadata_ objectForKey:@"Token"];
8858 if (Settings_ != nil)
8859 Role_ = [Settings_ objectForKey:@"Role"];
8861 if (Packages_ == nil) {
8862 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8863 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8866 if (Sections_ == nil) {
8867 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8868 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8871 if (Sources_ == nil) {
8872 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8873 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8878 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8881 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8883 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
8884 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
8885 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8886 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8887 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8888 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8890 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
8892 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8893 unlink("/tmp/.cydia.fw");
8895 } else if (access("/User", F_OK) != 0 || version < 2) {
8898 system("/usr/libexec/cydia/firmware.sh");
8902 _assert([[NSFileManager defaultManager]
8903 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8904 withIntermediateDirectories:YES
8909 if (access("/tmp/cydia.chk", F_OK) == 0) {
8910 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8911 _assert(errno == ENOENT);
8912 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8913 _assert(errno == ENOENT);
8916 /* APT Initialization {{{ */
8917 _assert(pkgInitConfig(*_config));
8918 _assert(pkgInitSystem(*_config, _system));
8921 _config->Set("APT::Acquire::Translation", lang);
8922 _config->Set("Acquire::http::Timeout", 15);
8923 _config->Set("Acquire::http::MaxParallel", 3);
8925 /* Color Choices {{{ */
8926 space_ = CGColorSpaceCreateDeviceRGB();
8928 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8929 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8930 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8931 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8932 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8933 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8934 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8935 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8936 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8938 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8939 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8941 /* UIKit Configuration {{{ */
8942 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8943 if ($GSFontSetUseLegacyFontMetrics != NULL)
8944 $GSFontSetUseLegacyFontMetrics(YES);
8946 // XXX: I have a feeling this was important
8947 //UIKeyboardDisableAutomaticAppearance();
8950 Colon_ = UCLocalize("COLON_DELIMITED");
8951 Error_ = UCLocalize("ERROR");
8952 Warning_ = UCLocalize("WARNING");
8955 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
8957 CGColorSpaceRelease(space_);