1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2010 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "UICaboodle/UCPlatform.h"
45 #include "UICaboodle/UCLocalize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
111 #include <mach-o/nlist.h>
121 #include <ext/hash_map>
123 #include "UICaboodle/BrowserView.h"
125 #include "substrate.h"
132 #define _timestamp ({ \
134 gettimeofday(&tv, NULL); \
135 tv.tv_sec * 1000000 + tv.tv_usec; \
138 typedef std::vector<class ProfileTime *> TimeList;
148 ProfileTime(const char *name) :
152 times_.push_back(this);
155 void AddTime(uint64_t time) {
162 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
174 ProfileTimer(ProfileTime &time) :
181 time_.AddTime(_timestamp - start_);
186 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
188 std::cerr << "========" << std::endl;
191 #define _profile(name) { \
192 static ProfileTime name(#name); \
193 ProfileTimer _ ## name(name);
198 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
200 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
202 void NSLogPoint(const char *fix, const CGPoint &point) {
203 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
206 void NSLogRect(const char *fix, const CGRect &rect) {
207 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
210 static _finline NSString *CydiaURL(NSString *path) {
212 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
213 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
214 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
215 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
216 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
217 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
220 static _finline void UpdateExternalStatus(uint64_t newStatus) {
222 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
223 notify_set_state(notify_token, newStatus);
224 notify_cancel(notify_token);
226 notify_post("com.saurik.Cydia.status");
229 /* [NSObject yieldToSelector:(withObject:)] {{{*/
230 @interface NSObject (Cydia)
231 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
232 - (id) yieldToSelector:(SEL)selector;
235 @implementation NSObject (Cydia)
240 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
241 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
242 id object([[context objectAtIndex:1] nonretainedObjectValue]);
243 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
245 /* XXX: deal with exceptions */
246 id value([self performSelector:selector withObject:object]);
248 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
249 [context removeAllObjects];
250 if ([signature methodReturnLength] != 0 && value != nil)
251 [context addObject:value];
256 performSelectorOnMainThread:@selector(doNothing)
262 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
263 /*return [self performSelector:selector withObject:object];*/
265 volatile bool stopped(false);
267 NSMutableArray *context([NSMutableArray arrayWithObjects:
268 [NSValue valueWithPointer:selector],
269 [NSValue valueWithNonretainedObject:object],
270 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
273 NSThread *thread([[[NSThread alloc]
275 selector:@selector(_yieldToContext:)
281 NSRunLoop *loop([NSRunLoop currentRunLoop]);
282 NSDate *future([NSDate distantFuture]);
284 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
286 return [context count] == 0 ? nil : [context objectAtIndex:0];
289 - (id) yieldToSelector:(SEL)selector {
290 return [self yieldToSelector:selector withObject:nil];
296 /* Cydia Action Sheet {{{ */
297 @interface CYActionSheet : UIAlertView {
301 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
304 @implementation CYActionSheet
306 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
307 if ((self = [super init])) {
308 [self setTitle:title];
309 [self setDelegate:self];
310 for (NSString *button in buttons) [self addButtonWithTitle:button];
311 [self setCancelButtonIndex:index];
315 - (void) _updateFrameForDisplay {
316 [super _updateFrameForDisplay];
317 if ([self cancelButtonIndex] == -1) {
318 NSArray *buttons = [self buttons];
319 if ([buttons count]) {
320 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
321 for (UIThreePartButton *button in buttons)
322 [button setBackground:background forState:0];
327 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
328 button_ = buttonIndex + 1;
332 [self dismissWithClickedButtonIndex:-1 animated:YES];
335 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
336 [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 (1 && !ForRelease)
386 #define ShowInternals (0 && !ForRelease)
387 #define IgnoreInstall (0 && !ForRelease)
388 #define AlwaysReload (0 && !ForRelease)
392 #define _trace(args...)
397 #define _profile(name) {
400 #define PrintTimes() do {} while (false)
404 typedef uint32_t (*SKRadixFunction)(id, void *);
406 @interface NSMutableArray (Radix)
407 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
408 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
416 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
417 struct RadixItem_ *lhs(swap), *rhs(swap + count);
419 static const size_t width = 32;
420 static const size_t bits = 11;
421 static const size_t slots = 1 << bits;
422 static const size_t passes = (width + (bits - 1)) / bits;
424 size_t *hist(new size_t[slots]);
426 for (size_t pass(0); pass != passes; ++pass) {
427 memset(hist, 0, sizeof(size_t) * slots);
429 for (size_t i(0); i != count; ++i) {
430 uint32_t key(lhs[i].key);
432 key &= _not(uint32_t) >> width - bits;
437 for (size_t i(0); i != slots; ++i) {
438 size_t local(offset);
443 for (size_t i(0); i != count; ++i) {
444 uint32_t key(lhs[i].key);
446 key &= _not(uint32_t) >> width - bits;
447 rhs[hist[key]++] = lhs[i];
450 RadixItem_ *tmp(lhs);
457 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
458 for (size_t i(0); i != count; ++i)
459 [values addObject:[self objectAtIndex:lhs[i].index]];
460 [self setArray:values];
465 @implementation NSMutableArray (Radix)
467 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
468 size_t count([self count]);
473 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
474 [invocation setSelector:selector];
475 [invocation setArgument:&object atIndex:2];
477 /* XXX: this is an unsafe optimization of doomy hell */
478 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
479 _assert(method != NULL);
480 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
481 _assert(imp != NULL);
484 struct RadixItem_ *swap(new RadixItem_[count * 2]);
486 for (size_t i(0); i != count; ++i) {
487 RadixItem_ &item(swap[i]);
490 id object([self objectAtIndex:i]);
493 [invocation setTarget:object];
495 [invocation getReturnValue:&item.key];
497 item.key = imp(object, selector, object);
501 RadixSort_(self, count, swap);
504 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
505 size_t count([self count]);
506 struct RadixItem_ *swap(new RadixItem_[count * 2]);
508 for (size_t i(0); i != count; ++i) {
509 RadixItem_ &item(swap[i]);
512 id object([self objectAtIndex:i]);
513 item.key = function(object, argument);
516 RadixSort_(self, count, swap);
521 /* Insertion Sort {{{ */
523 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
524 const char *ptr = (const char *)list;
526 CFIndex half = count / 2;
527 const char *probe = ptr + elementSize * half;
528 CFComparisonResult cr = comparator(element, probe, context);
529 if (0 == cr) return (probe - (const char *)list) / elementSize;
530 ptr = (cr < 0) ? ptr : probe + elementSize;
531 count = (cr < 0) ? half : (half + (count & 1) - 1);
533 return (ptr - (const char *)list) / elementSize;
536 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
537 const char *ptr = (const char *)list;
539 CFIndex half = count / 2;
540 const char *probe = ptr + elementSize * half;
541 CFComparisonResult cr = comparator(element, probe, context);
542 if (0 == cr) return (probe - (const char *)list) / elementSize;
543 ptr = (cr < 0) ? ptr : probe + elementSize;
544 count = (cr < 0) ? half : (half + (count & 1) - 1);
546 return (ptr - (const char *)list) / elementSize;
549 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
550 if (range.length == 0)
552 const void **values(new const void *[range.length]);
553 CFArrayGetValues(array, range, values);
555 #if HistogramInsertionSort
556 uint32_t total(0), *offsets(new uint32_t[range.length]);
559 for (CFIndex index(1); index != range.length; ++index) {
560 const void *value(values[index]);
561 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
562 CFIndex correct(index);
563 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
566 if (correct != index) {
567 size_t offset(index - correct);
568 #if HistogramInsertionSort
572 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
574 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
575 values[correct] = value;
579 CFArrayReplaceValues(array, range, values, range.length);
582 #if HistogramInsertionSort
583 for (CFIndex index(0); index != range.length; ++index)
584 if (offsets[index] != 0)
585 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
586 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
593 /* Apple Bug Fixes {{{ */
594 @implementation UIWebDocumentView (Cydia)
596 - (void) _setScrollerOffset:(CGPoint)offset {
597 UIScroller *scroller([self _scroller]);
599 CGSize size([scroller contentSize]);
600 CGSize bounds([scroller bounds].size);
603 max.x = size.width - bounds.width;
604 max.y = size.height - bounds.height;
612 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
613 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
615 [scroller setOffset:offset];
621 @implementation WebScriptObject (NSFastEnumeration)
623 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(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;
638 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
639 size_t length([self length] - state->state);
642 else if (length > count)
644 for (size_t i(0); i != length; ++i)
645 objects[i] = [self item:state->state++];
646 state->itemsPtr = objects;
647 state->mutationsPtr = (unsigned long *) self;
651 /* Cydia NSString Additions {{{ */
652 @interface NSString (Cydia)
653 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
654 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
655 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
656 - (NSComparisonResult) compareByPath:(NSString *)other;
657 - (NSString *) stringByCachingURLWithCurrentCDN;
658 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
661 @implementation NSString (Cydia)
663 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
664 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
667 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
668 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
669 memcpy(data, bytes, length);
670 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
673 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
674 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
677 - (NSComparisonResult) compareByPath:(NSString *)other {
678 NSString *prefix = [self commonPrefixWithString:other options:0];
679 size_t length = [prefix length];
681 NSRange lrange = NSMakeRange(length, [self length] - length);
682 NSRange rrange = NSMakeRange(length, [other length] - length);
684 lrange = [self rangeOfString:@"/" options:0 range:lrange];
685 rrange = [other rangeOfString:@"/" options:0 range:rrange];
687 NSComparisonResult value;
689 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
690 value = NSOrderedSame;
691 else if (lrange.location == NSNotFound)
692 value = NSOrderedAscending;
693 else if (rrange.location == NSNotFound)
694 value = NSOrderedDescending;
696 value = NSOrderedSame;
698 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
699 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
700 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
701 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
703 NSComparisonResult result = [lpath compare:rpath];
704 return result == NSOrderedSame ? value : result;
707 - (NSString *) stringByCachingURLWithCurrentCDN {
709 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
710 withString:@"://cache.cydia.saurik.com/"
714 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
715 return [(id)CFURLCreateStringByAddingPercentEscapes(
720 kCFStringEncodingUTF8
727 /* C++ NSString Wrapper Cache {{{ */
734 _finline void clear_() {
735 if (cache_ != NULL) {
742 _finline bool empty() const {
746 _finline size_t size() const {
750 _finline char *data() const {
754 _finline void clear() {
759 _finline CYString() :
766 _finline ~CYString() {
770 void operator =(const CYString &rhs) {
774 if (rhs.cache_ == nil)
777 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
780 void set(apr_pool_t *pool, const char *data, size_t size) {
786 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
787 memcpy(temp, data, size);
794 _finline void set(apr_pool_t *pool, const char *data) {
795 set(pool, data, data == NULL ? 0 : strlen(data));
798 _finline void set(apr_pool_t *pool, const std::string &rhs) {
799 set(pool, rhs.data(), rhs.size());
802 bool operator ==(const CYString &rhs) const {
803 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
806 operator CFStringRef() {
807 if (cache_ == NULL) {
810 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
812 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
816 _finline operator id() {
817 return (NSString *) static_cast<CFStringRef>(*this);
821 /* C++ NSString Algorithm Adapters {{{ */
823 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
826 struct NSStringMapHash :
827 std::unary_function<NSString *, size_t>
829 _finline size_t operator ()(NSString *value) const {
830 return CFStringHashNSString((CFStringRef) value);
834 struct NSStringMapLess :
835 std::binary_function<NSString *, NSString *, bool>
837 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
838 return [lhs compare:rhs] == NSOrderedAscending;
842 struct NSStringMapEqual :
843 std::binary_function<NSString *, NSString *, bool>
845 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
846 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
847 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
848 //[lhs isEqualToString:rhs];
853 /* Perl-Compatible RegEx {{{ */
863 Pcre(const char *regex) :
868 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
871 lprintf("%d:%s\n", offset, error);
875 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
876 matches_ = new int[(capture_ + 1) * 3];
884 NSString *operator [](size_t match) {
885 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
888 bool operator ()(NSString *data) {
889 // XXX: length is for characters, not for bytes
890 return operator ()([data UTF8String], [data length]);
893 bool operator ()(const char *data, size_t size) {
895 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
899 /* Mime Addresses {{{ */
900 @interface Address : NSObject {
906 - (NSString *) address;
908 - (void) setAddress:(NSString *)address;
910 + (Address *) addressWithString:(NSString *)string;
911 - (Address *) initWithString:(NSString *)string;
914 @implementation Address
923 - (NSString *) name {
927 - (NSString *) address {
931 - (void) setAddress:(NSString *)address {
933 [address_ autorelease];
937 address_ = [address retain];
940 + (Address *) addressWithString:(NSString *)string {
941 return [[[Address alloc] initWithString:string] autorelease];
944 + (NSArray *) _attributeKeys {
945 return [NSArray arrayWithObjects:@"address", @"name", nil];
948 - (NSArray *) attributeKeys {
949 return [[self class] _attributeKeys];
952 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
953 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
956 - (Address *) initWithString:(NSString *)string {
957 if ((self = [super init]) != nil) {
958 const char *data = [string UTF8String];
959 size_t size = [string length];
961 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
963 if (address_r(data, size)) {
964 name_ = [address_r[1] retain];
965 address_ = [address_r[2] retain];
967 name_ = [string retain];
975 /* CoreGraphics Primitives {{{ */
986 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
989 Set(space, red, green, blue, alpha);
994 CGColorRelease(color_);
1001 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1003 float color[] = {red, green, blue, alpha};
1004 color_ = CGColorCreate(space, (CGFloat *) color);
1007 operator CGColorRef() {
1013 /* Random Global Variables {{{ */
1014 static const int PulseInterval_ = 50000;
1015 static const int ButtonBarWidth_ = 60;
1016 static const int ButtonBarHeight_ = 48;
1017 static const float KeyboardTime_ = 0.3f;
1020 static NSArray *Finishes_;
1022 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1023 #define NotifyConfig_ "/etc/notify.conf"
1025 static bool Queuing_;
1027 static CYColor Blue_;
1028 static CYColor Blueish_;
1029 static CYColor Black_;
1030 static CYColor Off_;
1031 static CYColor White_;
1032 static CYColor Gray_;
1033 static CYColor Green_;
1034 static CYColor Purple_;
1035 static CYColor Purplish_;
1037 static UIColor *InstallingColor_;
1038 static UIColor *RemovingColor_;
1040 static NSString *App_;
1041 static NSString *Home_;
1043 static BOOL Advanced_;
1044 static BOOL Ignored_;
1046 static UIFont *Font12_;
1047 static UIFont *Font12Bold_;
1048 static UIFont *Font14_;
1049 static UIFont *Font18Bold_;
1050 static UIFont *Font22Bold_;
1052 static const char *Machine_ = NULL;
1053 static NSString *System_ = nil;
1054 static NSString *SerialNumber_ = nil;
1055 static NSString *ChipID_ = nil;
1056 static NSString *Token_ = nil;
1057 static NSString *UniqueID_ = nil;
1058 static NSString *PLMN_ = nil;
1059 static NSString *Build_ = nil;
1060 static NSString *Product_ = nil;
1061 static NSString *Safari_ = nil;
1063 static CFLocaleRef Locale_;
1064 static NSArray *Languages_;
1065 static CGColorSpaceRef space_;
1067 static NSDictionary *SectionMap_;
1068 static NSMutableDictionary *Metadata_;
1069 static _transient NSMutableDictionary *Settings_;
1070 static _transient NSString *Role_;
1071 static _transient NSMutableDictionary *Packages_;
1072 static _transient NSMutableDictionary *Sections_;
1073 static _transient NSMutableDictionary *Sources_;
1074 static bool Changed_;
1075 static NSDate *now_;
1077 static bool IsWildcat_;
1080 /* Display Helpers {{{ */
1081 inline float Interpolate(float begin, float end, float fraction) {
1082 return (end - begin) * fraction + begin;
1085 /* XXX: localize this! */
1086 NSString *SizeString(double size) {
1087 bool negative = size < 0;
1092 while (size > 1024) {
1097 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1099 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1102 static _finline CFStringRef CFCString(const char *value) {
1103 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1106 const char *StripVersion_(const char *version) {
1107 const char *colon(strchr(version, ':'));
1109 version = colon + 1;
1113 CFStringRef StripVersion(const char *version) {
1114 const char *colon(strchr(version, ':'));
1116 version = colon + 1;
1117 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1119 return CFCString(version);
1122 NSString *LocalizeSection(NSString *section) {
1123 static Pcre title_r("^(.*?) \\((.*)\\)$");
1124 if (title_r(section)) {
1125 NSString *parent(title_r[1]);
1126 NSString *child(title_r[2]);
1128 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1129 LocalizeSection(parent),
1130 LocalizeSection(child)
1134 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1137 NSString *Simplify(NSString *title) {
1138 const char *data = [title UTF8String];
1139 size_t size = [title length];
1141 static Pcre square_r("^\\[(.*)\\]$");
1142 if (square_r(data, size))
1143 return Simplify(square_r[1]);
1145 static Pcre paren_r("^\\((.*)\\)$");
1146 if (paren_r(data, size))
1147 return Simplify(paren_r[1]);
1149 static Pcre title_r("^(.*?) \\((.*)\\)$");
1150 if (title_r(data, size))
1151 return Simplify(title_r[1]);
1157 NSString *GetLastUpdate() {
1158 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1161 return UCLocalize("NEVER_OR_UNKNOWN");
1163 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1164 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1166 CFRelease(formatter);
1168 return [(NSString *) formatted autorelease];
1171 bool isSectionVisible(NSString *section) {
1172 NSDictionary *metadata([Sections_ objectForKey:section]);
1173 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1174 return hidden == nil || ![hidden boolValue];
1179 /* Delegate Prototypes {{{ */
1183 @interface NSObject (ProgressDelegate)
1186 @protocol ProgressDelegate
1187 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1188 - (void) setProgressTitle:(NSString *)title;
1189 - (void) setProgressPercent:(float)percent;
1190 - (void) startProgress;
1191 - (void) addProgressOutput:(NSString *)output;
1192 - (bool) isCancelling:(size_t)received;
1195 @protocol ConfigurationDelegate
1196 - (void) repairWithSelector:(SEL)selector;
1197 - (void) setConfigurationData:(NSString *)data;
1200 @class PackageController;
1202 @protocol CydiaDelegate
1203 - (void) setPackageController:(PackageController *)view;
1204 - (void) clearPackage:(Package *)package;
1205 - (void) installPackage:(Package *)package;
1206 - (void) installPackages:(NSArray *)packages;
1207 - (void) removePackage:(Package *)package;
1208 - (void) beginUpdate;
1210 - (void) distUpgrade;
1212 - (void) updateData;
1214 - (void) showSettings;
1215 - (UIProgressHUD *) addProgressHUD;
1216 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1217 - (CYViewController *) pageForPackage:(NSString *)name;
1218 - (PackageController *) packageController;
1219 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1223 /* Status Delegation {{{ */
1225 public pkgAcquireStatus
1228 _transient NSObject<ProgressDelegate> *delegate_;
1236 void setDelegate(id delegate) {
1237 delegate_ = delegate;
1240 NSObject<ProgressDelegate> *getDelegate() const {
1244 virtual bool MediaChange(std::string media, std::string drive) {
1248 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1251 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1252 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1253 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1256 virtual void Done(pkgAcquire::ItemDesc &item) {
1259 virtual void Fail(pkgAcquire::ItemDesc &item) {
1261 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1262 item.Owner->Status == pkgAcquire::Item::StatDone
1266 std::string &error(item.Owner->ErrorText);
1270 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1271 NSArray *fields([description componentsSeparatedByString:@" "]);
1272 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1274 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1275 withObject:[NSArray arrayWithObjects:
1276 [NSString stringWithUTF8String:error.c_str()],
1283 virtual bool Pulse(pkgAcquire *Owner) {
1284 bool value = pkgAcquireStatus::Pulse(Owner);
1287 double(CurrentBytes + CurrentItems) /
1288 double(TotalBytes + TotalItems)
1291 [delegate_ setProgressPercent:percent];
1292 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1295 virtual void Start() {
1296 [delegate_ startProgress];
1299 virtual void Stop() {
1303 /* Progress Delegation {{{ */
1308 _transient id<ProgressDelegate> delegate_;
1312 virtual void Update() {
1313 /*if (abs(Percent - percent_) > 2)
1314 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1318 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1319 [delegate_ setProgressPercent:(Percent / 100)];*/
1329 void setDelegate(id delegate) {
1330 delegate_ = delegate;
1333 id getDelegate() const {
1337 virtual void Done() {
1339 //[delegate_ setProgressPercent:1];
1344 /* Database Interface {{{ */
1345 typedef std::map< unsigned long, _H<Source> > SourceMap;
1347 @interface Database : NSObject {
1353 pkgCacheFile cache_;
1354 pkgDepCache::Policy *policy_;
1355 pkgRecords *records_;
1356 pkgProblemResolver *resolver_;
1357 pkgAcquire *fetcher_;
1359 SPtr<pkgPackageManager> manager_;
1360 pkgSourceList *list_;
1363 NSMutableArray *packages_;
1365 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1374 + (Database *) sharedInstance;
1377 - (void) _readCydia:(NSNumber *)fd;
1378 - (void) _readStatus:(NSNumber *)fd;
1379 - (void) _readOutput:(NSNumber *)fd;
1383 - (Package *) packageWithName:(NSString *)name;
1385 - (pkgCacheFile &) cache;
1386 - (pkgDepCache::Policy *) policy;
1387 - (pkgRecords *) records;
1388 - (pkgProblemResolver *) resolver;
1389 - (pkgAcquire &) fetcher;
1390 - (pkgSourceList &) list;
1391 - (NSArray *) packages;
1392 - (NSArray *) sources;
1393 - (void) reloadData;
1401 - (void) setVisible;
1403 - (void) updateWithStatus:(Status &)status;
1405 - (void) setDelegate:(id)delegate;
1406 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1409 /* Delegate Helpers {{{ */
1410 @implementation NSObject (ProgressDelegate)
1412 - (void) _setProgressErrorPackage:(NSArray *)args {
1413 [self performSelector:@selector(setProgressError:forPackage:)
1414 withObject:[args objectAtIndex:0]
1415 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1419 - (void) _setProgressErrorTitle:(NSArray *)args {
1420 [self performSelector:@selector(setProgressError:withTitle:)
1421 withObject:[args objectAtIndex:0]
1422 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1426 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1427 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1428 withObject:[NSArray arrayWithObjects:error, title, nil]
1433 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1434 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1436 [self performSelector:@selector(setProgressError:withTitle:)
1438 withObject:(package == nil ? id : [package name])
1445 /* Source Class {{{ */
1446 @interface Source : NSObject {
1447 CYString depiction_;
1448 CYString description_;
1454 CYString distribution_;
1459 NSString *authority_;
1461 CYString defaultIcon_;
1463 NSDictionary *record_;
1467 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1469 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1471 - (NSString *) depictionForPackage:(NSString *)package;
1472 - (NSString *) supportForPackage:(NSString *)package;
1474 - (NSDictionary *) record;
1478 - (NSString *) distribution;
1479 - (NSString *) type;
1481 - (NSString *) host;
1483 - (NSString *) name;
1484 - (NSString *) description;
1485 - (NSString *) label;
1486 - (NSString *) origin;
1487 - (NSString *) version;
1489 - (NSString *) defaultIcon;
1493 @implementation Source
1497 distribution_.clear();
1500 description_.clear();
1506 defaultIcon_.clear();
1508 if (record_ != nil) {
1518 if (authority_ != nil) {
1519 [authority_ release];
1529 + (NSArray *) _attributeKeys {
1530 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1533 - (NSArray *) attributeKeys {
1534 return [[self class] _attributeKeys];
1537 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1538 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1541 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1544 trusted_ = index->IsTrusted();
1546 uri_.set(pool, index->GetURI());
1547 distribution_.set(pool, index->GetDist());
1548 type_.set(pool, index->GetType());
1550 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1551 if (dindex != NULL) {
1553 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1556 pkgTagFile tags(&fd);
1558 pkgTagSection section;
1565 {"default-icon", &defaultIcon_},
1566 {"depiction", &depiction_},
1567 {"description", &description_},
1569 {"origin", &origin_},
1570 {"support", &support_},
1571 {"version", &version_},
1574 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1575 const char *start, *end;
1577 if (section.Find(names[i].name_, start, end)) {
1578 CYString &value(*names[i].value_);
1579 value.set(pool, start, end - start);
1585 record_ = [Sources_ objectForKey:[self key]];
1587 record_ = [record_ retain];
1589 NSURL *url([NSURL URLWithString:uri_]);
1593 host_ = [[host_ lowercaseString] retain];
1598 authority_ = [url path];
1600 if (authority_ != nil)
1601 authority_ = [authority_ retain];
1604 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1605 if ((self = [super init]) != nil) {
1606 [self setMetaIndex:index inPool:pool];
1610 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1611 NSDictionary *lhr = [self record];
1612 NSDictionary *rhr = [source record];
1615 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1617 NSString *lhs = [self name];
1618 NSString *rhs = [source name];
1620 if ([lhs length] != 0 && [rhs length] != 0) {
1621 unichar lhc = [lhs characterAtIndex:0];
1622 unichar rhc = [rhs characterAtIndex:0];
1624 if (isalpha(lhc) && !isalpha(rhc))
1625 return NSOrderedAscending;
1626 else if (!isalpha(lhc) && isalpha(rhc))
1627 return NSOrderedDescending;
1630 return [lhs compare:rhs options:LaxCompareOptions_];
1633 - (NSString *) depictionForPackage:(NSString *)package {
1634 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1637 - (NSString *) supportForPackage:(NSString *)package {
1638 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1641 - (NSDictionary *) record {
1649 - (NSString *) uri {
1653 - (NSString *) distribution {
1654 return distribution_;
1657 - (NSString *) type {
1661 - (NSString *) key {
1662 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1665 - (NSString *) host {
1669 - (NSString *) name {
1670 return origin_.empty() ? authority_ : origin_;
1673 - (NSString *) description {
1674 return description_;
1677 - (NSString *) label {
1678 return label_.empty() ? authority_ : label_;
1681 - (NSString *) origin {
1685 - (NSString *) version {
1689 - (NSString *) defaultIcon {
1690 return defaultIcon_;
1695 /* Relationship Class {{{ */
1696 @interface Relationship : NSObject {
1701 - (NSString *) type;
1703 - (NSString *) name;
1707 @implementation Relationship
1715 - (NSString *) type {
1723 - (NSString *) name {
1730 /* Package Class {{{ */
1731 @interface Package : NSObject {
1735 pkgCache::VerIterator version_;
1736 pkgCache::PkgIterator iterator_;
1737 _transient Database *database_;
1738 pkgCache::VerFileIterator file_;
1745 NSString *section$_;
1752 CYString installed_;
1758 CYString depiction_;
1769 NSMutableArray *tags_;
1772 NSArray *relationships_;
1774 NSMutableDictionary *metadata_;
1775 _transient NSDate *firstSeen_;
1776 _transient NSDate *lastSeen_;
1780 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1781 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1783 - (pkgCache::PkgIterator) iterator;
1786 - (NSString *) section;
1787 - (NSString *) simpleSection;
1789 - (NSString *) longSection;
1790 - (NSString *) shortSection;
1794 - (Address *) maintainer;
1796 - (NSString *) longDescription;
1797 - (NSString *) shortDescription;
1800 - (NSMutableDictionary *) metadata;
1802 - (BOOL) subscribed;
1805 - (NSString *) latest;
1806 - (NSString *) installed;
1807 - (BOOL) uninstalled;
1810 - (BOOL) upgradableAndEssential:(BOOL)essential;
1813 - (BOOL) unfiltered;
1817 - (BOOL) halfConfigured;
1818 - (BOOL) halfInstalled;
1820 - (NSString *) mode;
1822 - (void) setVisible;
1825 - (NSString *) name;
1827 - (NSString *) homepage;
1828 - (NSString *) depiction;
1829 - (Address *) author;
1831 - (NSString *) support;
1833 - (NSArray *) files;
1834 - (NSArray *) relationships;
1835 - (NSArray *) warnings;
1836 - (NSArray *) applications;
1838 - (Source *) source;
1839 - (NSString *) role;
1841 - (BOOL) matches:(NSString *)text;
1843 - (bool) hasSupportingRole;
1844 - (BOOL) hasTag:(NSString *)tag;
1845 - (NSString *) primaryPurpose;
1846 - (NSArray *) purposes;
1847 - (bool) isCommercial;
1849 - (CYString &) cyname;
1851 - (uint32_t) compareBySection:(NSArray *)sections;
1853 - (uint32_t) compareForChanges;
1858 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1859 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1860 - (bool) isInstalledAndVisible:(NSNumber *)number;
1861 - (bool) isVisibleInSection:(NSString *)section;
1862 - (bool) isVisibleInSource:(Source *)source;
1866 uint32_t PackageChangesRadix(Package *self, void *) {
1871 uint32_t timestamp : 30;
1872 uint32_t ignored : 1;
1873 uint32_t upgradable : 1;
1877 bool upgradable([self upgradableAndEssential:YES]);
1878 value.bits.upgradable = upgradable ? 1 : 0;
1881 value.bits.timestamp = 0;
1882 value.bits.ignored = [self ignored] ? 0 : 1;
1883 value.bits.upgradable = 1;
1885 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1886 value.bits.ignored = 0;
1887 value.bits.upgradable = 0;
1890 return _not(uint32_t) - value.key;
1893 _finline static void Stifle(uint8_t &value) {
1896 uint32_t PackagePrefixRadix(Package *self, void *context) {
1897 size_t offset(reinterpret_cast<size_t>(context));
1898 CYString &name([self cyname]);
1900 size_t size(name.size());
1903 char *text(name.data());
1906 if (!isdigit(text[0]))
1910 while (size != digits && isdigit(text[digits]))
1920 if (offset == 0 && zeros != 0) {
1921 memset(data, '0', zeros);
1922 memcpy(data + zeros, text, 4 - zeros);
1924 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1925 if (size <= offset - zeros)
1928 text += offset - zeros;
1929 size -= offset - zeros;
1932 memcpy(data, text, 4);
1934 memcpy(data, text, size);
1935 memset(data + size, 0, 4 - size);
1938 for (size_t i(0); i != 4; ++i)
1939 if (isalpha(data[i]))
1944 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1946 /* XXX: ntohl may be more honest */
1947 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1950 CYString &(*PackageName)(Package *self, SEL sel);
1952 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1953 _profile(PackageNameCompare)
1954 CYString &lhi(PackageName(lhs, @selector(cyname)));
1955 CYString &rhi(PackageName(rhs, @selector(cyname)));
1956 CFStringRef lhn(lhi), rhn(rhi);
1959 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1960 else if (rhn == NULL)
1961 return NSOrderedDescending;
1963 _profile(PackageNameCompare$NumbersLast)
1964 if (!lhi.empty() && !rhi.empty()) {
1965 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1966 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1967 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1968 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1969 return lha ? NSOrderedAscending : NSOrderedDescending;
1973 CFIndex length = CFStringGetLength(lhn);
1975 _profile(PackageNameCompare$Compare)
1976 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1981 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1982 return PackageNameCompare(*lhs, *rhs, context);
1985 struct PackageNameOrdering :
1986 std::binary_function<Package *, Package *, bool>
1988 _finline bool operator ()(Package *lhs, Package *rhs) const {
1989 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1993 @implementation Package
1995 - (NSString *) description {
1996 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2002 if (section$_ != nil)
2003 [section$_ release];
2008 if (sponsor$_ != nil)
2009 [sponsor$_ release];
2010 if (author$_ != nil)
2017 if (relationships_ != nil)
2018 [relationships_ release];
2019 if (metadata_ != nil)
2020 [metadata_ release];
2025 + (NSString *) webScriptNameForSelector:(SEL)selector {
2026 if (selector == @selector(hasTag:))
2032 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2033 return [self webScriptNameForSelector:selector] == nil;
2036 + (NSArray *) _attributeKeys {
2037 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];
2040 - (NSArray *) attributeKeys {
2041 return [[self class] _attributeKeys];
2044 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2045 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2055 _profile(Package$parse)
2056 pkgRecords::Parser *parser;
2058 _profile(Package$parse$Lookup)
2059 parser = &[database_ records]->Lookup(file_);
2064 _profile(Package$parse$Find)
2070 {"depiction", &depiction_},
2071 {"homepage", &homepage_},
2072 {"website", &website},
2074 {"support", &support_},
2075 {"sponsor", &sponsor_},
2076 {"author", &author_},
2079 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2080 const char *start, *end;
2082 if (parser->Find(names[i].name_, start, end)) {
2083 CYString &value(*names[i].value_);
2084 _profile(Package$parse$Value)
2085 value.set(pool_, start, end - start);
2091 _profile(Package$parse$Tagline)
2092 const char *start, *end;
2093 if (parser->ShortDesc(start, end)) {
2094 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2097 while (stop != start && stop[-1] == '\r')
2099 tagline_.set(pool_, start, stop - start);
2103 _profile(Package$parse$Retain)
2104 if (homepage_.empty())
2105 homepage_ = website;
2106 if (homepage_ == depiction_)
2112 - (void) setVisible {
2113 visible_ = required_ && [self unfiltered];
2116 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2117 if ((self = [super init]) != nil) {
2118 _profile(Package$initWithVersion)
2119 @synchronized (database) {
2120 era_ = [database era];
2124 iterator_ = version.ParentPkg();
2125 database_ = database;
2127 _profile(Package$initWithVersion$Latest)
2128 latest_ = (NSString *) StripVersion(version_.VerStr());
2131 pkgCache::VerIterator current;
2132 _profile(Package$initWithVersion$Versions)
2133 current = iterator_.CurrentVer();
2135 installed_.set(pool_, StripVersion_(current.VerStr()));
2137 if (!version_.end())
2138 file_ = version_.FileList();
2140 pkgCache &cache([database_ cache]);
2141 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2145 _profile(Package$initWithVersion$Name)
2146 id_.set(pool_, iterator_.Name());
2147 name_.set(pool, iterator_.Display());
2151 _profile(Package$initWithVersion$Source)
2152 source_ = [database_ getSource:file_.File()];
2161 _profile(Package$initWithVersion$Tags)
2162 pkgCache::TagIterator tag(iterator_.TagList());
2164 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2166 const char *name(tag.Name());
2167 [tags_ addObject:(NSString *)CFCString(name)];
2168 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2169 role_ = (NSString *) CFCString(name + 6);
2170 if (required_ && strncmp(name, "require::", 9) == 0 && (
2175 } while (!tag.end());
2179 bool changed(false);
2180 NSString *key([static_cast<id>(id_) lowercaseString]);
2182 _profile(Package$initWithVersion$Metadata)
2183 metadata_ = [Packages_ objectForKey:key];
2185 if (metadata_ == nil) {
2188 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2189 firstSeen_, @"FirstSeen",
2190 latest_, @"LastVersion",
2195 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2196 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2198 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2199 subscribed_ = [subscribed boolValue];
2201 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2203 if (firstSeen_ == nil) {
2204 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2205 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2209 if (version == nil) {
2210 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2212 } else if (![version isEqualToString:latest_]) {
2213 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2215 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2220 metadata_ = [metadata_ retain];
2223 [Packages_ setObject:metadata_ forKey:key];
2228 _profile(Package$initWithVersion$Section)
2229 section_.set(pool_, iterator_.Section());
2232 obsolete_ = [self hasTag:@"cydia::obsolete"];
2233 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2235 } _end } return self;
2238 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2239 @synchronized ([Database class]) {
2240 pkgCache::VerIterator version;
2242 _profile(Package$packageWithIterator$GetCandidateVer)
2243 version = [database policy]->GetCandidateVer(iterator);
2249 return [[[Package alloc]
2250 initWithVersion:version
2257 - (pkgCache::PkgIterator) iterator {
2261 - (NSString *) section {
2262 if (section$_ == nil) {
2263 if (section_.empty())
2266 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2267 NSString *name(section_);
2270 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2271 if (NSString *rename = [value objectForKey:@"Rename"]) {
2276 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2280 - (NSString *) simpleSection {
2281 if (NSString *section = [self section])
2282 return Simplify(section);
2287 - (NSString *) longSection {
2288 return LocalizeSection([self section]);
2291 - (NSString *) shortSection {
2292 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2295 - (NSString *) uri {
2298 pkgIndexFile *index;
2299 pkgCache::PkgFileIterator file(file_.File());
2300 if (![database_ list].FindIndex(file, index))
2302 return [NSString stringWithUTF8String:iterator_->Path];
2303 //return [NSString stringWithUTF8String:file.Site()];
2304 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2308 - (Address *) maintainer {
2311 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2312 const std::string &maintainer(parser->Maintainer());
2313 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2317 return version_.end() ? 0 : version_->InstalledSize;
2320 - (NSString *) longDescription {
2323 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2324 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2326 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2327 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2328 if ([lines count] < 2)
2331 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2332 for (size_t i(1), e([lines count]); i != e; ++i) {
2333 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2334 [trimmed addObject:trim];
2337 return [trimmed componentsJoinedByString:@"\n"];
2340 - (NSString *) shortDescription {
2345 _profile(Package$index)
2346 CFStringRef name((CFStringRef) [self name]);
2347 if (CFStringGetLength(name) == 0)
2349 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2350 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2352 return toupper(character);
2356 - (NSMutableDictionary *) metadata {
2361 if (subscribed_ && lastSeen_ != nil)
2366 - (BOOL) subscribed {
2371 NSDictionary *metadata([self metadata]);
2372 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2373 return [ignored boolValue];
2378 - (NSString *) latest {
2382 - (NSString *) installed {
2386 - (BOOL) uninstalled {
2387 return installed_.empty();
2391 return !version_.end();
2394 - (BOOL) upgradableAndEssential:(BOOL)essential {
2395 _profile(Package$upgradableAndEssential)
2396 pkgCache::VerIterator current(iterator_.CurrentVer());
2398 return essential && essential_ && visible_;
2400 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2404 - (BOOL) essential {
2409 return [database_ cache][iterator_].InstBroken();
2412 - (BOOL) unfiltered {
2413 NSString *section([self section]);
2414 return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
2422 unsigned char current(iterator_->CurrentState);
2423 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2426 - (BOOL) halfConfigured {
2427 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2430 - (BOOL) halfInstalled {
2431 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2435 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2436 return state.Mode != pkgDepCache::ModeKeep;
2439 - (NSString *) mode {
2440 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2442 switch (state.Mode) {
2443 case pkgDepCache::ModeDelete:
2444 if ((state.iFlags & pkgDepCache::Purge) != 0)
2448 case pkgDepCache::ModeKeep:
2449 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2450 return @"REINSTALL";
2451 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2455 case pkgDepCache::ModeInstall:
2456 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2457 return @"REINSTALL";
2458 else*/ switch (state.Status) {
2460 return @"DOWNGRADE";
2466 return @"NEW_INSTALL";
2477 - (NSString *) name {
2478 return name_.empty() ? id_ : name_;
2481 - (UIImage *) icon {
2482 NSString *section = [self simpleSection];
2486 if ([static_cast<id>(icon_) hasPrefix:@"file:///"])
2487 // XXX: correct escaping
2488 icon = [UIImage imageAtPath:[static_cast<id>(icon_) substringFromIndex:7]];
2489 if (icon == nil) if (section != nil)
2490 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2491 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2492 if ([dicon hasPrefix:@"file:///"])
2493 // XXX: correct escaping
2494 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2496 icon = [UIImage applicationImageNamed:@"unknown.png"];
2500 - (NSString *) homepage {
2504 - (NSString *) depiction {
2505 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2508 - (Address *) sponsor {
2509 if (sponsor$_ == nil) {
2510 if (sponsor_.empty())
2512 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2516 - (Address *) author {
2517 if (author$_ == nil) {
2518 if (author_.empty())
2520 author$_ = [[Address addressWithString:author_] retain];
2524 - (NSString *) support {
2525 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2528 - (NSArray *) files {
2529 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2530 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2533 fin.open([path UTF8String]);
2538 while (std::getline(fin, line))
2539 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2544 - (NSArray *) relationships {
2545 return relationships_;
2548 - (NSArray *) warnings {
2549 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2550 const char *name(iterator_.Name());
2552 size_t length(strlen(name));
2553 if (length < 2) invalid:
2554 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2555 else for (size_t i(0); i != length; ++i)
2557 /* XXX: technically this is not allowed */
2558 (name[i] < 'A' || name[i] > 'Z') &&
2559 (name[i] < 'a' || name[i] > 'z') &&
2560 (name[i] < '0' || name[i] > '9') &&
2561 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2564 if (strcmp(name, "cydia") != 0) {
2567 bool _private = false;
2570 bool repository = [[self section] isEqualToString:@"Repositories"];
2572 if (NSArray *files = [self files])
2573 for (NSString *file in files)
2574 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2576 else if (!user && [file isEqualToString:@"/User"])
2578 else if (!_private && [file isEqualToString:@"/private"])
2580 else if (!stash && [file isEqualToString:@"/var/stash"])
2583 /* XXX: this is not sensitive enough. only some folders are valid. */
2584 if (cydia && !repository)
2585 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2587 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2589 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2591 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2594 return [warnings count] == 0 ? nil : warnings;
2597 - (NSArray *) applications {
2598 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2600 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2602 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2603 if (NSArray *files = [self files])
2604 for (NSString *file in files)
2605 if (application_r(file)) {
2606 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2607 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2608 if ([id isEqualToString:me])
2611 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2613 display = application_r[1];
2615 NSString *bundle([file stringByDeletingLastPathComponent]);
2616 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2617 if (icon == nil || [icon length] == 0)
2619 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2621 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2622 [applications addObject:application];
2624 [application addObject:id];
2625 [application addObject:display];
2626 [application addObject:url];
2629 return [applications count] == 0 ? nil : applications;
2632 - (Source *) source {
2634 @synchronized (database_) {
2635 if ([database_ era] != era_ || file_.end())
2638 source_ = [database_ getSource:file_.File()];
2650 - (NSString *) role {
2654 - (BOOL) matches:(NSString *)text {
2660 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2661 if (range.location != NSNotFound)
2664 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2665 if (range.location != NSNotFound)
2668 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2669 if (range.location != NSNotFound)
2675 - (bool) hasSupportingRole {
2678 if ([role_ isEqualToString:@"enduser"])
2680 if ([Role_ isEqualToString:@"User"])
2682 if ([role_ isEqualToString:@"hacker"])
2684 if ([Role_ isEqualToString:@"Hacker"])
2686 if ([role_ isEqualToString:@"developer"])
2688 if ([Role_ isEqualToString:@"Developer"])
2693 - (BOOL) hasTag:(NSString *)tag {
2694 return tags_ == nil ? NO : [tags_ containsObject:tag];
2697 - (NSString *) primaryPurpose {
2698 for (NSString *tag in tags_)
2699 if ([tag hasPrefix:@"purpose::"])
2700 return [tag substringFromIndex:9];
2704 - (NSArray *) purposes {
2705 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2706 for (NSString *tag in tags_)
2707 if ([tag hasPrefix:@"purpose::"])
2708 [purposes addObject:[tag substringFromIndex:9]];
2709 return [purposes count] == 0 ? nil : purposes;
2712 - (bool) isCommercial {
2713 return [self hasTag:@"cydia::commercial"];
2716 - (CYString &) cyname {
2717 return name_.empty() ? id_ : name_;
2720 - (uint32_t) compareBySection:(NSArray *)sections {
2721 NSString *section([self section]);
2722 for (size_t i(0), e([sections count]); i != e; ++i) {
2723 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2727 return _not(uint32_t);
2730 - (uint32_t) compareForChanges {
2735 uint32_t timestamp : 30;
2736 uint32_t ignored : 1;
2737 uint32_t upgradable : 1;
2741 bool upgradable([self upgradableAndEssential:YES]);
2742 value.bits.upgradable = upgradable ? 1 : 0;
2745 value.bits.timestamp = 0;
2746 value.bits.ignored = [self ignored] ? 0 : 1;
2747 value.bits.upgradable = 1;
2749 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2750 value.bits.ignored = 0;
2751 value.bits.upgradable = 0;
2754 return _not(uint32_t) - value.key;
2758 pkgProblemResolver *resolver = [database_ resolver];
2759 resolver->Clear(iterator_);
2760 resolver->Protect(iterator_);
2764 pkgProblemResolver *resolver = [database_ resolver];
2765 resolver->Clear(iterator_);
2766 resolver->Protect(iterator_);
2767 pkgCacheFile &cache([database_ cache]);
2768 cache->MarkInstall(iterator_, false);
2769 pkgDepCache::StateCache &state((*cache)[iterator_]);
2770 if (!state.Install())
2771 cache->SetReInstall(iterator_, true);
2775 pkgProblemResolver *resolver = [database_ resolver];
2776 resolver->Clear(iterator_);
2777 resolver->Protect(iterator_);
2778 resolver->Remove(iterator_);
2779 [database_ cache]->MarkDelete(iterator_, true);
2782 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2783 _profile(Package$isUnfilteredAndSearchedForBy)
2786 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2787 value &= [self unfiltered];
2790 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2791 value &= [self matches:search];
2798 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2799 if ([search length] == 0)
2802 _profile(Package$isUnfilteredAndSelectedForBy)
2805 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2806 value &= [self unfiltered];
2809 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2810 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2817 - (bool) isInstalledAndVisible:(NSNumber *)number {
2818 return (![number boolValue] || [self visible]) && ![self uninstalled];
2821 - (bool) isVisibleInSection:(NSString *)name {
2822 NSString *section = [self section];
2827 section == nil && [name length] == 0 ||
2828 [name isEqualToString:section]
2832 - (bool) isVisibleInSource:(Source *)source {
2833 return [self source] == source && [self visible];
2838 /* Section Class {{{ */
2839 @interface Section : NSObject {
2844 NSString *localized_;
2847 - (NSComparisonResult) compareByLocalized:(Section *)section;
2848 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2849 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2850 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2851 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2852 - (NSString *) name;
2859 - (void) addToCount;
2861 - (void) setCount:(size_t)count;
2862 - (NSString *) localized;
2866 @implementation Section
2870 if (localized_ != nil)
2871 [localized_ release];
2875 - (NSComparisonResult) compareByLocalized:(Section *)section {
2876 NSString *lhs(localized_);
2877 NSString *rhs([section localized]);
2879 /*if ([lhs length] != 0 && [rhs length] != 0) {
2880 unichar lhc = [lhs characterAtIndex:0];
2881 unichar rhc = [rhs characterAtIndex:0];
2883 if (isalpha(lhc) && !isalpha(rhc))
2884 return NSOrderedAscending;
2885 else if (!isalpha(lhc) && isalpha(rhc))
2886 return NSOrderedDescending;
2889 return [lhs compare:rhs options:LaxCompareOptions_];
2892 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2893 if ((self = [self initWithName:name localize:NO]) != nil) {
2894 if (localized != nil)
2895 localized_ = [localized retain];
2899 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2900 return [self initWithName:name row:0 localize:localize];
2903 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2904 if ((self = [super init]) != nil) {
2905 name_ = [name retain];
2909 localized_ = [LocalizeSection(name_) retain];
2913 /* XXX: localize the index thingees */
2914 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2915 if ((self = [super init]) != nil) {
2916 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2922 - (NSString *) name {
2942 - (void) addToCount {
2946 - (void) setCount:(size_t)count {
2950 - (NSString *) localized {
2957 static NSString *Colon_;
2958 static NSString *Error_;
2959 static NSString *Warning_;
2961 /* Database Implementation {{{ */
2962 @implementation Database
2964 + (Database *) sharedInstance {
2965 static Database *instance;
2966 if (instance == nil)
2967 instance = [[Database alloc] init];
2977 NSRecycleZone(zone_);
2978 // XXX: malloc_destroy_zone(zone_);
2979 apr_pool_destroy(pool_);
2983 - (void) _readCydia:(NSNumber *)fd { _pooled
2984 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2985 std::istream is(&ib);
2988 static Pcre finish_r("^finish:([^:]*)$");
2990 while (std::getline(is, line)) {
2991 const char *data(line.c_str());
2992 size_t size = line.size();
2993 lprintf("C:%s\n", data);
2995 if (finish_r(data, size)) {
2996 NSString *finish = finish_r[1];
2997 int index = [Finishes_ indexOfObject:finish];
2998 if (index != INT_MAX && index > Finish_)
3006 - (void) _readStatus:(NSNumber *)fd { _pooled
3007 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3008 std::istream is(&ib);
3011 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3012 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3014 while (std::getline(is, line)) {
3015 const char *data(line.c_str());
3016 size_t size(line.size());
3017 lprintf("S:%s\n", data);
3019 if (conffile_r(data, size)) {
3020 [delegate_ setConfigurationData:conffile_r[1]];
3021 } else if (strncmp(data, "status: ", 8) == 0) {
3022 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3023 [delegate_ setProgressTitle:string];
3024 } else if (pmstatus_r(data, size)) {
3025 std::string type([pmstatus_r[1] UTF8String]);
3026 NSString *id = pmstatus_r[2];
3028 float percent([pmstatus_r[3] floatValue]);
3029 [delegate_ setProgressPercent:(percent / 100)];
3031 NSString *string = pmstatus_r[4];
3033 if (type == "pmerror")
3034 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3035 withObject:[NSArray arrayWithObjects:string, id, nil]
3038 else if (type == "pmstatus") {
3039 [delegate_ setProgressTitle:string];
3040 } else if (type == "pmconffile")
3041 [delegate_ setConfigurationData:string];
3043 lprintf("E:unknown pmstatus\n");
3045 lprintf("E:unknown status\n");
3051 - (void) _readOutput:(NSNumber *)fd { _pooled
3052 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3053 std::istream is(&ib);
3056 while (std::getline(is, line)) {
3057 lprintf("O:%s\n", line.c_str());
3058 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3068 - (Package *) packageWithName:(NSString *)name {
3069 @synchronized ([Database class]) {
3070 if (static_cast<pkgDepCache *>(cache_) == NULL)
3072 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3073 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3077 if ((self = [super init]) != nil) {
3084 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3085 apr_pool_create(&pool_, NULL);
3087 packages_ = [[NSMutableArray alloc] init];
3091 _assert(pipe(fds) != -1);
3094 _config->Set("APT::Keep-Fds::", cydiafd_);
3095 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3098 detachNewThreadSelector:@selector(_readCydia:)
3100 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3103 _assert(pipe(fds) != -1);
3107 detachNewThreadSelector:@selector(_readStatus:)
3109 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3112 _assert(pipe(fds) != -1);
3113 _assert(dup2(fds[0], 0) != -1);
3114 _assert(close(fds[0]) != -1);
3116 input_ = fdopen(fds[1], "a");
3118 _assert(pipe(fds) != -1);
3119 _assert(dup2(fds[1], 1) != -1);
3120 _assert(close(fds[1]) != -1);
3123 detachNewThreadSelector:@selector(_readOutput:)
3125 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3130 - (pkgCacheFile &) cache {
3134 - (pkgDepCache::Policy *) policy {
3138 - (pkgRecords *) records {
3142 - (pkgProblemResolver *) resolver {
3146 - (pkgAcquire &) fetcher {
3150 - (pkgSourceList &) list {
3154 - (NSArray *) packages {
3158 - (NSArray *) sources {
3159 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3160 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3161 [sources addObject:i->second];
3165 - (NSArray *) issues {
3166 if (cache_->BrokenCount() == 0)
3169 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3171 for (Package *package in packages_) {
3172 if (![package broken])
3174 pkgCache::PkgIterator pkg([package iterator]);
3176 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3177 [entry addObject:[package name]];
3178 [issues addObject:entry];
3180 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3184 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3185 pkgCache::DepIterator start;
3186 pkgCache::DepIterator end;
3187 dep.GlobOr(start, end); // ++dep
3189 if (!cache_->IsImportantDep(end))
3191 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3194 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3195 [entry addObject:failure];
3196 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3198 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3199 if (Package *package = [self packageWithName:name])
3200 name = [package name];
3201 [failure addObject:name];
3203 pkgCache::PkgIterator target(start.TargetPkg());
3204 if (target->ProvidesList != 0)
3205 [failure addObject:@"?"];
3207 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3209 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3210 else if (!cache_[target].CandidateVerIter(cache_).end())
3211 [failure addObject:@"-"];
3212 else if (target->ProvidesList == 0)
3213 [failure addObject:@"!"];
3215 [failure addObject:@"%"];
3219 if (start.TargetVer() != 0)
3220 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3231 - (bool) popErrorWithTitle:(NSString *)title {
3233 std::string message;
3235 while (!_error->empty()) {
3237 bool warning(!_error->PopMessage(error));
3241 size_t size(error.size());
3242 if (size == 0 || error[size - 1] != '\n')
3244 error.resize(size - 1);
3246 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3248 if (!message.empty())
3253 if (fatal && !message.empty())
3254 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3259 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3260 return [self popErrorWithTitle:title] || !success;
3263 - (void) reloadData { _pooled
3264 @synchronized ([Database class]) {
3265 @synchronized (self) {
3269 [packages_ removeAllObjects];
3295 apr_pool_clear(pool_);
3296 NSRecycleZone(zone_);
3298 int chk(creat("/tmp/cydia.chk", 0644));
3302 NSString *title(UCLocalize("DATABASE"));
3305 if (!cache_.Open(progress_, true)) { pop:
3307 bool warning(!_error->PopMessage(error));
3308 lprintf("cache_.Open():[%s]\n", error.c_str());
3310 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3311 [delegate_ repairWithSelector:@selector(configure)];
3312 else if (error == "The package lists or status file could not be parsed or opened.")
3313 [delegate_ repairWithSelector:@selector(update)];
3314 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3315 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3316 // else if (error == "The list of sources could not be read.")
3318 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3327 unlink("/tmp/cydia.chk");
3329 now_ = [[NSDate date] retain];
3331 policy_ = new pkgDepCache::Policy();
3332 records_ = new pkgRecords(cache_);
3333 resolver_ = new pkgProblemResolver(cache_);
3334 fetcher_ = new pkgAcquire(&status_);
3337 list_ = new pkgSourceList();
3338 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3341 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3342 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3346 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3349 if (cache_->BrokenCount() != 0) {
3350 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3353 if (cache_->BrokenCount() != 0) {
3354 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3358 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3364 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3365 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3366 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3367 // XXX: this could be more intelligent
3368 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3369 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3371 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3378 /*std::vector<Package *> packages;
3379 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3380 [packages_ release];
3385 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3386 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3387 //packages.push_back(package);
3388 [packages_ addObject:package];
3392 /*if (packages.empty())
3393 packages_ = [[NSArray alloc] init];
3395 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3398 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3399 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3400 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3408 /*if (!packages.empty())
3409 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3410 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3412 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3414 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3416 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3422 - (void) configure {
3423 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3424 system([dpkg UTF8String]);
3428 // XXX: I don't remember this condition
3433 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3435 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3437 if ([self popErrorWithTitle:title])
3441 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3444 public pkgArchiveCleaner
3447 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3452 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3459 fetcher_->Shutdown();
3461 pkgRecords records(cache_);
3463 lock_ = new FileFd();
3464 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3466 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3468 if ([self popErrorWithTitle:title])
3472 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3475 manager_ = (_system->CreatePM(cache_));
3476 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3483 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3485 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3487 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3489 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3490 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3493 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3498 bool failed = false;
3499 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3500 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3502 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3505 std::string uri = (*item)->DescURI();
3506 std::string error = (*item)->ErrorText;
3508 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3511 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3512 withObject:[NSArray arrayWithObjects:
3513 [NSString stringWithUTF8String:error.c_str()],
3525 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3527 if (_error->PendingError()) {
3532 if (result == pkgPackageManager::Failed) {
3537 if (result != pkgPackageManager::Completed) {
3542 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3544 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3546 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3547 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3550 if (![before isEqualToArray:after])
3555 NSString *title(UCLocalize("UPGRADE"));
3556 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3562 [self updateWithStatus:status_];
3565 - (void) setVisible {
3566 for (Package *package in packages_)
3567 [package setVisible];
3570 - (void) updateWithStatus:(Status &)status {
3571 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3572 NSString *title(UCLocalize("REFRESHING_DATA"));
3575 if (!list.ReadMainList())
3576 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3579 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3580 if ([self popErrorWithTitle:title])
3583 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3584 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3585 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3587 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3591 - (void) setDelegate:(id)delegate {
3592 delegate_ = delegate;
3593 status_.setDelegate(delegate);
3594 progress_.setDelegate(delegate);
3597 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3598 SourceMap::const_iterator i(sources_.find(file->ID));
3599 return i == sources_.end() ? nil : i->second;
3605 /* Confirmation Controller {{{ */
3606 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3607 if (!iterator.end())
3608 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3609 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3611 pkgCache::PkgIterator package(dep.TargetPkg());
3614 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3622 /* Web Scripting {{{ */
3623 @interface CydiaObject : NSObject {
3628 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3631 @implementation CydiaObject
3634 [indirect_ release];
3638 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3639 if ((self = [super init]) != nil) {
3640 indirect_ = [indirect retain];
3644 - (void) setDelegate:(id)delegate {
3645 delegate_ = delegate;
3648 + (NSArray *) _attributeKeys {
3649 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3652 - (NSArray *) attributeKeys {
3653 return [[self class] _attributeKeys];
3656 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3657 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3660 - (NSString *) device {
3661 return [[UIDevice currentDevice] uniqueIdentifier];
3664 #if 0 // XXX: implement!
3665 - (NSString *) mac {
3666 if (![indirect_ promptForSensitive:@"Mac Address"])
3670 - (NSString *) serial {
3671 if (![indirect_ promptForSensitive:@"Serial #"])
3675 - (NSString *) firewire {
3676 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3680 - (NSString *) imei {
3681 if (![indirect_ promptForSensitive:@"IMEI"])
3686 + (NSString *) webScriptNameForSelector:(SEL)selector {
3687 if (selector == @selector(close))
3689 else if (selector == @selector(getInstalledPackages))
3690 return @"getInstalledPackages";
3691 else if (selector == @selector(getPackageById:))
3692 return @"getPackageById";
3693 else if (selector == @selector(installPackages:))
3694 return @"installPackages";
3695 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3696 return @"setButtonImage";
3697 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3698 return @"setButtonTitle";
3699 else if (selector == @selector(setPopupHook:))
3700 return @"setPopupHook";
3701 else if (selector == @selector(setSpecial:))
3702 return @"setSpecial";
3703 else if (selector == @selector(setToken:))
3705 else if (selector == @selector(setViewportWidth:))
3706 return @"setViewportWidth";
3707 else if (selector == @selector(supports:))
3709 else if (selector == @selector(stringWithFormat:arguments:))
3711 else if (selector == @selector(localizedStringForKey:value:table:))
3713 else if (selector == @selector(du:))
3715 else if (selector == @selector(statfs:))
3721 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3722 return [self webScriptNameForSelector:selector] == nil;
3725 - (BOOL) supports:(NSString *)feature {
3726 return [feature isEqualToString:@"window.open"];
3729 - (NSArray *) getInstalledPackages {
3730 NSArray *packages([[Database sharedInstance] packages]);
3731 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3732 for (Package *package in packages)
3733 if ([package installed] != nil)
3734 [installed addObject:package];
3738 - (Package *) getPackageById:(NSString *)id {
3739 Package *package([[Database sharedInstance] packageWithName:id]);
3744 - (NSArray *) statfs:(NSString *)path {
3747 if (path == nil || statfs([path UTF8String], &stat) == -1)
3750 return [NSArray arrayWithObjects:
3751 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3752 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3753 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3757 - (NSNumber *) du:(NSString *)path {
3758 NSNumber *value(nil);
3761 _assert(pipe(fds) != -1);
3763 pid_t pid(ExecFork());
3765 _assert(dup2(fds[1], 1) != -1);
3766 _assert(close(fds[0]) != -1);
3767 _assert(close(fds[1]) != -1);
3768 /* XXX: this should probably not use du */
3769 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3774 _assert(close(fds[1]) != -1);
3776 if (FILE *du = fdopen(fds[0], "r")) {
3778 while (fgets(line, sizeof(line), du) != NULL) {
3779 size_t length(strlen(line));
3780 while (length != 0 && line[length - 1] == '\n')
3781 line[--length] = '\0';
3782 if (char *tab = strchr(line, '\t')) {
3784 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3789 } else _assert(close(fds[0]));
3793 if (waitpid(pid, &status, 0) == -1)
3796 else _assert(false);
3805 - (void) installPackages:(NSArray *)packages {
3806 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3809 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3810 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3813 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3814 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3817 - (void) setSpecial:(id)function {
3818 [indirect_ setSpecial:function];
3821 - (void) setToken:(NSString *)token {
3824 Token_ = [token retain];
3826 [Metadata_ setObject:Token_ forKey:@"Token"];
3830 - (void) setPopupHook:(id)function {
3831 [indirect_ setPopupHook:function];
3834 - (void) setViewportWidth:(float)width {
3835 [indirect_ setViewportWidth:width];
3838 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3839 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3840 unsigned count([arguments count]);
3842 for (unsigned i(0); i != count; ++i)
3843 values[i] = [arguments objectAtIndex:i];
3844 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3847 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3848 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3850 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3852 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3858 /* Cydia Browser Controller {{{ */
3859 @interface CYBrowserController : BrowserController {
3860 CydiaObject *cydia_;
3865 @implementation CYBrowserController
3872 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3875 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3876 [super webView:view didClearWindowObject:window forFrame:frame];
3878 WebDataSource *source([frame dataSource]);
3879 NSURLResponse *response([source response]);
3880 NSURL *url([response URL]);
3881 NSString *scheme([url scheme]);
3883 NSHTTPURLResponse *http;
3884 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3885 http = (NSHTTPURLResponse *) response;
3889 NSDictionary *headers([http allHeaderFields]);
3890 NSString *host([url host]);
3891 [self setHeaders:headers forHost:host];
3894 [host isEqualToString:@"cydia.saurik.com"] ||
3895 [host hasSuffix:@".cydia.saurik.com"] ||
3896 [scheme isEqualToString:@"file"]
3898 [window setValue:cydia_ forKey:@"cydia"];
3901 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3902 if (System_ != NULL)
3903 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3904 if (Machine_ != NULL)
3905 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3907 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3909 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3912 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3913 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3914 [self _setMoreHeaders:copy];
3918 - (void) setDelegate:(id)delegate {
3919 [super setDelegate:delegate];
3920 [cydia_ setDelegate:delegate];
3924 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3925 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3927 WebView *webview([[webview_ _documentView] webView]);
3929 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3931 NSString *application = package == nil ? @"Cydia" : [NSString
3932 stringWithFormat:@"Cydia/%@",
3937 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3939 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3940 if (Product_ != nil)
3941 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3943 [webview setApplicationNameForUserAgent:application];
3950 /* Confirmation {{{ */
3951 @protocol ConfirmationControllerDelegate
3952 - (void) cancelAndClear:(bool)clear;
3953 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3957 @interface ConfirmationController : CYBrowserController {
3958 _transient Database *database_;
3959 UIAlertView *essential_;
3966 - (id) initWithDatabase:(Database *)database;
3970 @implementation ConfirmationController
3977 if (essential_ != nil)
3978 [essential_ release];
3982 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3983 NSString *context([alert context]);
3985 if ([context isEqualToString:@"remove"]) {
3986 if (button == [alert cancelButtonIndex]) {
3987 [self dismissModalViewControllerAnimated:YES];
3988 } else if (button == [alert firstOtherButtonIndex]) {
3991 [delegate_ confirmWithNavigationController:[self navigationController]];
3994 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3995 } else if ([context isEqualToString:@"unable"]) {
3996 [self dismissModalViewControllerAnimated:YES];
3997 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3999 [super alertView:alert clickedButtonAtIndex:button];
4003 - (void) _doContinue {
4004 [self dismissModalViewControllerAnimated:YES];
4005 [delegate_ cancelAndClear:NO];
4008 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4009 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4013 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4014 [super webView:view didClearWindowObject:window forFrame:frame];
4015 [window setValue:changes_ forKey:@"changes"];
4016 [window setValue:issues_ forKey:@"issues"];
4017 [window setValue:sizes_ forKey:@"sizes"];
4018 [window setValue:self forKey:@"queue"];
4021 - (id) initWithDatabase:(Database *)database {
4022 if ((self = [super init]) != nil) {
4023 database_ = database;
4025 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4027 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4028 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4029 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4030 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4031 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4035 pkgDepCache::Policy *policy([database_ policy]);
4037 pkgCacheFile &cache([database_ cache]);
4038 NSArray *packages = [database_ packages];
4039 for (Package *package in packages) {
4040 pkgCache::PkgIterator iterator = [package iterator];
4041 pkgDepCache::StateCache &state(cache[iterator]);
4043 NSString *name([package name]);
4045 if (state.NewInstall())
4046 [installing addObject:name];
4047 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4048 [reinstalling addObject:name];
4049 else if (state.Upgrade())
4050 [upgrading addObject:name];
4051 else if (state.Downgrade())
4052 [downgrading addObject:name];
4053 else if (state.Delete()) {
4054 if ([package essential])
4056 [removing addObject:name];
4059 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4060 substrate_ |= DepSubstrate(iterator.CurrentVer());
4065 else if (Advanced_) {
4066 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4068 essential_ = [[UIAlertView alloc]
4069 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4070 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4072 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4073 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4076 [essential_ setContext:@"remove"];
4078 essential_ = [[UIAlertView alloc]
4079 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4080 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4082 cancelButtonTitle:UCLocalize("OKAY")
4083 otherButtonTitles:nil
4086 [essential_ setContext:@"unable"];
4089 changes_ = [[NSArray alloc] initWithObjects:
4097 issues_ = [database_ issues];
4099 issues_ = [issues_ retain];
4101 sizes_ = [[NSArray alloc] initWithObjects:
4102 SizeString([database_ fetcher].FetchNeeded()),
4103 SizeString([database_ fetcher].PartialPresent()),
4106 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4108 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
4109 initWithTitle:UCLocalize("CANCEL")
4110 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4111 style:UIBarButtonItemStylePlain
4113 action:@selector(cancelButtonClicked)
4115 [[self navigationItem] setLeftBarButtonItem:leftItem];
4120 - (void) applyRightButton {
4121 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
4122 initWithTitle:UCLocalize("CONFIRM")
4123 style:UIBarButtonItemStylePlain
4125 action:@selector(confirmButtonClicked)
4127 #if !AlwaysReload && !IgnoreInstall
4128 if (issues_ == nil && ![self isLoading]) [[self navigationItem] setRightBarButtonItem:rightItem];
4129 else [super applyRightButton];
4131 [[self navigationItem] setRightBarButtonItem:nil];
4133 [rightItem release];
4136 - (void) cancelButtonClicked {
4137 [self dismissModalViewControllerAnimated:YES];
4138 [delegate_ cancelAndClear:YES];
4142 - (void) confirmButtonClicked {
4146 if (essential_ != nil)
4151 [delegate_ confirmWithNavigationController:[self navigationController]];
4159 /* Progress Data {{{ */
4160 @interface ProgressData : NSObject {
4166 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4173 @implementation ProgressData
4175 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4176 if ((self = [super init]) != nil) {
4177 selector_ = selector;
4197 /* Progress Controller {{{ */
4198 @interface ProgressController : CYViewController <
4199 ConfigurationDelegate,
4202 _transient Database *database_;
4203 UIProgressBar *progress_;
4204 UITextView *output_;
4205 UITextLabel *status_;
4206 UIPushButton *close_;
4208 SHA1SumValue springlist_;
4209 SHA1SumValue notifyconf_;
4213 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4215 - (void) _retachThread;
4216 - (void) _detachNewThreadData:(ProgressData *)data;
4217 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4223 @protocol ProgressControllerDelegate
4224 - (void) progressControllerIsComplete:(ProgressController *)sender;
4227 @implementation ProgressController
4230 [database_ setDelegate:nil];
4231 [progress_ release];
4240 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4241 if ((self = [super init]) != nil) {
4242 database_ = database;
4243 [database_ setDelegate:self];
4244 delegate_ = delegate;
4246 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4248 progress_ = [[UIProgressBar alloc] init];
4249 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4250 [progress_ setStyle:0];
4252 status_ = [[UITextLabel alloc] init];
4253 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4254 [status_ setColor:[UIColor whiteColor]];
4255 [status_ setBackgroundColor:[UIColor clearColor]];
4256 [status_ setCentersHorizontally:YES];
4257 //[status_ setFont:font];
4259 output_ = [[UITextView alloc] init];
4261 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4262 //[output_ setTextFont:@"Courier New"];
4263 [output_ setFont:[[output_ font] fontWithSize:12]];
4264 [output_ setTextColor:[UIColor whiteColor]];
4265 [output_ setBackgroundColor:[UIColor clearColor]];
4266 [output_ setMarginTop:0];
4267 [output_ setAllowsRubberBanding:YES];
4268 [output_ setEditable:NO];
4269 [[self view] addSubview:output_];
4271 close_ = [[UIPushButton alloc] init];
4272 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4273 [close_ setAutosizesToFit:NO];
4274 [close_ setDrawsShadow:YES];
4275 [close_ setStretchBackground:YES];
4276 [close_ setEnabled:YES];
4277 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4278 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4279 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4280 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4284 - (void) positionViews {
4285 CGRect bounds = [[self view] bounds];
4286 CGSize prgsize = [UIProgressBar defaultSize];
4289 (bounds.size.width - prgsize.width) / 2,
4290 bounds.size.height - prgsize.height - 20
4293 float closewidth = bounds.size.width - 20;
4294 if (closewidth > 300) closewidth = 300;
4296 [progress_ setFrame:prgrect];
4297 [status_ setFrame:CGRectMake(
4299 bounds.size.height - prgsize.height - 50,
4300 bounds.size.width - 20,
4303 [output_ setFrame:CGRectMake(
4306 bounds.size.width - 20,
4307 bounds.size.height - 62
4309 [close_ setFrame:CGRectMake(
4310 (bounds.size.width - closewidth) / 2,
4311 bounds.size.height - prgsize.height - 50,
4317 - (void) viewWillAppear:(BOOL)animated {
4318 [super viewDidAppear:animated];
4319 [[self navigationItem] setHidesBackButton:YES];
4320 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4322 [self positionViews];
4325 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4326 [self positionViews];
4329 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4330 NSString *context([alert context]);
4332 if ([context isEqualToString:@"conffile"]) {
4333 FILE *input = [database_ input];
4334 if (button == [alert cancelButtonIndex]) fprintf(input, "N\n");
4335 else if (button == [alert firstOtherButtonIndex]) fprintf(input, "Y\n");
4340 - (void) closeButtonPushed {
4343 UpdateExternalStatus(0);
4347 [self dismissModalViewControllerAnimated:YES];
4351 [delegate_ terminateWithSuccess];
4352 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4353 [delegate_ suspendWithAnimation:YES];
4355 [delegate_ suspend];*/
4359 system("launchctl stop com.apple.SpringBoard");
4363 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4372 - (void) _retachThread {
4373 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4375 [[self view] addSubview:close_];
4376 [progress_ removeFromSuperview];
4377 [status_ removeFromSuperview];
4379 [database_ popErrorWithTitle:title_];
4380 [delegate_ progressControllerIsComplete:self];
4384 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4387 MMap mmap(file, MMap::ReadOnly);
4389 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4390 if (!(notifyconf_ == sha1.Result()))
4397 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4400 MMap mmap(file, MMap::ReadOnly);
4402 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4403 if (!(springlist_ == sha1.Result()))
4409 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4410 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4411 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4412 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4413 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4416 system("su -c /usr/bin/uicache mobile");
4418 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4420 [delegate_ setStatusBarShowsProgress:NO];
4423 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4424 [[data target] performSelector:[data selector] withObject:[data object]];
4427 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4430 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4431 UpdateExternalStatus(1);
4438 title_ = [title retain];
4440 [[self navigationItem] setTitle:title_];
4442 [status_ setText:nil];
4443 [output_ setText:@""];
4444 [progress_ setProgress:0];
4446 [close_ removeFromSuperview];
4447 [[self view] addSubview:progress_];
4448 [[self view] addSubview:status_];
4450 [delegate_ setStatusBarShowsProgress:YES];
4455 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4458 MMap mmap(file, MMap::ReadOnly);
4460 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4461 notifyconf_ = sha1.Result();
4467 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4470 MMap mmap(file, MMap::ReadOnly);
4472 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4473 springlist_ = sha1.Result();
4478 detachNewThreadSelector:@selector(_detachNewThreadData:)
4480 withObject:[[ProgressData alloc]
4481 initWithSelector:selector
4488 - (void) repairWithSelector:(SEL)selector {
4490 detachNewThreadSelector:selector
4493 title:UCLocalize("REPAIRING")
4497 - (void) setConfigurationData:(NSString *)data {
4499 performSelectorOnMainThread:@selector(_setConfigurationData:)
4505 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4506 CYActionSheet *sheet([[[CYActionSheet alloc]
4508 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4509 defaultButtonIndex:0
4512 [sheet setMessage:error];
4513 [sheet yieldToPopupAlertAnimated:YES];
4517 - (void) setProgressTitle:(NSString *)title {
4519 performSelectorOnMainThread:@selector(_setProgressTitle:)
4525 - (void) setProgressPercent:(float)percent {
4527 performSelectorOnMainThread:@selector(_setProgressPercent:)
4528 withObject:[NSNumber numberWithFloat:percent]
4533 - (void) startProgress {
4536 - (void) addProgressOutput:(NSString *)output {
4538 performSelectorOnMainThread:@selector(_addProgressOutput:)
4544 - (bool) isCancelling:(size_t)received {
4548 - (void) _setConfigurationData:(NSString *)data {
4549 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4551 if (!conffile_r(data)) {
4552 lprintf("E:invalid conffile\n");
4556 NSString *ofile = conffile_r[1];
4557 //NSString *nfile = conffile_r[2];
4559 UIAlertView *alert = [[[UIAlertView alloc]
4560 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4561 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4563 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4564 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4565 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4569 [alert setContext:@"conffile"];
4573 - (void) _setProgressTitle:(NSString *)title {
4574 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4575 for (size_t i(0), e([words count]); i != e; ++i) {
4576 NSString *word([words objectAtIndex:i]);
4577 if (Package *package = [database_ packageWithName:word])
4578 [words replaceObjectAtIndex:i withObject:[package name]];
4581 [status_ setText:[words componentsJoinedByString:@" "]];
4584 - (void) _setProgressPercent:(NSNumber *)percent {
4585 [progress_ setProgress:[percent floatValue]];
4588 - (void) _addProgressOutput:(NSString *)output {
4589 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4590 CGSize size = [output_ contentSize];
4591 CGRect rect = {{0, size.height}, {size.width, 0}};
4592 [output_ scrollRectToVisible:rect animated:YES];
4595 - (BOOL) isRunning {
4602 /* Cell Content View {{{ */
4603 @protocol ContentDelegate
4604 - (void) drawContentRect:(CGRect)rect;
4607 @interface ContentView : UIView {
4608 _transient id<ContentDelegate> delegate_;
4613 @implementation ContentView
4614 - (id) initWithFrame:(CGRect)frame {
4615 if ((self = [super initWithFrame:frame]) != nil) {
4616 /* Fix landscape stretching. */
4617 [self setNeedsDisplayOnBoundsChange:YES];
4621 - (void) setDelegate:(id<ContentDelegate>)delegate {
4622 delegate_ = delegate;
4625 - (void) drawRect:(CGRect)rect {
4626 [super drawRect:rect];
4627 [delegate_ drawContentRect:rect];
4631 /* Package Cell {{{ */
4632 @interface PackageCell : UITableViewCell <
4637 NSString *description_;
4643 ContentView *content_;
4649 - (PackageCell *) init;
4650 - (void) setPackage:(Package *)package;
4652 + (int) heightForPackage:(Package *)package;
4653 - (void) drawContentRect:(CGRect)rect;
4657 @implementation PackageCell
4659 - (void) clearPackage {
4670 if (description_ != nil) {
4671 [description_ release];
4675 if (source_ != nil) {
4680 if (badge_ != nil) {
4685 if (placard_ != nil) {
4695 [self clearPackage];
4702 return faded_ ? [self selectionPercent] : fade_;
4705 - (PackageCell *) init {
4706 CGRect frame(CGRectMake(0, 0, 320, 74));
4707 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4708 UIView *content([self contentView]);
4709 CGRect bounds([content bounds]);
4711 content_ = [[ContentView alloc] initWithFrame:bounds];
4712 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4713 [content addSubview:content_];
4715 [content_ setDelegate:self];
4716 [content_ setOpaque:YES];
4717 if ([self respondsToSelector:@selector(selectionPercent)])
4722 - (void) _setBackgroundColor {
4724 if (NSString *mode = [package_ mode]) {
4725 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4726 color = remove ? RemovingColor_ : InstallingColor_;
4728 color = [UIColor whiteColor];
4730 [content_ setBackgroundColor:color];
4731 [self setNeedsDisplay];
4734 - (void) setPackage:(Package *)package {
4735 [self clearPackage];
4738 Source *source = [package source];
4740 icon_ = [[package icon] retain];
4741 name_ = [[package name] retain];
4744 description_ = [package longDescription];
4745 if (description_ == nil)
4746 description_ = [package shortDescription];
4747 if (description_ != nil)
4748 description_ = [description_ retain];
4750 commercial_ = [package isCommercial];
4752 package_ = [package retain];
4754 NSString *label = nil;
4755 bool trusted = false;
4757 if (source != nil) {
4758 label = [source label];
4759 trusted = [source trusted];
4760 } else if ([[package id] isEqualToString:@"firmware"])
4761 label = UCLocalize("APPLE");
4763 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4765 NSString *from(label);
4767 NSString *section = [package simpleSection];
4768 if (section != nil && ![section isEqualToString:label]) {
4769 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4770 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4773 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4774 source_ = [from retain];
4776 if (NSString *purpose = [package primaryPurpose])
4777 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4778 badge_ = [badge_ retain];
4780 if ([package installed] != nil)
4781 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4782 placard_ = [placard_ retain];
4784 [self _setBackgroundColor];
4785 [content_ setNeedsDisplay];
4788 - (void) drawContentRect:(CGRect)rect {
4789 bool selected([self isSelected]);
4790 float width([self bounds].size.width);
4793 CGContextRef context(UIGraphicsGetCurrentContext());
4794 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4795 CGContextFillRect(context, rect);
4800 rect.size = [icon_ size];
4802 rect.size.width /= 2;
4803 rect.size.height /= 2;
4805 rect.origin.x = 25 - rect.size.width / 2;
4806 rect.origin.y = 25 - rect.size.height / 2;
4808 [icon_ drawInRect:rect];
4811 if (badge_ != nil) {
4812 CGSize size = [badge_ size];
4814 [badge_ drawAtPoint:CGPointMake(
4815 36 - size.width / 2,
4816 36 - size.height / 2
4824 UISetColor(commercial_ ? Purple_ : Black_);
4825 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4826 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4829 UISetColor(commercial_ ? Purplish_ : Gray_);
4830 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4832 if (placard_ != nil)
4833 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4836 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4837 //[self _setBackgroundColor];
4838 [super setSelected:selected animated:fade];
4839 [content_ setNeedsDisplay];
4842 + (int) heightForPackage:(Package *)package {
4848 /* Section Cell {{{ */
4849 @interface SectionCell : UITableViewCell <
4857 ContentView *content_;
4862 - (void) setSection:(Section *)section editing:(BOOL)editing;
4866 @implementation SectionCell
4868 - (void) clearSection {
4869 if (basic_ != nil) {
4874 if (section_ != nil) {
4884 if (count_ != nil) {
4891 [self clearSection];
4899 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4900 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4901 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4902 switch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4903 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4905 UIView *content([self contentView]);
4906 CGRect bounds([content bounds]);
4908 content_ = [[ContentView alloc] initWithFrame:bounds];
4909 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4910 [content addSubview:content_];
4911 [content_ setBackgroundColor:[UIColor whiteColor]];
4913 [content_ setDelegate:self];
4917 - (void) onSwitch:(id)sender {
4918 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4919 if (metadata == nil) {
4920 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4921 [Sections_ setObject:metadata forKey:basic_];
4925 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4928 - (void) setSection:(Section *)section editing:(BOOL)editing {
4929 if (editing != editing_) {
4931 [switch_ removeFromSuperview];
4933 [self addSubview:switch_];
4937 [self clearSection];
4939 if (section == nil) {
4940 name_ = [UCLocalize("ALL_PACKAGES") retain];
4943 basic_ = [section name];
4945 basic_ = [basic_ retain];
4947 section_ = [section localized];
4948 if (section_ != nil)
4949 section_ = [section_ retain];
4951 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4952 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4955 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4958 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4959 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
4961 [content_ setNeedsDisplay];
4964 - (void) setFrame:(CGRect)frame {
4965 [super setFrame:frame];
4967 CGRect rect([switch_ frame]);
4968 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4971 - (void) drawContentRect:(CGRect)rect {
4972 BOOL selected = [self isSelected];
4974 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4982 float width(rect.size.width);
4986 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4988 CGSize size = [count_ sizeWithFont:Font14_];
4992 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4998 /* File Table {{{ */
4999 @interface FileTable : CYViewController <
5000 UITableViewDataSource,
5003 _transient Database *database_;
5006 NSMutableArray *files_;
5010 - (id) initWithDatabase:(Database *)database;
5011 - (void) setPackage:(Package *)package;
5015 @implementation FileTable
5018 if (package_ != nil)
5027 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5028 return files_ == nil ? 0 : [files_ count];
5031 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5035 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5036 static NSString *reuseIdentifier = @"Cell";
5038 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5040 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5041 [cell setFont:[UIFont systemFontOfSize:16]];
5043 [cell setText:[files_ objectAtIndex:indexPath.row]];
5044 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5049 - (id) initWithDatabase:(Database *)database {
5050 if ((self = [super init]) != nil) {
5051 database_ = database;
5053 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5055 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5057 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5058 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5059 [list_ setRowHeight:24.0f];
5060 [[self view] addSubview:list_];
5062 [list_ setDataSource:self];
5063 [list_ setDelegate:self];
5067 - (void) setPackage:(Package *)package {
5068 if (package_ != nil) {
5069 [package_ autorelease];
5078 [files_ removeAllObjects];
5080 if (package != nil) {
5081 package_ = [package retain];
5082 name_ = [[package id] retain];
5084 if (NSArray *files = [package files])
5085 [files_ addObjectsFromArray:files];
5087 if ([files_ count] != 0) {
5088 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5089 [files_ removeObjectAtIndex:0];
5090 [files_ sortUsingSelector:@selector(compareByPath:)];
5092 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5093 [stack addObject:@"/"];
5095 for (int i(0), e([files_ count]); i != e; ++i) {
5096 NSString *file = [files_ objectAtIndex:i];
5097 while (![file hasPrefix:[stack lastObject]])
5098 [stack removeLastObject];
5099 NSString *directory = [stack lastObject];
5100 [stack addObject:[file stringByAppendingString:@"/"]];
5101 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5102 ([stack count] - 2) * 3, "",
5103 [file substringFromIndex:[directory length]]
5112 - (void) reloadData {
5113 [self setPackage:[database_ packageWithName:name_]];
5118 /* Package Controller {{{ */
5119 @interface PackageController : CYBrowserController <
5120 UIActionSheetDelegate
5122 _transient Database *database_;
5126 NSMutableArray *buttons_;
5127 UIBarButtonItem *button_;
5130 - (id) initWithDatabase:(Database *)database;
5131 - (void) setPackage:(Package *)package;
5135 @implementation PackageController
5138 if (package_ != nil)
5152 if ([self retainCount] == 1)
5153 [delegate_ setPackageController:self];
5157 /* XXX: this is not safe at all... localization of /fail/ */
5158 - (void) _clickButtonWithName:(NSString *)name {
5159 if ([name isEqualToString:UCLocalize("CLEAR")])
5160 [delegate_ clearPackage:package_];
5161 else if ([name isEqualToString:UCLocalize("INSTALL")])
5162 [delegate_ installPackage:package_];
5163 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5164 [delegate_ installPackage:package_];
5165 else if ([name isEqualToString:UCLocalize("REMOVE")])
5166 [delegate_ removePackage:package_];
5167 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5168 [delegate_ installPackage:package_];
5169 else _assert(false);
5172 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5173 NSString *context([sheet context]);
5175 if ([context isEqualToString:@"modify"]) {
5176 if (button != [sheet cancelButtonIndex]) {
5177 NSString *buttonName = [buttons_ objectAtIndex:button];
5178 [self _clickButtonWithName:buttonName];
5181 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5185 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5186 [super webView:view didClearWindowObject:window forFrame:frame];
5187 [window setValue:package_ forKey:@"package"];
5190 - (bool) _allowJavaScriptPanel {
5195 - (void) _customButtonClicked {
5196 int count([buttons_ count]);
5201 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5203 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5204 [buttons addObjectsFromArray:buttons_];
5206 UIActionSheet *sheet = [[[UIActionSheet alloc]
5209 cancelButtonTitle:nil
5210 destructiveButtonTitle:nil
5211 otherButtonTitles:nil
5214 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5216 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5217 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5219 [sheet setContext:@"modify"];
5221 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5225 // We don't want to allow non-commercial packages to do custom things to the install button,
5226 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5227 - (void) customButtonClicked {
5229 [super customButtonClicked];
5231 [self _customButtonClicked];
5234 - (void) reloadButtonClicked {
5235 // Don't reload a package view by clicking the button.
5238 - (void) applyLoadingTitle {
5239 // Don't show "Loading" as the title. Ever.
5242 - (UIBarButtonItem *) rightButton {
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")];
5292 switch ([buttons_ count]) {
5293 case 0: title = nil; break;
5294 case 1: title = [buttons_ objectAtIndex:0]; break;
5295 default: title = UCLocalize("MODIFY"); break;
5298 button_ = [[UIBarButtonItem alloc]
5300 style:UIBarButtonItemStylePlain
5302 action:@selector(customButtonClicked)
5306 - (bool) isLoading {
5307 return commercial_ ? [super isLoading] : false;
5310 - (void) reloadData {
5311 [self setPackage:[database_ packageWithName:name_]];
5316 /* Package Table {{{ */
5317 @interface PackageTable : UIView <
5318 UITableViewDataSource,
5321 _transient Database *database_;
5322 NSMutableArray *packages_;
5323 NSMutableArray *sections_;
5325 NSMutableArray *index_;
5326 NSMutableDictionary *indices_;
5332 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5334 - (void) setDelegate:(id)delegate;
5336 - (void) reloadData;
5337 - (void) resetCursor;
5339 - (UITableView *) list;
5341 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5343 - (void) deselectWithAnimation:(BOOL)animated;
5347 @implementation PackageTable
5350 [packages_ release];
5351 [sections_ release];
5359 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5360 NSInteger count([sections_ count]);
5361 return count == 0 ? 1 : count;
5364 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5365 if ([sections_ count] == 0)
5367 return [[sections_ objectAtIndex:section] name];
5370 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5371 if ([sections_ count] == 0)
5373 return [[sections_ objectAtIndex:section] count];
5376 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5377 Section *section([sections_ objectAtIndex:[path section]]);
5378 NSInteger row([path row]);
5379 Package *package([packages_ objectAtIndex:([section row] + row)]);
5383 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5384 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5386 cell = [[[PackageCell alloc] init] autorelease];
5387 [cell setPackage:[self packageAtIndexPath:path]];
5391 - (void) deselectWithAnimation:(BOOL)animated {
5392 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5395 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5396 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5399 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5400 Package *package([self packageAtIndexPath:path]);
5401 package = [database_ packageWithName:[package id]];
5402 [target_ performSelector:action_ withObject:package];
5406 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5407 return [packages_ count] > 20 ? index_ : nil;
5410 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5414 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5415 if ((self = [super initWithFrame:frame]) != nil) {
5416 database_ = database;
5421 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5422 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5424 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5425 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5427 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5428 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5429 [list_ setRowHeight:73.0f];
5430 [self addSubview:list_];
5432 [list_ setDataSource:self];
5433 [list_ setDelegate:self];
5437 - (void) setDelegate:(id)delegate {
5438 delegate_ = delegate;
5441 - (bool) hasPackage:(Package *)package {
5445 - (void) reloadData {
5446 NSArray *packages = [database_ packages];
5448 [packages_ removeAllObjects];
5449 [sections_ removeAllObjects];
5451 _profile(PackageTable$reloadData$Filter)
5452 for (Package *package in packages)
5453 if ([self hasPackage:package])
5454 [packages_ addObject:package];
5457 [index_ removeAllObjects];
5458 [indices_ removeAllObjects];
5460 Section *section = nil;
5462 _profile(PackageTable$reloadData$Section)
5463 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5467 _profile(PackageTable$reloadData$Section$Package)
5468 package = [packages_ objectAtIndex:offset];
5469 index = [package index];
5472 if (section == nil || [section index] != index) {
5473 _profile(PackageTable$reloadData$Section$Allocate)
5474 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5477 [index_ addObject:[section name]];
5478 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5480 _profile(PackageTable$reloadData$Section$Add)
5481 [sections_ addObject:section];
5485 [section addToCount];
5489 _profile(PackageTable$reloadData$List)
5494 - (void) resetCursor {
5495 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5498 - (UITableView *) list {
5502 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5503 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5508 /* Filtered Package Table {{{ */
5509 @interface FilteredPackageTable : PackageTable {
5515 - (void) setObject:(id)object;
5516 - (void) setObject:(id)object forFilter:(SEL)filter;
5518 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5522 @implementation FilteredPackageTable
5530 - (void) setFilter:(SEL)filter {
5533 /* XXX: this is an unsafe optimization of doomy hell */
5534 Method method(class_getInstanceMethod([Package class], filter));
5535 _assert(method != NULL);
5536 imp_ = method_getImplementation(method);
5537 _assert(imp_ != NULL);
5540 - (void) setObject:(id)object {
5546 object_ = [object retain];
5549 - (void) setObject:(id)object forFilter:(SEL)filter {
5550 [self setFilter:filter];
5551 [self setObject:object];
5554 - (bool) hasPackage:(Package *)package {
5555 _profile(FilteredPackageTable$hasPackage)
5556 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5560 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5561 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5562 [self setFilter:filter];
5563 object_ = [object retain];
5571 /* Filtered Package Controller {{{ */
5572 @interface FilteredPackageController : CYViewController {
5573 _transient Database *database_;
5574 FilteredPackageTable *packages_;
5578 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5582 @implementation FilteredPackageController
5585 [packages_ release];
5591 - (void) viewDidAppear:(BOOL)animated {
5592 [super viewDidAppear:animated];
5593 [packages_ deselectWithAnimation:animated];
5596 - (void) didSelectPackage:(Package *)package {
5597 PackageController *view([delegate_ packageController]);
5598 [view setPackage:package];
5599 [view setDelegate:delegate_];
5600 [[self navigationController] pushViewController:view animated:YES];
5603 - (NSString *) title { return title_; }
5605 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5606 if ((self = [super init]) != nil) {
5607 database_ = database;
5608 title_ = [title copy];
5609 [[self navigationItem] setTitle:title_];
5611 packages_ = [[FilteredPackageTable alloc]
5612 initWithFrame:[[self view] bounds]
5615 action:@selector(didSelectPackage:)
5620 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5621 [[self view] addSubview:packages_];
5625 - (void) reloadData {
5626 [packages_ reloadData];
5629 - (void) setDelegate:(id)delegate {
5630 [super setDelegate:delegate];
5631 [packages_ setDelegate:delegate];
5638 /* Add Source Controller {{{ */
5639 @interface AddSourceController : CYViewController {
5640 _transient Database *database_;
5643 - (id) initWithDatabase:(Database *)database;
5647 @implementation AddSourceController
5649 - (id) initWithDatabase:(Database *)database {
5650 if ((self = [super init]) != nil) {
5651 database_ = database;
5657 /* Source Cell {{{ */
5658 @interface SourceCell : UITableViewCell <
5663 NSString *description_;
5665 ContentView *content_;
5668 - (void) setSource:(Source *)source;
5672 @implementation SourceCell
5674 - (void) clearSource {
5677 [description_ release];
5686 - (void) setSource:(Source *)source {
5690 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5692 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5693 icon_ = [icon_ retain];
5695 origin_ = [[source name] retain];
5696 label_ = [[source uri] retain];
5697 description_ = [[source description] retain];
5699 [content_ setNeedsDisplay];
5708 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5709 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5710 UIView *content([self contentView]);
5711 CGRect bounds([content bounds]);
5713 content_ = [[ContentView alloc] initWithFrame:bounds];
5714 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5715 [content_ setBackgroundColor:[UIColor whiteColor]];
5716 [content addSubview:content_];
5718 [content_ setDelegate:self];
5719 [content_ setOpaque:YES];
5723 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5724 [super setSelected:selected animated:animated];
5725 [content_ setNeedsDisplay];
5728 - (void) drawContentRect:(CGRect)rect {
5729 bool selected([self isSelected]);
5730 float width(rect.size.width);
5733 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5740 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5744 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5748 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5753 /* Source Table {{{ */
5754 @interface SourceTable : CYViewController <
5755 UITableViewDataSource,
5758 _transient Database *database_;
5760 NSMutableArray *sources_;
5764 UIProgressHUD *hud_;
5767 //NSURLConnection *installer_;
5768 NSURLConnection *trivial_;
5769 NSURLConnection *trivial_bz2_;
5770 NSURLConnection *trivial_gz_;
5771 //NSURLConnection *automatic_;
5776 - (id) initWithDatabase:(Database *)database;
5778 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5782 @implementation SourceTable
5784 - (void) _deallocConnection:(NSURLConnection *)connection {
5785 if (connection != nil) {
5786 [connection cancel];
5787 //[connection setDelegate:nil];
5788 [connection release];
5800 //[self _deallocConnection:installer_];
5801 [self _deallocConnection:trivial_];
5802 [self _deallocConnection:trivial_gz_];
5803 [self _deallocConnection:trivial_bz2_];
5804 //[self _deallocConnection:automatic_];
5811 - (void) viewDidAppear:(BOOL)animated {
5812 [super viewDidAppear:animated];
5813 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5816 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5817 return offset_ == 0 ? 1 : 2;
5820 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5821 switch (section + (offset_ == 0 ? 1 : 0)) {
5822 case 0: return UCLocalize("ENTERED_BY_USER");
5823 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5829 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5830 int count = [sources_ count];
5832 case 0: return (offset_ == 0 ? count : offset_);
5833 case 1: return count - offset_;
5839 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5841 switch (indexPath.section) {
5842 case 0: idx = indexPath.row; break;
5843 case 1: idx = indexPath.row + offset_; break;
5847 return [sources_ objectAtIndex:idx];
5850 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5851 Source *source = [self sourceAtIndexPath:indexPath];
5852 return [source description] == nil ? 56 : 73;
5855 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5856 static NSString *cellIdentifier = @"SourceCell";
5858 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5859 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5860 [cell setSource:[self sourceAtIndexPath:indexPath]];
5865 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5866 return UITableViewCellAccessoryDisclosureIndicator;
5869 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5870 Source *source = [self sourceAtIndexPath:indexPath];
5872 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5873 initWithDatabase:database_
5874 title:[source label]
5875 filter:@selector(isVisibleInSource:)
5879 [packages setDelegate:delegate_];
5881 [[self navigationController] pushViewController:packages animated:YES];
5884 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5885 Source *source = [self sourceAtIndexPath:indexPath];
5886 return [source record] != nil;
5889 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5890 Source *source = [self sourceAtIndexPath:indexPath];
5891 [Sources_ removeObjectForKey:[source key]];
5892 [delegate_ syncData];
5896 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5899 @"./", @"Distribution",
5900 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5902 [delegate_ syncData];
5905 - (NSString *) getWarning {
5906 NSString *href(href_);
5907 NSRange colon([href rangeOfString:@"://"]);
5908 if (colon.location != NSNotFound)
5909 href = [href substringFromIndex:(colon.location + 3)];
5910 href = [href stringByAddingPercentEscapes];
5911 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5912 href = [href stringByCachingURLWithCurrentCDN];
5914 NSURL *url([NSURL URLWithString:href]);
5916 NSStringEncoding encoding;
5917 NSError *error(nil);
5919 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5920 return [warning length] == 0 ? nil : warning;
5924 - (void) _endConnection:(NSURLConnection *)connection {
5925 NSURLConnection **field = NULL;
5926 if (connection == trivial_)
5928 else if (connection == trivial_bz2_)
5929 field = &trivial_bz2_;
5930 else if (connection == trivial_gz_)
5931 field = &trivial_gz_;
5932 _assert(field != NULL);
5933 [connection release];
5938 trivial_bz2_ == nil &&
5944 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5947 UIAlertView *alert = [[[UIAlertView alloc]
5948 initWithTitle:UCLocalize("SOURCE_WARNING")
5951 cancelButtonTitle:UCLocalize("CANCEL")
5952 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5955 [alert setContext:@"warning"];
5956 [alert setNumberOfRows:1];
5960 } else if (error_ != nil) {
5961 UIAlertView *alert = [[[UIAlertView alloc]
5962 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5963 message:[error_ localizedDescription]
5965 cancelButtonTitle:UCLocalize("OK")
5966 otherButtonTitles:nil
5969 [alert setContext:@"urlerror"];
5972 UIAlertView *alert = [[[UIAlertView alloc]
5973 initWithTitle:UCLocalize("NOT_REPOSITORY")
5974 message:UCLocalize("NOT_REPOSITORY_EX")
5976 cancelButtonTitle:UCLocalize("OK")
5977 otherButtonTitles:nil
5980 [alert setContext:@"trivial"];
5984 [delegate_ setStatusBarShowsProgress:NO];
5985 [delegate_ removeProgressHUD:hud_];
5995 if (error_ != nil) {
6002 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6003 switch ([response statusCode]) {
6009 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6010 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6012 error_ = [error retain];
6013 [self _endConnection:connection];
6016 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6017 [self _endConnection:connection];
6020 - (NSString *) title { return UCLocalize("SOURCES"); }
6022 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6023 NSMutableURLRequest *request = [NSMutableURLRequest
6024 requestWithURL:[NSURL URLWithString:href]
6025 cachePolicy:NSURLRequestUseProtocolCachePolicy
6026 timeoutInterval:120.0
6029 [request setHTTPMethod:method];
6031 if (Machine_ != NULL)
6032 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6033 if (UniqueID_ != nil)
6034 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6036 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6038 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6041 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6042 NSString *context([alert context]);
6044 if ([context isEqualToString:@"source"]) {
6047 NSString *href = [[alert textField] text];
6049 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6051 if (![href hasSuffix:@"/"])
6052 href_ = [href stringByAppendingString:@"/"];
6055 href_ = [href_ retain];
6057 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6058 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6059 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6060 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6064 hud_ = [[delegate_ addProgressHUD] retain];
6065 [hud_ setText:UCLocalize("VERIFYING_URL")];
6074 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6075 } else if ([context isEqualToString:@"trivial"])
6076 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6077 else if ([context isEqualToString:@"urlerror"])
6078 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6079 else if ([context isEqualToString:@"warning"]) {
6094 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6098 - (id) initWithDatabase:(Database *)database {
6099 if ((self = [super init]) != nil) {
6100 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6101 [self updateButtonsForEditingStatus:NO animated:NO];
6103 database_ = database;
6104 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6106 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6107 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6108 [[self view] addSubview:list_];
6110 [list_ setDataSource:self];
6111 [list_ setDelegate:self];
6117 - (void) reloadData {
6119 if (!list.ReadMainList())
6122 [sources_ removeAllObjects];
6123 [sources_ addObjectsFromArray:[database_ sources]];
6125 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6128 int count([sources_ count]);
6130 for (int i = 0; i != count; i++) {
6131 if ([[sources_ objectAtIndex:i] record] == nil) break;
6135 [list_ setEditing:NO];
6136 [self updateButtonsForEditingStatus:NO animated:NO];
6140 - (void) addButtonClicked {
6141 /*[book_ pushPage:[[[AddSourceController alloc]
6146 UIAlertView *alert = [[[UIAlertView alloc]
6147 initWithTitle:UCLocalize("ENTER_APT_URL")
6150 cancelButtonTitle:UCLocalize("CANCEL")
6151 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6154 [alert setContext:@"source"];
6155 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6157 [alert setNumberOfRows:1];
6158 [alert addTextFieldWithValue:@"http://" label:@""];
6160 UITextInputTraits *traits = [[alert textField] textInputTraits];
6161 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6162 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6163 [traits setKeyboardType:UIKeyboardTypeURL];
6164 // XXX: UIReturnKeyDone
6165 [traits setReturnKeyType:UIReturnKeyNext];
6170 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6171 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
6172 initWithTitle:UCLocalize("ADD")
6173 style:UIBarButtonItemStylePlain
6175 action:@selector(addButtonClicked)
6177 [[self navigationItem] setLeftBarButtonItem:editing ? leftItem : [[self navigationItem] backBarButtonItem] animated:animated];
6180 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6181 initWithTitle:editing ? UCLocalize("DONE") : UCLocalize("EDIT")
6182 style:editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6184 action:@selector(editButtonClicked)
6186 [[self navigationItem] setRightBarButtonItem:rightItem animated:animated];
6187 [rightItem release];
6189 if (IsWildcat_ && !editing) {
6190 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6191 initWithTitle:UCLocalize("SETTINGS")
6192 style:UIBarButtonItemStylePlain
6194 action:@selector(settingsButtonClicked)
6196 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6197 [settingsItem release];
6201 - (void) settingsButtonClicked {
6202 [delegate_ showSettings];
6205 - (void) editButtonClicked {
6206 [list_ setEditing:![list_ isEditing] animated:YES];
6208 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6214 /* Installed Controller {{{ */
6215 @interface InstalledController : FilteredPackageController {
6219 - (id) initWithDatabase:(Database *)database;
6221 - (void) updateRoleButton;
6222 - (void) queueStatusDidChange;
6226 @implementation InstalledController
6232 - (NSString *) title { return UCLocalize("INSTALLED"); }
6234 - (id) initWithDatabase:(Database *)database {
6235 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndVisible:) with:[NSNumber numberWithBool:YES]]) != nil) {
6236 [self updateRoleButton];
6237 [self queueStatusDidChange];
6242 - (void) queueButtonClicked {
6247 - (void) queueStatusDidChange {
6250 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6251 initWithTitle:UCLocalize("QUEUE")
6252 style:UIBarButtonItemStyleDone
6254 action:@selector(queueButtonClicked)
6256 if (Queuing_) [[self navigationItem] setLeftBarButtonItem:queueItem];
6257 else [[self navigationItem] setLeftBarButtonItem:nil];
6258 [queueItem release];
6263 - (void) reloadData {
6264 [packages_ reloadData];
6267 - (void) updateRoleButton {
6268 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6269 initWithTitle:expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE")
6270 style:expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain
6272 action:@selector(roleButtonClicked)
6274 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"]) [[self navigationItem] setRightBarButtonItem:rightItem];
6275 [rightItem release];
6278 - (void) roleButtonClicked {
6279 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6280 [packages_ reloadData];
6283 [self updateRoleButton];
6286 - (void) setDelegate:(id)delegate {
6287 [super setDelegate:delegate];
6288 [packages_ setDelegate:delegate];
6294 /* Home Controller {{{ */
6295 @interface HomeController : CYBrowserController {
6300 @implementation HomeController
6302 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6303 [super _setMoreHeaders:request];
6306 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6307 if (UniqueID_ != nil)
6308 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6310 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6313 - (void) aboutButtonClicked {
6314 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6316 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6317 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6318 [alert setCancelButtonIndex:0];
6321 @"Copyright (C) 2008-2010\n"
6322 "Jay Freeman (saurik)\n"
6323 "saurik@saurik.com\n"
6324 "http://www.saurik.com/"
6330 - (void) viewWillAppear:(BOOL)animated {
6331 [super viewWillAppear:animated];
6332 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6335 - (void) viewWillDisappear:(BOOL)animated {
6336 [super viewWillDisappear:animated];
6337 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6341 if ((self = [super init]) != nil) {
6342 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6343 initWithTitle:UCLocalize("ABOUT")
6344 style:UIBarButtonItemStylePlain
6346 action:@selector(aboutButtonClicked)
6353 /* Manage Controller {{{ */
6354 @interface ManageController : CYBrowserController {
6357 - (void) queueStatusDidChange;
6360 @implementation ManageController
6363 if ((self = [super init]) != nil) {
6364 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6366 UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]
6367 initWithTitle:UCLocalize("SETTINGS")
6368 style:UIBarButtonItemStylePlain
6370 action:@selector(settingsButtonClicked)
6372 [[self navigationItem] setLeftBarButtonItem:settingsItem];
6373 [settingsItem release];
6375 [self queueStatusDidChange];
6379 - (void) settingsButtonClicked {
6380 [delegate_ showSettings];
6384 - (void) queueButtonClicked {
6388 - (void) applyLoadingTitle {
6389 // No "Loading" title.
6392 - (void) applyRightButton {
6397 - (void) queueStatusDidChange {
6399 if (!IsWildcat_ && Queuing_) {
6400 UIBarButtonItem *queueItem = [[UIBarButtonItem alloc]
6401 initWithTitle:UCLocalize("QUEUE")
6402 style:UIBarButtonItemStyleDone
6404 action:@selector(queueButtonClicked)
6406 [[self navigationItem] setRightBarButtonItem:queueItem];
6408 [queueItem release];
6410 [[self navigationItem] setRightBarButtonItem:nil];
6415 - (bool) isLoading {
6422 /* Refresh Bar {{{ */
6423 @interface RefreshBar : UINavigationBar {
6424 UIProgressIndicator *indicator_;
6425 UITextLabel *prompt_;
6426 UIProgressBar *progress_;
6427 UINavigationButton *cancel_;
6432 @implementation RefreshBar
6434 - (void) positionViews {
6435 CGRect frame = [cancel_ frame];
6436 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6437 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6438 [cancel_ setFrame:frame];
6440 CGSize prgsize = {75, 100};
6442 [self frame].size.width - prgsize.width - 10,
6443 ([self frame].size.height - prgsize.height) / 2
6445 [progress_ setFrame:prgrect];
6447 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6448 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6449 CGRect indrect = {{indoffset, indoffset}, indsize};
6450 [indicator_ setFrame:indrect];
6452 CGSize prmsize = {215, indsize.height + 4};
6454 indoffset * 2 + indsize.width,
6455 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6457 [prompt_ setFrame:prmrect];
6460 - (void)setFrame:(CGRect)frame {
6461 [super setFrame:frame];
6463 [self positionViews];
6466 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6467 if ((self = [super initWithFrame:frame])) {
6468 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6470 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6471 [self setBarStyle:UIBarStyleBlack];
6473 UIBarStyle barstyle([self _barStyle:NO]);
6474 bool ugly(barstyle == UIBarStyleDefault);
6476 UIProgressIndicatorStyle style = ugly ?
6477 UIProgressIndicatorStyleMediumBrown :
6478 UIProgressIndicatorStyleMediumWhite;
6480 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6481 [indicator_ setStyle:style];
6482 [indicator_ startAnimation];
6483 [self addSubview:indicator_];
6485 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6486 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6487 [prompt_ setBackgroundColor:[UIColor clearColor]];
6488 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6489 [self addSubview:prompt_];
6491 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6492 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6493 [progress_ setStyle:0];
6494 [self addSubview:progress_];
6496 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6497 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6498 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6499 [cancel_ setBarStyle:barstyle];
6501 [self positionViews];
6506 [cancel_ removeFromSuperview];
6510 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6511 [progress_ setProgress:0];
6512 [self addSubview:cancel_];
6516 [cancel_ removeFromSuperview];
6519 - (void) setPrompt:(NSString *)prompt {
6520 [prompt_ setText:prompt];
6523 - (void) setProgress:(float)progress {
6524 [progress_ setProgress:progress];
6530 @class CYNavigationController;
6532 /* Cydia Tab Bar Controller {{{ */
6533 @interface CYTabBarController : UITabBarController {
6534 Database *database_;
6539 @implementation CYTabBarController
6541 /* XXX: some logic should probably go here related to
6542 freeing the view controllers on tab change */
6544 - (void) reloadData {
6545 size_t count([[self viewControllers] count]);
6546 for (size_t i(0); i != count; ++i) {
6547 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6552 - (id) initWithDatabase:(Database *)database {
6553 if ((self = [super init]) != nil) {
6554 database_ = database;
6561 /* Cydia Navigation Controller {{{ */
6562 @interface CYNavigationController : UINavigationController {
6563 _transient Database *database_;
6564 id<UINavigationControllerDelegate> delegate_;
6567 - (id) initWithDatabase:(Database *)database;
6568 - (void) reloadData;
6573 @implementation CYNavigationController
6575 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6576 // Inherit autorotation settings for modal parents.
6577 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6578 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6580 return [super shouldAutorotateToInterfaceOrientation:orientation];
6588 - (void) reloadData {
6589 size_t count([[self viewControllers] count]);
6590 for (size_t i(0); i != count; ++i) {
6591 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6596 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6597 delegate_ = delegate;
6600 - (id) initWithDatabase:(Database *)database {
6601 if ((self = [super init]) != nil) {
6602 database_ = database;
6608 /* Cydia:// Protocol {{{ */
6609 @interface CydiaURLProtocol : NSURLProtocol {
6614 @implementation CydiaURLProtocol
6616 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6617 NSURL *url([request URL]);
6620 NSString *scheme([[url scheme] lowercaseString]);
6621 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6626 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6630 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6631 id<NSURLProtocolClient> client([self client]);
6633 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6635 NSData *data(UIImagePNGRepresentation(icon));
6637 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6638 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6639 [client URLProtocol:self didLoadData:data];
6640 [client URLProtocolDidFinishLoading:self];
6644 - (void) startLoading {
6645 id<NSURLProtocolClient> client([self client]);
6646 NSURLRequest *request([self request]);
6648 NSURL *url([request URL]);
6649 NSString *href([url absoluteString]);
6651 NSString *path([href substringFromIndex:8]);
6652 NSRange slash([path rangeOfString:@"/"]);
6655 if (slash.location == NSNotFound) {
6659 command = [path substringToIndex:slash.location];
6660 path = [path substringFromIndex:(slash.location + 1)];
6663 Database *database([Database sharedInstance]);
6665 if ([command isEqualToString:@"package-icon"]) {
6668 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6669 Package *package([database packageWithName:path]);
6672 UIImage *icon([package icon]);
6673 [self _returnPNGWithImage:icon forRequest:request];
6674 } else if ([command isEqualToString:@"source-icon"]) {
6677 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6678 NSString *source(Simplify(path));
6679 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6681 icon = [UIImage applicationImageNamed:@"unknown.png"];
6682 [self _returnPNGWithImage:icon forRequest:request];
6683 } else if ([command isEqualToString:@"uikit-image"]) {
6686 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6687 UIImage *icon(_UIImageWithName(path));
6688 [self _returnPNGWithImage:icon forRequest:request];
6689 } else if ([command isEqualToString:@"section-icon"]) {
6692 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6693 NSString *section(Simplify(path));
6694 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6696 icon = [UIImage applicationImageNamed:@"unknown.png"];
6697 [self _returnPNGWithImage:icon forRequest:request];
6699 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6703 - (void) stopLoading {
6709 /* Sections Controller {{{ */
6710 @interface SectionsController : CYViewController <
6711 UITableViewDataSource,
6714 _transient Database *database_;
6715 NSMutableArray *sections_;
6716 NSMutableArray *filtered_;
6722 - (id) initWithDatabase:(Database *)database;
6723 - (void) reloadData;
6726 - (void) editButtonClicked;
6730 @implementation SectionsController
6733 [list_ setDataSource:nil];
6734 [list_ setDelegate:nil];
6736 [sections_ release];
6737 [filtered_ release];
6739 [accessory_ release];
6743 - (void) viewDidAppear:(BOOL)animated {
6744 [super viewDidAppear:animated];
6745 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6748 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6749 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6753 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6754 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6757 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6761 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6762 static NSString *reuseIdentifier = @"SectionCell";
6764 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6765 if (cell == nil) cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6766 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6771 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6775 Section *section = [self sectionAtIndexPath:indexPath];
6776 NSString *name = [section name];
6779 if ([indexPath row] == 0) {
6782 title = UCLocalize("ALL_PACKAGES");
6785 name = [NSString stringWithString:name];
6786 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6789 title = UCLocalize("NO_SECTION");
6793 FilteredPackageController *table = [[[FilteredPackageController alloc]
6794 initWithDatabase:database_
6796 filter:@selector(isVisibleInSection:)
6800 [table setDelegate:delegate_];
6802 [[self navigationController] pushViewController:table animated:YES];
6805 - (NSString *) title { return UCLocalize("SECTIONS"); }
6807 - (id) initWithDatabase:(Database *)database {
6808 if ((self = [super init]) != nil) {
6809 database_ = database;
6811 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6813 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6814 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6816 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6817 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6818 [list_ setRowHeight:45.0f];
6819 [[self view] addSubview:list_];
6821 [list_ setDataSource:self];
6822 [list_ setDelegate:self];
6828 - (void) reloadData {
6829 NSArray *packages = [database_ packages];
6831 [sections_ removeAllObjects];
6832 [filtered_ removeAllObjects];
6835 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6836 SectionMap sections;
6837 sections.resize(64);
6839 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6843 for (Package *package in packages) {
6844 NSString *name([package section]);
6845 NSString *key(name == nil ? @"" : name);
6850 _profile(SectionsView$reloadData$Section)
6851 section = §ions[key];
6852 if (*section == nil) {
6853 _profile(SectionsView$reloadData$Section$Allocate)
6854 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6859 [*section addToCount];
6861 _profile(SectionsView$reloadData$Filter)
6862 if (![package valid] || ![package visible])
6866 [*section addToRow];
6870 _profile(SectionsView$reloadData$Section)
6871 section = [sections objectForKey:key];
6872 if (section == nil) {
6873 _profile(SectionsView$reloadData$Section$Allocate)
6874 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6875 [sections setObject:section forKey:key];
6880 [section addToCount];
6882 _profile(SectionsView$reloadData$Filter)
6883 if (![package valid] || ![package visible])
6893 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6894 [sections_ addObject:i->second];
6896 [sections_ addObjectsFromArray:[sections allValues]];
6899 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6901 for (Section *section in sections_) {
6902 size_t count([section row]);
6906 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6907 [section setCount:count];
6908 [filtered_ addObject:section];
6911 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
6912 initWithTitle:[sections_ count] == 0 ? nil : UCLocalize("EDIT")
6913 style:UIBarButtonItemStylePlain
6915 action:@selector(editButtonClicked)
6917 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] != nil];
6918 [rightItem release];
6924 - (void) resetView {
6926 [self editButtonClicked];
6929 - (void) editButtonClicked {
6930 if ((editing_ = !editing_))
6933 [delegate_ updateData];
6935 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6936 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6937 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6940 - (UIView *) accessoryView {
6946 /* Changes Controller {{{ */
6947 @interface ChangesController : CYViewController <
6948 UITableViewDataSource,
6951 _transient Database *database_;
6952 NSMutableArray *packages_;
6953 NSMutableArray *sections_;
6956 BOOL hasSentFirstLoad_;
6959 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6960 - (void) reloadData;
6964 @implementation ChangesController
6967 [list_ setDelegate:nil];
6968 [list_ setDataSource:nil];
6970 [packages_ release];
6971 [sections_ release];
6976 - (void) viewDidAppear:(BOOL)animated {
6977 [super viewDidAppear:animated];
6978 if (!hasSentFirstLoad_) {
6979 hasSentFirstLoad_ = YES;
6980 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6982 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6986 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6987 NSInteger count([sections_ count]);
6988 return count == 0 ? 1 : count;
6991 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6992 if ([sections_ count] == 0)
6994 return [[sections_ objectAtIndex:section] name];
6997 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6998 if ([sections_ count] == 0)
7000 return [[sections_ objectAtIndex:section] count];
7003 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7004 Section *section([sections_ objectAtIndex:[path section]]);
7005 NSInteger row([path row]);
7006 return [packages_ objectAtIndex:([section row] + row)];
7009 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7010 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7012 cell = [[[PackageCell alloc] init] autorelease];
7013 [cell setPackage:[self packageAtIndexPath:path]];
7017 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7018 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7021 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7022 Package *package([self packageAtIndexPath:path]);
7023 PackageController *view([delegate_ packageController]);
7024 [view setDelegate:delegate_];
7025 [view setPackage:package];
7026 [[self navigationController] pushViewController:view animated:YES];
7030 - (void) refreshButtonClicked {
7031 [delegate_ beginUpdate];
7032 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7035 - (void) upgradeButtonClicked {
7036 [delegate_ distUpgrade];
7039 - (NSString *) title { return UCLocalize("CHANGES"); }
7041 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7042 if ((self = [super init]) != nil) {
7043 database_ = database;
7044 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7046 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
7047 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7049 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7050 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7051 [list_ setRowHeight:73.0f];
7052 [[self view] addSubview:list_];
7054 [list_ setDataSource:self];
7055 [list_ setDelegate:self];
7057 delegate_ = delegate;
7061 - (void) _reloadPackages:(NSArray *)packages {
7063 for (Package *package in packages)
7065 [package uninstalled] && [package valid] && [package visible] ||
7066 [package upgradableAndEssential:YES]
7068 [packages_ addObject:package];
7071 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7075 - (void) reloadData {
7076 NSArray *packages = [database_ packages];
7078 [packages_ removeAllObjects];
7079 [sections_ removeAllObjects];
7081 UIProgressHUD *hud([delegate_ addProgressHUD]);
7083 [hud setText:@"Loading Changes"];
7084 //NSLog(@"HUD:%@::%@", delegate_, hud);
7085 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7086 [delegate_ removeProgressHUD:hud];
7088 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7089 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7090 Section *section = nil;
7094 bool unseens = false;
7096 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7098 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7099 Package *package = [packages_ objectAtIndex:offset];
7101 BOOL uae = [package upgradableAndEssential:YES];
7107 _profile(ChangesController$reloadData$Remember)
7108 seen = [package seen];
7111 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7116 name = UCLocalize("UNKNOWN");
7118 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7122 _profile(ChangesController$reloadData$Allocate)
7123 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7124 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7125 [sections_ addObject:section];
7129 [section addToCount];
7130 } else if ([package ignored])
7131 [ignored addToCount];
7134 [upgradable addToCount];
7139 CFRelease(formatter);
7142 Section *last = [sections_ lastObject];
7143 size_t count = [last count];
7144 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7145 [sections_ removeLastObject];
7148 if ([ignored count] != 0)
7149 [sections_ insertObject:ignored atIndex:0];
7151 [sections_ insertObject:upgradable atIndex:0];
7155 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7156 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7157 style:UIBarButtonItemStylePlain
7159 action:@selector(upgradeButtonClicked)
7161 if (upgrades_ > 0) [[self navigationItem] setRightBarButtonItem:rightItem];
7162 [rightItem release];
7164 UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]
7165 initWithTitle:UCLocalize("REFRESH")
7166 style:UIBarButtonItemStylePlain
7168 action:@selector(refreshButtonClicked)
7170 if (![delegate_ updating]) [[self navigationItem] setLeftBarButtonItem:leftItem];
7176 /* Search Controller {{{ */
7177 @interface SearchController : FilteredPackageController <
7180 UISearchBar *search_;
7183 - (id) initWithDatabase:(Database *)database;
7184 - (void) reloadData;
7188 @implementation SearchController
7195 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7196 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7197 [search_ resignFirstResponder];
7201 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7202 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7206 - (NSString *) title { return nil; }
7208 - (id) initWithDatabase:(Database *)database {
7209 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7212 - (void)viewDidAppear:(BOOL)animated {
7213 [super viewDidAppear:animated];
7215 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7216 [search_ layoutSubviews];
7217 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7218 UITextField *textField = [search_ searchField];
7219 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7220 [search_ setDelegate:self];
7221 [textField setEnablesReturnKeyAutomatically:NO];
7222 [[self navigationItem] setTitleView:textField];
7226 - (void) _reloadData {
7229 - (void) reloadData {
7230 _profile(SearchController$reloadData)
7231 [packages_ reloadData];
7234 [packages_ resetCursor];
7237 - (void) didSelectPackage:(Package *)package {
7238 [search_ resignFirstResponder];
7239 [super didSelectPackage:package];
7244 /* Settings Controller {{{ */
7245 @interface SettingsController : CYViewController <
7246 UITableViewDataSource,
7249 _transient Database *database_;
7252 UITableView *table_;
7253 id subscribedSwitch_;
7255 UITableViewCell *subscribedCell_;
7256 UITableViewCell *ignoredCell_;
7259 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7263 @implementation SettingsController
7267 if (package_ != nil)
7270 [subscribedSwitch_ release];
7271 [ignoredSwitch_ release];
7272 [subscribedCell_ release];
7273 [ignoredCell_ release];
7278 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7279 if (package_ == nil)
7285 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7286 if (package_ == nil)
7292 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7293 return UCLocalize("SHOW_ALL_CHANGES_EX");
7296 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7297 if (package_ == nil)
7300 NSMutableDictionary *metadata([package_ metadata]);
7303 if (NSNumber *number = [metadata objectForKey:key])
7304 before = [number boolValue];
7308 if (value != before) {
7309 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7311 [delegate_ updateData];
7315 - (void) onSubscribed:(id)control {
7316 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7319 - (void) onIgnored:(id)control {
7320 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
7323 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7324 if (package_ == nil)
7327 switch ([indexPath row]) {
7328 case 0: return subscribedCell_;
7329 case 1: return ignoredCell_;
7337 - (NSString *) title { return UCLocalize("SETTINGS"); }
7339 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7340 if ((self = [super init])) {
7341 database_ = database;
7342 name_ = [package retain];
7344 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7346 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7347 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7348 [[self view] addSubview:table_];
7350 subscribedSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7351 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7352 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7354 ignoredSwitch_ = [[objc_getClass("UISwitch") alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7355 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7356 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7358 subscribedCell_ = [[UITableViewCell alloc] init];
7359 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7360 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7361 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7363 ignoredCell_ = [[UITableViewCell alloc] init];
7364 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7365 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7366 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7368 [table_ setDataSource:self];
7369 [table_ setDelegate:self];
7374 - (void) reloadData {
7375 if (package_ != nil)
7376 [package_ autorelease];
7377 package_ = [database_ packageWithName:name_];
7378 if (package_ != nil) {
7380 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7381 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7384 [table_ reloadData];
7389 /* Signature Controller {{{ */
7390 @interface SignatureController : CYBrowserController {
7391 _transient Database *database_;
7395 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7399 @implementation SignatureController
7406 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7408 [super webView:view didClearWindowObject:window forFrame:frame];
7411 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7412 if ((self = [super init]) != nil) {
7413 database_ = database;
7414 package_ = [package retain];
7419 - (void) reloadData {
7420 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7426 /* Role Controller {{{ */
7427 @interface RoleController : CYViewController <
7428 UITableViewDataSource,
7431 _transient Database *database_;
7433 UITableView *table_;
7434 UISegmentedControl *segment_;
7438 - (void) showDoneButton;
7439 - (void) resizeSegmentedControl;
7443 @implementation RoleController
7447 [container_ release];
7452 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7453 if ((self = [super init])) {
7454 database_ = database;
7455 roledelegate_ = delegate;
7457 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7459 NSArray *items = [NSArray arrayWithObjects:
7461 UCLocalize("HACKER"),
7462 UCLocalize("DEVELOPER"),
7464 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7465 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7466 [container_ addSubview:segment_];
7469 if ([Role_ isEqualToString:@"User"]) index = 0;
7470 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7471 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7473 [segment_ setSelectedSegmentIndex:index];
7474 [self showDoneButton];
7477 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7478 [self resizeSegmentedControl];
7480 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7481 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7482 [table_ setDelegate:self];
7483 [table_ setDataSource:self];
7484 [[self view] addSubview:table_];
7485 [table_ reloadData];
7489 - (void) resizeSegmentedControl {
7490 CGFloat width = [[self view] frame].size.width;
7491 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7494 - (void) viewWillAppear:(BOOL)animated {
7495 [super viewWillAppear:animated];
7497 [self resizeSegmentedControl];
7500 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7501 [self resizeSegmentedControl];
7504 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7505 [self resizeSegmentedControl];
7509 NSString *role(nil);
7511 switch ([segment_ selectedSegmentIndex]) {
7512 case 0: role = @"User"; break;
7513 case 1: role = @"Hacker"; break;
7514 case 2: role = @"Developer"; break;
7519 if (![role isEqualToString:Role_]) {
7520 bool rolling(Role_ == nil);
7523 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7527 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7532 [roledelegate_ loadData];
7534 [roledelegate_ updateData];
7538 - (void) segmentChanged:(UISegmentedControl *)control {
7539 [self showDoneButton];
7542 - (void) doneButtonClicked {
7544 [[self navigationController] dismissModalViewControllerAnimated:YES];
7547 - (void) showDoneButton {
7548 UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]
7549 initWithTitle:UCLocalize("DONE")
7550 style:UIBarButtonItemStyleDone
7552 action:@selector(doneButtonClicked)
7554 [[self navigationItem] setRightBarButtonItem:rightItem animated:[[self navigationItem] rightBarButtonItem] == nil];
7555 [rightItem release];
7558 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7559 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7563 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7567 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7568 return nil; // This method is required by the protocol.
7571 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7573 return UCLocalize("ROLE_EX");
7575 return [NSString stringWithFormat:
7576 @"%@: %@\n%@: %@\n%@: %@",
7577 UCLocalize("USER"), UCLocalize("USER_EX"),
7578 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7579 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7584 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7585 if (section == 3) return 44.0f;
7589 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7590 if (section == 3) return container_;
7596 /* Stash Controller {{{ */
7597 @interface CYStashController : CYViewController {
7598 UIActivityIndicatorView *spinner_;
7604 @implementation CYStashController
7606 if ((self = [super init])) {
7607 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7609 spinner_ = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
7610 CGRect spinrect = [spinner_ frame];
7611 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7612 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7613 [spinner_ setFrame:spinrect];
7614 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7615 [[self view] addSubview:spinner_];
7617 [spinner_ startAnimating];
7620 captrect.size.width = [[self view] frame].size.width;
7621 captrect.size.height = 40.0f;
7622 captrect.origin.x = 0;
7623 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7624 caption_ = [[UILabel alloc] initWithFrame:captrect];
7625 [caption_ setText:@"Initializing Filesystem"];
7626 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7627 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7628 [caption_ setTextColor:[UIColor whiteColor]];
7629 [caption_ setBackgroundColor:[UIColor clearColor]];
7630 [caption_ setShadowColor:[UIColor blackColor]];
7631 [caption_ setTextAlignment:UITextAlignmentCenter];
7632 [[self view] addSubview:caption_];
7636 statusrect.size.width = [[self view] frame].size.width;
7637 statusrect.size.height = 30.0f;
7638 statusrect.origin.x = 0;
7639 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7640 status_ = [[UILabel alloc] initWithFrame:statusrect];
7641 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7642 [status_ setText:@"(Cydia will exit when complete.)"];
7643 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7644 [status_ setTextColor:[UIColor whiteColor]];
7645 [status_ setBackgroundColor:[UIColor clearColor]];
7646 [status_ setShadowColor:[UIColor blackColor]];
7647 [status_ setTextAlignment:UITextAlignmentCenter];
7648 [[self view] addSubview:status_];
7653 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7654 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7659 /* Cydia Container {{{ */
7660 @interface CYContainer : UIViewController <ProgressDelegate> {
7661 _transient Database *database_;
7662 RefreshBar *refreshbar_;
7667 UITabBarController *root_;
7670 - (void) setTabBarController:(UITabBarController *)controller;
7672 - (void) dropBar:(BOOL)animated;
7673 - (void) beginUpdate;
7674 - (void) raiseBar:(BOOL)animated;
7679 @implementation CYContainer
7681 - (BOOL) _reallyWantsFullScreenLayout {
7685 // NOTE: UIWindow only sends the top controller these messages,
7686 // So we have to forward them on.
7688 - (void) viewDidAppear:(BOOL)animated {
7689 [super viewDidAppear:animated];
7690 [root_ viewDidAppear:animated];
7693 - (void) viewWillAppear:(BOOL)animated {
7694 [super viewWillAppear:animated];
7695 [root_ viewWillAppear:animated];
7698 - (void) viewDidDisappear:(BOOL)animated {
7699 [super viewDidDisappear:animated];
7700 [root_ viewDidDisappear:animated];
7703 - (void) viewWillDisappear:(BOOL)animated {
7704 [super viewWillDisappear:animated];
7705 [root_ viewWillDisappear:animated];
7708 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7709 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7712 - (void) setTabBarController:(UITabBarController *)controller {
7714 [[self view] addSubview:[root_ view]];
7717 - (void) setUpdate:(NSDate *)date {
7721 - (void) beginUpdate {
7723 [refreshbar_ start];
7728 detachNewThreadSelector:@selector(performUpdate)
7734 - (void) performUpdate { _pooled
7736 status.setDelegate(self);
7737 [database_ updateWithStatus:status];
7740 performSelectorOnMainThread:@selector(completeUpdate)
7746 - (void) completeUpdate {
7747 if (!updating_) return;
7750 [self raiseBar:YES];
7752 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7755 - (void) cancelUpdate {
7757 [self raiseBar:YES];
7759 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7762 - (void) cancelPressed {
7763 [self cancelUpdate];
7770 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7771 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7774 - (void) startProgress {
7777 - (void) setProgressTitle:(NSString *)title {
7779 performSelectorOnMainThread:@selector(_setProgressTitle:)
7785 - (bool) isCancelling:(size_t)received {
7789 - (void) setProgressPercent:(float)percent {
7791 performSelectorOnMainThread:@selector(_setProgressPercent:)
7792 withObject:[NSNumber numberWithFloat:percent]
7797 - (void) addProgressOutput:(NSString *)output {
7799 performSelectorOnMainThread:@selector(_addProgressOutput:)
7805 - (void) _setProgressTitle:(NSString *)title {
7806 [refreshbar_ setPrompt:title];
7809 - (void) _setProgressPercent:(NSNumber *)percent {
7810 [refreshbar_ setProgress:[percent floatValue]];
7813 - (void) _addProgressOutput:(NSString *)output {
7816 - (void) setUpdateDelegate:(id)delegate {
7817 updatedelegate_ = delegate;
7820 - (CGFloat) statusBarHeight {
7821 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7822 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7824 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7828 - (void) dropBar:(BOOL)animated {
7829 if (dropped_) return;
7832 [[self view] addSubview:refreshbar_];
7834 CGFloat sboffset = [self statusBarHeight];
7836 CGRect barframe = [refreshbar_ frame];
7837 barframe.origin.y = sboffset;
7838 [refreshbar_ setFrame:barframe];
7840 if (animated) [UIView beginAnimations:nil context:NULL];
7841 CGRect viewframe = [[root_ view] frame];
7842 viewframe.origin.y += barframe.size.height + sboffset;
7843 viewframe.size.height -= barframe.size.height + sboffset;
7844 [[root_ view] setFrame:viewframe];
7845 if (animated) [UIView commitAnimations];
7847 // Ensure bar has the proper width for our view, it might have changed
7848 barframe.size.width = viewframe.size.width;
7849 [refreshbar_ setFrame:barframe];
7851 // XXX: fix Apple's layout bug
7852 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7855 - (void) raiseBar:(BOOL)animated {
7856 if (!dropped_) return;
7859 [refreshbar_ removeFromSuperview];
7861 CGFloat sboffset = [self statusBarHeight];
7863 if (animated) [UIView beginAnimations:nil context:NULL];
7864 CGRect barframe = [refreshbar_ frame];
7865 CGRect viewframe = [[root_ view] frame];
7866 viewframe.origin.y -= barframe.size.height + sboffset;
7867 viewframe.size.height += barframe.size.height + sboffset;
7868 [[root_ view] setFrame:viewframe];
7869 if (animated) [UIView commitAnimations];
7871 // XXX: fix Apple's layout bug
7872 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7875 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7876 // XXX: fix Apple's layout bug
7877 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7880 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7886 // XXX: fix Apple's layout bug
7887 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7890 - (void) statusBarFrameChanged:(NSNotification *)notification {
7898 [refreshbar_ release];
7899 [[NSNotificationCenter defaultCenter] removeObserver:self];
7903 - (id) initWithDatabase:(Database *)database {
7904 if ((self = [super init]) != nil) {
7905 database_ = database;
7907 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7908 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7910 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7927 @interface Cydia : UIApplication <
7928 ConfirmationControllerDelegate,
7929 ProgressControllerDelegate,
7931 UINavigationControllerDelegate
7934 CYContainer *container_;
7937 NSMutableArray *essential_;
7938 NSMutableArray *broken_;
7940 Database *database_;
7944 UIKeyboard *keyboard_;
7945 UIProgressHUD *hud_;
7947 SectionsController *sections_;
7948 ChangesController *changes_;
7949 ManageController *manage_;
7950 SearchController *search_;
7951 SourceTable *sources_;
7952 InstalledController *installed_;
7955 CYStashController *stash_;
7960 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7961 - (void) setPage:(CYViewController *)page;
7966 static _finline void _setHomePage(Cydia *self) {
7967 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7970 @implementation Cydia
7972 - (void) beginUpdate {
7973 [container_ beginUpdate];
7977 return [container_ updating];
7980 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7985 if ([broken_ count] != 0) {
7986 int count = [broken_ count];
7988 UIAlertView *alert = [[[UIAlertView alloc]
7989 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7990 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7992 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7993 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
7996 [alert setContext:@"fixhalf"];
7998 } else if (!Ignored_ && [essential_ count] != 0) {
7999 int count = [essential_ count];
8001 UIAlertView *alert = [[[UIAlertView alloc]
8002 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8003 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8005 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8006 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8009 [alert setContext:@"upgrade"];
8014 - (void) _saveConfig {
8017 NSString *error(nil);
8018 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8020 NSError *error(nil);
8021 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8022 NSLog(@"failure to save metadata data: %@", error);
8025 NSLog(@"failure to serialize metadata: %@", error);
8033 - (void) _updateData {
8036 /* XXX: this is just stupid */
8037 if (tag_ != 1 && sections_ != nil)
8038 [sections_ reloadData];
8039 if (tag_ != 2 && changes_ != nil)
8040 [changes_ reloadData];
8041 if (tag_ != 4 && search_ != nil)
8042 [search_ reloadData];
8044 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8047 - (int)indexOfTabWithTag:(int)tag {
8049 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8050 if ([[controller tabBarItem] tag] == tag) return i;
8057 - (void) _refreshIfPossible {
8058 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8060 bool recently = false;
8061 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8062 if (update != nil) {
8063 NSTimeInterval interval([update timeIntervalSinceNow]);
8064 if (interval <= 0 && interval > -(15*60))
8068 // Don't automatic refresh if:
8069 // - We already refreshed recently.
8070 // - We already auto-refreshed this launch.
8071 // - Auto-refresh is disabled.
8072 if (recently || loaded_ || ManualRefresh) {
8073 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8075 // If we are cancelling due to ManualRefresh or a recent refresh
8076 // we need to make sure it knows it's already loaded.
8080 // We are going to load, so remember that.
8084 SCNetworkReachabilityFlags flags; {
8085 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8086 SCNetworkReachabilityGetFlags(reachability, &flags);
8087 CFRelease(reachability);
8090 // XXX: this elaborate mess is what Apple is using to determine this? :(
8091 // XXX: do we care if the user has to intervene? maybe that's ok?
8093 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8094 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8095 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8096 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8097 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8098 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8102 // If we can reach the server, auto-refresh!
8104 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8109 - (void) refreshIfPossible {
8110 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8113 - (void) _reloadData {
8114 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8115 [hud setText:UCLocalize("RELOADING_DATA")];
8117 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8120 if (hud) [self removeProgressHUD:hud];
8124 [essential_ removeAllObjects];
8125 [broken_ removeAllObjects];
8127 NSArray *packages([database_ packages]);
8128 for (Package *package in packages) {
8130 [broken_ addObject:package];
8131 if ([package upgradableAndEssential:NO]) {
8132 if ([package essential])
8133 [essential_ addObject:package];
8138 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8140 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8141 [changesItem setBadgeValue:badge];
8142 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8144 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8145 [self setApplicationBadge:badge];
8147 [self setApplicationBadgeString:badge];
8149 [changesItem setBadgeValue:nil];
8150 [changesItem setAnimatedBadge:NO];
8152 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8153 [self removeApplicationBadge];
8154 else // XXX: maybe use setApplicationBadgeString also?
8155 [self setApplicationIconBadgeNumber:0];
8160 [self refreshIfPossible];
8163 - (void) updateData {
8164 [database_ setVisible];
8173 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8174 _assert(file != NULL);
8176 for (NSString *key in [Sources_ allKeys]) {
8177 NSDictionary *source([Sources_ objectForKey:key]);
8179 fprintf(file, "%s %s %s\n",
8180 [[source objectForKey:@"Type"] UTF8String],
8181 [[source objectForKey:@"URI"] UTF8String],
8182 [[source objectForKey:@"Distribution"] UTF8String]
8190 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8191 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8192 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8193 [container_ presentModalViewController:navigation animated:YES];
8196 detachNewThreadSelector:@selector(update_)
8199 title:UCLocalize("UPDATING_SOURCES")
8203 - (void) reloadData {
8204 @synchronized (self) {
8210 pkgProblemResolver *resolver = [database_ resolver];
8212 resolver->InstallProtect();
8213 if (!resolver->Resolve(true))
8217 - (CGRect) popUpBounds {
8218 return [[tabbar_ view] bounds];
8222 if (![database_ prepare])
8225 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8226 [page setDelegate:self];
8227 CYNavigationController *confirm_ = [[CYNavigationController alloc] initWithRootViewController:page];
8228 [confirm_ setDelegate:self];
8230 if (IsWildcat_) [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8231 [container_ presentModalViewController:confirm_ animated:YES];
8237 @synchronized (self) {
8242 - (void) clearPackage:(Package *)package {
8243 @synchronized (self) {
8250 - (void) installPackages:(NSArray *)packages {
8251 @synchronized (self) {
8252 for (Package *package in packages)
8259 - (void) installPackage:(Package *)package {
8260 @synchronized (self) {
8267 - (void) removePackage:(Package *)package {
8268 @synchronized (self) {
8275 - (void) distUpgrade {
8276 @synchronized (self) {
8277 if (![database_ upgrade])
8284 @synchronized (self) {
8289 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8290 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8292 if (navigation != nil) {
8293 [navigation pushViewController:progress animated:YES];
8295 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8296 if (IsWildcat_) [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8297 [container_ presentModalViewController:navigation animated:YES];
8301 detachNewThreadSelector:@selector(perform)
8304 title:UCLocalize("RUNNING")
8308 - (void) progressControllerIsComplete:(ProgressController *)progress {
8312 - (void) setPage:(CYViewController *)page {
8313 [page setDelegate:self];
8315 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8316 [navController setViewControllers:[NSArray arrayWithObject:page]];
8317 for (CYNavigationController *page in [tabbar_ viewControllers]) {
8318 if (page != navController) [page setViewControllers:nil];
8322 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8323 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8324 [browser loadURL:url];
8328 - (SectionsController *) sectionsController {
8329 if (sections_ == nil)
8330 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8334 - (ChangesController *) changesController {
8335 if (changes_ == nil)
8336 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8340 - (ManageController *) manageController {
8341 if (manage_ == nil) {
8342 manage_ = (ManageController *) [[self
8343 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8344 withClass:[ManageController class]
8346 if (!IsWildcat_) queueDelegate_ = manage_;
8351 - (SearchController *) searchController {
8353 search_ = [[SearchController alloc] initWithDatabase:database_];
8357 - (SourceTable *) sourcesController {
8358 if (sources_ == nil)
8359 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8363 - (InstalledController *) installedController {
8364 if (installed_ == nil) {
8365 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8366 if (IsWildcat_) queueDelegate_ = installed_;
8371 - (void) tabBarController:(id)tabBarController didSelectViewController:(UIViewController *)viewController {
8372 int tag = [[viewController tabBarItem] tag];
8374 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8376 } else if (tag_ == 1) {
8377 [[self sectionsController] resetView];
8381 case kCydiaTag: _setHomePage(self); break;
8383 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8384 case kChangesTag: [self setPage:[self changesController]]; break;
8385 case kManageTag: [self setPage:[self manageController]]; break;
8386 case kInstalledTag: [self setPage:[self installedController]]; break;
8387 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8388 case kSearchTag: [self setPage:[self searchController]]; break;
8396 - (void) showSettings {
8397 RoleController *role = [[RoleController alloc] initWithDatabase:database_ delegate:self];
8398 CYNavigationController *nav = [[CYNavigationController alloc] initWithRootViewController:role];
8399 if (IsWildcat_) [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8400 [container_ presentModalViewController:nav animated:YES];
8403 - (void) setPackageController:(PackageController *)view {
8405 [view setPackage:nil];
8409 - (PackageController *) _packageController {
8410 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8413 - (PackageController *) packageController {
8414 return [self _packageController];
8417 // Returns the navigation controller for the queuing badge.
8418 - (id) queueBadgeController {
8419 int index = [self indexOfTabWithTag:kManageTag];
8420 if (index == -1) index = [self indexOfTabWithTag:kInstalledTag];
8422 return [[tabbar_ viewControllers] objectAtIndex:index];
8425 - (void) cancelAndClear:(bool)clear {
8426 @synchronized (self) {
8429 pkgCacheFile &cache([database_ cache]);
8430 for (pkgCache::PkgIterator iterator = cache->PkgBegin(); !iterator.end(); ++iterator) {
8431 // Unmark method taken from Synaptic Package Manager.
8432 // Thanks for being sane, unlike Aptitude.
8433 if (!cache[iterator].Keep()) {
8434 cache->MarkKeep(iterator, false);
8435 cache->SetReInstall(iterator, false);
8441 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
8445 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8448 // Show the changes in the current view.
8449 [(CYNavigationController *) [tabbar_ selectedViewController] reloadData];
8450 [queueDelegate_ queueStatusDidChange];
8454 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8455 NSString *context([alert context]);
8457 if ([context isEqualToString:@"fixhalf"]) {
8458 if (button == [alert firstOtherButtonIndex]) {
8459 @synchronized (self) {
8460 for (Package *broken in broken_) {
8463 NSString *id = [broken id];
8464 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8465 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8466 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8467 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8473 } else if (button == [alert cancelButtonIndex]) {
8474 [broken_ removeAllObjects];
8478 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8479 } else if ([context isEqualToString:@"upgrade"]) {
8480 if (button == [alert firstOtherButtonIndex]) {
8481 @synchronized (self) {
8482 for (Package *essential in essential_)
8483 [essential install];
8488 } else if (button == [alert firstOtherButtonIndex] + 1) {
8490 } else if (button == [alert cancelButtonIndex]) {
8494 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8498 - (void) system:(NSString *)command { _pooled
8499 system([command UTF8String]);
8502 - (void) applicationWillSuspend {
8504 [super applicationWillSuspend];
8507 - (void) applicationSuspend:(__GSEvent *)event {
8508 // Use external process status API internally.
8509 // This is probably a really bad idea.
8510 uint64_t status = 0;
8512 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8513 notify_get_state(notify_token, &status);
8514 notify_cancel(notify_token);
8517 if (hud_ == nil && status == 0)
8518 [super applicationSuspend:event];
8521 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8523 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8526 - (void) _setSuspended:(BOOL)value {
8528 [super _setSuspended:value];
8531 - (UIProgressHUD *) addProgressHUD {
8532 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8533 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8535 [window_ setUserInteractionEnabled:NO];
8538 UIViewController *target = container_;
8539 while ([target modalViewController] != nil) target = [target modalViewController];
8540 [[target view] addSubview:hud];
8545 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8547 [hud removeFromSuperview];
8548 [window_ setUserInteractionEnabled:YES];
8551 - (CYViewController *) pageForPackage:(NSString *)name {
8552 if (Package *package = [database_ packageWithName:name]) {
8553 PackageController *view([self packageController]);
8554 [view setPackage:package];
8557 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8558 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8559 return [self _pageForURL:url withClass:[CYBrowserController class]];
8563 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8567 NSString *href([url absoluteString]);
8568 if ([href hasPrefix:@"apptapp://package/"])
8569 return [self pageForPackage:[href substringFromIndex:18]];
8571 NSString *scheme([[url scheme] lowercaseString]);
8572 if (![scheme isEqualToString:@"cydia"])
8574 NSString *path([url absoluteString]);
8575 if ([path length] < 8)
8577 path = [path substringFromIndex:8];
8578 if (![path hasPrefix:@"/"])
8579 path = [@"/" stringByAppendingString:path];
8581 if ([path isEqualToString:@"/add-source"])
8582 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8583 else if ([path isEqualToString:@"/storage"])
8584 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8585 else if ([path isEqualToString:@"/sources"])
8586 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8587 else if ([path isEqualToString:@"/packages"])
8588 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8589 else if ([path hasPrefix:@"/url/"])
8590 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8591 else if ([path hasPrefix:@"/launch/"])
8592 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8593 else if ([path hasPrefix:@"/package-settings/"])
8594 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8595 else if ([path hasPrefix:@"/package-signature/"])
8596 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8597 else if ([path hasPrefix:@"/package/"])
8598 return [self pageForPackage:[path substringFromIndex:9]];
8599 else if ([path hasPrefix:@"/files/"]) {
8600 NSString *name = [path substringFromIndex:7];
8602 if (Package *package = [database_ packageWithName:name]) {
8603 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8604 [files setPackage:package];
8612 - (void) applicationOpenURL:(NSURL *)url {
8613 [super applicationOpenURL:url];
8615 if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
8616 [self setPage:page];
8618 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8622 - (void) applicationWillResignActive:(UIApplication *)application {
8623 // Stop refreshing if you get a phone call or lock the device.
8624 if ([container_ updating]) [container_ cancelUpdate];
8626 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8627 [super applicationWillResignActive:application];
8630 - (void) addStashController {
8631 stash_ = [[CYStashController alloc] init];
8632 [window_ addSubview:[stash_ view]];
8635 - (void) removeStashController {
8636 [[stash_ view] removeFromSuperview];
8641 [self setIdleTimerDisabled:YES];
8643 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8644 [self setStatusBarShowsProgress:YES];
8645 UpdateExternalStatus(1);
8647 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8649 UpdateExternalStatus(0);
8650 [self setStatusBarShowsProgress:NO];
8652 [self removeStashController];
8654 if (ExecFork() == 0) {
8655 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8656 perror("launchctl stop");
8660 - (void) setupTabBarController {
8661 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8662 [tabbar_ setDelegate:self];
8664 NSMutableArray *items([NSMutableArray arrayWithObjects:
8665 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8666 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8667 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8668 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8672 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8673 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8675 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8678 NSMutableArray *controllers([NSMutableArray array]);
8680 for (UITabBarItem *item in items) {
8681 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8682 [controller setTabBarItem:item];
8683 [controllers addObject:controller];
8686 [tabbar_ setViewControllers:controllers];
8687 [tabbar_ setSelectedIndex:0];
8690 - (void) applicationDidFinishLaunching:(id)unused {
8691 [CYBrowserController _initialize];
8693 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8695 Font12_ = [[UIFont systemFontOfSize:12] retain];
8696 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8697 Font14_ = [[UIFont systemFontOfSize:14] retain];
8698 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8699 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8703 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8704 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8706 UIScreen *screen([UIScreen mainScreen]);
8708 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8709 [window_ orderFront:self];
8710 [window_ makeKey:self];
8711 [window_ setHidden:NO];
8714 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8715 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8716 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8717 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8718 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8719 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8720 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8721 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8722 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8725 [self addStashController];
8726 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8730 database_ = [Database sharedInstance];
8732 [self setupTabBarController];
8734 container_ = [[CYContainer alloc] initWithDatabase:database_];
8735 [container_ setUpdateDelegate:self];
8736 [container_ setTabBarController:tabbar_];
8737 [window_ addSubview:[container_ view]];
8739 // Show pinstripes while loading data.
8740 [[container_ view] setBackgroundColor:[UIColor performSelector:@selector(pinStripeColor)]];
8742 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8747 [self showSettings];
8751 [UIKeyboard initImplementationNow];
8753 [window_ setUserInteractionEnabled:NO];
8755 UIView *container = [[UIView alloc] init];
8756 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8758 UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
8759 [spinner startAnimating];
8760 [container addSubview:spinner];
8763 UILabel *label = [[UILabel alloc] init];
8764 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8765 [label setBackgroundColor:[UIColor clearColor]];
8766 [label setTextColor:[UIColor blackColor]];
8767 [label setShadowColor:[UIColor whiteColor]];
8768 [label setShadowOffset:CGSizeMake(0, 1)];
8769 [label setText:UCLocalize("LOADING_DATA")];
8770 [container addSubview:label];
8773 CGSize viewsize = [[tabbar_ view] frame].size;
8774 CGSize spinnersize = [spinner bounds].size;
8775 CGSize textsize = [[label text] sizeWithFont:[label font]];
8776 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8778 CGRect containrect = {
8779 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8780 CGSizeMake(bothwidth, spinnersize.height)
8783 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8791 [container setFrame:containrect];
8792 [spinner setFrame:spinrect];
8793 [label setFrame:textrect];
8794 [[container_ view] addSubview:container];
8795 [container release];
8800 // Show the home page
8802 [window_ setUserInteractionEnabled:YES];
8804 // XXX: does this actually slow anything down?
8805 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8806 [container removeFromSuperview];
8809 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8810 if (item != nil && IsWildcat_) {
8811 [sheet showFromBarButtonItem:item animated:YES];
8813 [sheet showInView:window_];
8820 id Alloc_(id self, SEL selector) {
8821 id object = alloc_(self, selector);
8822 lprintf("[%s]A-%p\n", self->isa->name, object);
8827 id Dealloc_(id self, SEL selector) {
8828 id object = dealloc_(self, selector);
8829 lprintf("[%s]D-%p\n", self->isa->name, object);
8833 Class $WebDefaultUIKitDelegate;
8835 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8836 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8837 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8838 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8841 static NSNumber *shouldPlayKeyboardSounds;
8845 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8847 case 1104: // Keyboard Button Clicked
8848 case 1105: // Keyboard Delete Repeated
8849 if (shouldPlayKeyboardSounds == nil) {
8850 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8851 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8854 if (![shouldPlayKeyboardSounds boolValue])
8858 _UIHardware$_playSystemSound$(self, _cmd, sound);
8862 int main(int argc, char *argv[]) { _pooled
8865 if (Class $UIDevice = objc_getClass("UIDevice")) {
8866 UIDevice *device([$UIDevice currentDevice]);
8867 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8871 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8873 /* Library Hacks {{{ */
8874 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8876 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8877 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8878 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8879 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8880 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8883 $UIHardware = objc_getClass("UIHardware");
8884 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8885 if (UIHardware$_playSystemSound$ != NULL) {
8886 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8887 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8890 /* Set Locale {{{ */
8891 Locale_ = CFLocaleCopyCurrent();
8892 Languages_ = [NSLocale preferredLanguages];
8893 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8894 //NSLog(@"%@", [Languages_ description]);
8897 if (Languages_ == nil || [Languages_ count] == 0)
8898 // XXX: consider just setting to C and then falling through?
8901 lang = [[Languages_ objectAtIndex:0] UTF8String];
8902 setenv("LANG", lang, true);
8905 //std::setlocale(LC_ALL, lang);
8906 NSLog(@"Setting Language: %s", lang);
8909 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8911 /* Parse Arguments {{{ */
8912 bool substrate(false);
8918 for (int argi(1); argi != argc; ++argi)
8919 if (strcmp(argv[argi], "--") == 0) {
8921 argv[argi] = argv[0];
8927 for (int argi(1); argi != arge; ++argi)
8928 if (strcmp(args[argi], "--substrate") == 0)
8931 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8935 App_ = [[NSBundle mainBundle] bundlePath];
8936 Home_ = NSHomeDirectory();
8942 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8943 alloc_ = alloc->method_imp;
8944 alloc->method_imp = (IMP) &Alloc_;*/
8946 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8947 dealloc_ = dealloc->method_imp;
8948 dealloc->method_imp = (IMP) &Dealloc_;*/
8950 /* System Information {{{ */
8954 size = sizeof(maxproc);
8955 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8956 perror("sysctlbyname(\"kern.maxproc\", ?)");
8957 else if (maxproc < 64) {
8959 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8960 perror("sysctlbyname(\"kern.maxproc\", #)");
8963 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8964 char *osversion = new char[size];
8965 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8966 perror("sysctlbyname(\"kern.osversion\", ?)");
8968 System_ = [NSString stringWithUTF8String:osversion];
8970 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8971 char *machine = new char[size];
8972 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8973 perror("sysctlbyname(\"hw.machine\", ?)");
8977 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8978 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8979 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8980 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8984 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8985 NSData *data((NSData *) ecid);
8986 size_t length([data length]);
8987 uint8_t bytes[length];
8988 [data getBytes:bytes];
8989 char string[length * 2 + 1];
8990 for (size_t i(0); i != length; ++i)
8991 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8992 ChipID_ = [NSString stringWithUTF8String:string];
8996 IOObjectRelease(service);
9000 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9002 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9003 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9004 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9006 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9007 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9008 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9010 if (mcc != NULL && mnc != NULL)
9011 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9018 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9019 Build_ = [system objectForKey:@"ProductBuildVersion"];
9020 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9021 Product_ = [info objectForKey:@"SafariProductVersion"];
9022 Safari_ = [info objectForKey:@"CFBundleVersion"];
9025 /* Load Database {{{ */
9027 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9029 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9032 if (Metadata_ == NULL)
9033 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9035 Settings_ = [Metadata_ objectForKey:@"Settings"];
9037 Packages_ = [Metadata_ objectForKey:@"Packages"];
9038 Sections_ = [Metadata_ objectForKey:@"Sections"];
9039 Sources_ = [Metadata_ objectForKey:@"Sources"];
9041 Token_ = [Metadata_ objectForKey:@"Token"];
9044 if (Settings_ != nil)
9045 Role_ = [Settings_ objectForKey:@"Role"];
9047 if (Packages_ == nil) {
9048 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
9049 [Metadata_ setObject:Packages_ forKey:@"Packages"];
9052 if (Sections_ == nil) {
9053 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9054 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9057 if (Sources_ == nil) {
9058 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9059 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9063 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9065 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9066 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9067 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9068 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9069 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9070 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9072 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9074 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9075 unlink("/tmp/.cydia.fw");
9077 } else if (access("/User", F_OK) != 0 || version < 2) {
9080 system("/usr/libexec/cydia/firmware.sh");
9084 _assert([[NSFileManager defaultManager]
9085 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9086 withIntermediateDirectories:YES
9091 if (access("/tmp/cydia.chk", F_OK) == 0) {
9092 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9093 _assert(errno == ENOENT);
9094 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9095 _assert(errno == ENOENT);
9098 /* APT Initialization {{{ */
9099 _assert(pkgInitConfig(*_config));
9100 _assert(pkgInitSystem(*_config, _system));
9103 _config->Set("APT::Acquire::Translation", lang);
9105 // XXX: this timeout might be important :(
9106 //_config->Set("Acquire::http::Timeout", 15);
9108 _config->Set("Acquire::http::MaxParallel", 3);
9110 /* Color Choices {{{ */
9111 space_ = CGColorSpaceCreateDeviceRGB();
9113 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9114 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9115 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9116 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9117 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9118 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9119 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9120 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9121 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9123 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9124 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9126 /* UIKit Configuration {{{ */
9127 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9128 if ($GSFontSetUseLegacyFontMetrics != NULL)
9129 $GSFontSetUseLegacyFontMetrics(YES);
9131 // XXX: I have a feeling this was important
9132 //UIKeyboardDisableAutomaticAppearance();
9135 Colon_ = UCLocalize("COLON_DELIMITED");
9136 Error_ = UCLocalize("ERROR");
9137 Warning_ = UCLocalize("WARNING");
9140 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9142 CGColorSpaceRelease(space_);