1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2010 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "UICaboodle/UCPlatform.h"
45 #include "UICaboodle/UCLocalize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
111 #include <mach-o/nlist.h>
121 #include "UICaboodle/BrowserView.h"
123 #include "substrate.h"
130 #define _timestamp ({ \
132 gettimeofday(&tv, NULL); \
133 tv.tv_sec * 1000000 + tv.tv_usec; \
136 typedef std::vector<class ProfileTime *> TimeList;
146 ProfileTime(const char *name) :
150 times_.push_back(this);
153 void AddTime(uint64_t time) {
160 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
172 ProfileTimer(ProfileTime &time) :
179 time_.AddTime(_timestamp - start_);
184 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
186 std::cerr << "========" << std::endl;
189 #define _profile(name) { \
190 static ProfileTime name(#name); \
191 ProfileTimer _ ## name(name);
196 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
198 #define CYPoolStart() \
199 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
201 #define CYPoolEnd() \
205 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
207 void NSLogPoint(const char *fix, const CGPoint &point) {
208 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
211 void NSLogRect(const char *fix, const CGRect &rect) {
212 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
215 static _finline NSString *CydiaURL(NSString *path) {
217 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
218 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
219 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
220 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
221 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
222 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
225 static _finline void UpdateExternalStatus(uint64_t newStatus) {
227 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
228 notify_set_state(notify_token, newStatus);
229 notify_cancel(notify_token);
231 notify_post("com.saurik.Cydia.status");
234 /* [NSObject yieldToSelector:(withObject:)] {{{*/
235 @interface NSObject (Cydia)
236 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
237 - (id) yieldToSelector:(SEL)selector;
240 @implementation NSObject (Cydia)
245 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
246 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
247 id object([[context objectAtIndex:1] nonretainedObjectValue]);
248 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
250 /* XXX: deal with exceptions */
251 id value([self performSelector:selector withObject:object]);
253 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
254 [context removeAllObjects];
255 if ([signature methodReturnLength] != 0 && value != nil)
256 [context addObject:value];
261 performSelectorOnMainThread:@selector(doNothing)
267 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
268 /*return [self performSelector:selector withObject:object];*/
270 volatile bool stopped(false);
272 NSMutableArray *context([NSMutableArray arrayWithObjects:
273 [NSValue valueWithPointer:selector],
274 [NSValue valueWithNonretainedObject:object],
275 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
278 NSThread *thread([[[NSThread alloc]
280 selector:@selector(_yieldToContext:)
286 NSRunLoop *loop([NSRunLoop currentRunLoop]);
287 NSDate *future([NSDate distantFuture]);
289 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
291 return [context count] == 0 ? nil : [context objectAtIndex:0];
294 - (id) yieldToSelector:(SEL)selector {
295 return [self yieldToSelector:selector withObject:nil];
301 /* Cydia Action Sheet {{{ */
302 @interface CYActionSheet : UIAlertView {
306 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
309 @implementation CYActionSheet
311 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
312 if ((self = [super init])) {
313 [self setTitle:title];
314 [self setDelegate:self];
315 for (NSString *button in buttons) [self addButtonWithTitle:button];
316 [self setCancelButtonIndex:index];
320 - (void) _updateFrameForDisplay {
321 [super _updateFrameForDisplay];
322 if ([self cancelButtonIndex] == -1) {
323 NSArray *buttons = [self buttons];
324 if ([buttons count]) {
325 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
326 for (UIThreePartButton *button in buttons)
327 [button setBackground:background forState:0];
332 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
333 button_ = buttonIndex + 1;
337 [self dismissWithClickedButtonIndex:-1 animated:YES];
340 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
341 [self setRunsModal:YES];
350 /* NSForcedOrderingSearch doesn't work on the iPhone */
351 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
352 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
353 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
355 /* Information Dictionaries {{{ */
356 @interface NSMutableArray (Cydia)
357 - (void) addInfoDictionary:(NSDictionary *)info;
360 @implementation NSMutableArray (Cydia)
362 - (void) addInfoDictionary:(NSDictionary *)info {
363 [self addObject:info];
368 @interface NSMutableDictionary (Cydia)
369 - (void) addInfoDictionary:(NSDictionary *)info;
372 @implementation NSMutableDictionary (Cydia)
374 - (void) addInfoDictionary:(NSDictionary *)info {
375 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
381 #define lprintf(args...) fprintf(stderr, args)
384 #define TraceLogging (1 && !ForRelease)
385 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
386 #define ProfileTimes (0 && !ForRelease)
387 #define ForSaurik (0 && !ForRelease)
388 #define LogBrowser (0 && !ForRelease)
389 #define TrackResize (0 && !ForRelease)
390 #define ManualRefresh (1 && !ForRelease)
391 #define ShowInternals (0 && !ForRelease)
392 #define IgnoreInstall (0 && !ForRelease)
393 #define AlwaysReload (0 && !ForRelease)
397 #define _trace(args...)
402 #define _profile(name) {
405 #define PrintTimes() do {} while (false)
409 typedef uint32_t (*SKRadixFunction)(id, void *);
411 @interface NSMutableArray (Radix)
412 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
420 @implementation NSMutableArray (Radix)
422 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
423 size_t count([self count]);
424 struct RadixItem_ *swap(new RadixItem_[count * 2]);
426 for (size_t i(0); i != count; ++i) {
427 RadixItem_ &item(swap[i]);
430 id object([self objectAtIndex:i]);
431 item.key = function(object, argument);
434 struct RadixItem_ *lhs(swap), *rhs(swap + count);
436 static const size_t width = 32;
437 static const size_t bits = 11;
438 static const size_t slots = 1 << bits;
439 static const size_t passes = (width + (bits - 1)) / bits;
441 size_t *hist(new size_t[slots]);
443 for (size_t pass(0); pass != passes; ++pass) {
444 memset(hist, 0, sizeof(size_t) * slots);
446 for (size_t i(0); i != count; ++i) {
447 uint32_t key(lhs[i].key);
449 key &= _not(uint32_t) >> width - bits;
454 for (size_t i(0); i != slots; ++i) {
455 size_t local(offset);
460 for (size_t i(0); i != count; ++i) {
461 uint32_t key(lhs[i].key);
463 key &= _not(uint32_t) >> width - bits;
464 rhs[hist[key]++] = lhs[i];
467 RadixItem_ *tmp(lhs);
474 const void **values(new const void *[count]);
475 for (size_t i(0); i != count; ++i)
476 values[i] = [self objectAtIndex:lhs[i].index];
477 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
485 /* Insertion Sort {{{ */
487 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
488 const char *ptr = (const char *)list;
490 CFIndex half = count / 2;
491 const char *probe = ptr + elementSize * half;
492 CFComparisonResult cr = comparator(element, probe, context);
493 if (0 == cr) return (probe - (const char *)list) / elementSize;
494 ptr = (cr < 0) ? ptr : probe + elementSize;
495 count = (cr < 0) ? half : (half + (count & 1) - 1);
497 return (ptr - (const char *)list) / elementSize;
500 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
501 const char *ptr = (const char *)list;
503 CFIndex half = count / 2;
504 const char *probe = ptr + elementSize * half;
505 CFComparisonResult cr = comparator(element, probe, context);
506 if (0 == cr) return (probe - (const char *)list) / elementSize;
507 ptr = (cr < 0) ? ptr : probe + elementSize;
508 count = (cr < 0) ? half : (half + (count & 1) - 1);
510 return (ptr - (const char *)list) / elementSize;
513 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
514 if (range.length == 0)
516 const void **values(new const void *[range.length]);
517 CFArrayGetValues(array, range, values);
519 #if HistogramInsertionSort > 0
520 uint32_t total(0), *offsets(new uint32_t[range.length]);
523 for (CFIndex index(1); index != range.length; ++index) {
524 const void *value(values[index]);
525 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
526 CFIndex correct(index);
527 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
528 #if HistogramInsertionSort > 1
529 NSLog(@"%@ < %@", value, values[correct - 1]);
534 if (correct != index) {
535 size_t offset(index - correct);
536 #if HistogramInsertionSort
540 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
542 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
543 values[correct] = value;
547 CFArrayReplaceValues(array, range, values, range.length);
550 #if HistogramInsertionSort > 0
551 for (CFIndex index(0); index != range.length; ++index)
552 if (offsets[index] != 0)
553 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
554 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
561 /* Apple Bug Fixes {{{ */
562 @implementation UIWebDocumentView (Cydia)
564 - (void) _setScrollerOffset:(CGPoint)offset {
565 UIScroller *scroller([self _scroller]);
567 CGSize size([scroller contentSize]);
568 CGSize bounds([scroller bounds].size);
571 max.x = size.width - bounds.width;
572 max.y = size.height - bounds.height;
580 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
581 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
583 [scroller setOffset:offset];
589 @implementation WebScriptObject (NSFastEnumeration)
591 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
592 size_t length([self count] - state->state);
595 else if (length > count)
597 for (size_t i(0); i != length; ++i)
598 objects[i] = [self objectAtIndex:state->state++];
599 state->itemsPtr = objects;
600 state->mutationsPtr = (unsigned long *) self;
606 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
607 size_t length([self length] - state->state);
610 else if (length > count)
612 for (size_t i(0); i != length; ++i)
613 objects[i] = [self item:state->state++];
614 state->itemsPtr = objects;
615 state->mutationsPtr = (unsigned long *) self;
619 /* Cydia NSString Additions {{{ */
620 @interface NSString (Cydia)
621 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
622 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
623 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
624 - (NSComparisonResult) compareByPath:(NSString *)other;
625 - (NSString *) stringByCachingURLWithCurrentCDN;
626 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
629 @implementation NSString (Cydia)
631 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
632 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
635 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
636 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
637 memcpy(data, bytes, length);
638 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
641 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
642 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
645 - (NSComparisonResult) compareByPath:(NSString *)other {
646 NSString *prefix = [self commonPrefixWithString:other options:0];
647 size_t length = [prefix length];
649 NSRange lrange = NSMakeRange(length, [self length] - length);
650 NSRange rrange = NSMakeRange(length, [other length] - length);
652 lrange = [self rangeOfString:@"/" options:0 range:lrange];
653 rrange = [other rangeOfString:@"/" options:0 range:rrange];
655 NSComparisonResult value;
657 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
658 value = NSOrderedSame;
659 else if (lrange.location == NSNotFound)
660 value = NSOrderedAscending;
661 else if (rrange.location == NSNotFound)
662 value = NSOrderedDescending;
664 value = NSOrderedSame;
666 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
667 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
668 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
669 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
671 NSComparisonResult result = [lpath compare:rpath];
672 return result == NSOrderedSame ? value : result;
675 - (NSString *) stringByCachingURLWithCurrentCDN {
677 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
678 withString:@"://cache.cydia.saurik.com/"
682 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
683 return [(id)CFURLCreateStringByAddingPercentEscapes(
688 kCFStringEncodingUTF8
695 /* C++ NSString Wrapper Cache {{{ */
696 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
697 return size == 0 ? NULL :
698 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
699 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
702 static _finline CFStringRef CYStringCreate(const char *data) {
703 return CYStringCreate(data, strlen(data));
712 _finline void clear_() {
713 if (cache_ != NULL) {
720 _finline bool empty() const {
724 _finline size_t size() const {
728 _finline char *data() const {
732 _finline void clear() {
737 _finline CYString() :
744 _finline ~CYString() {
748 void operator =(const CYString &rhs) {
752 if (rhs.cache_ == nil)
755 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
758 void set(apr_pool_t *pool, const char *data, size_t size) {
764 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
765 memcpy(temp, data, size);
772 _finline void set(apr_pool_t *pool, const char *data) {
773 set(pool, data, data == NULL ? 0 : strlen(data));
776 _finline void set(apr_pool_t *pool, const std::string &rhs) {
777 set(pool, rhs.data(), rhs.size());
780 bool operator ==(const CYString &rhs) const {
781 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
784 _finline operator CFStringRef() {
786 cache_ = CYStringCreate(data_, size_);
790 _finline operator id() {
791 return (NSString *) static_cast<CFStringRef>(*this);
794 _finline operator const char *() {
795 return reinterpret_cast<const char *>(data_);
799 /* C++ NSString Algorithm Adapters {{{ */
801 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
804 struct NSStringMapHash :
805 std::unary_function<NSString *, size_t>
807 _finline size_t operator ()(NSString *value) const {
808 return CFStringHashNSString((CFStringRef) value);
812 struct NSStringMapLess :
813 std::binary_function<NSString *, NSString *, bool>
815 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
816 return [lhs compare:rhs] == NSOrderedAscending;
820 struct NSStringMapEqual :
821 std::binary_function<NSString *, NSString *, bool>
823 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
824 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
825 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
826 //[lhs isEqualToString:rhs];
831 /* Perl-Compatible RegEx {{{ */
841 Pcre(const char *regex) :
846 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
849 lprintf("%d:%s\n", offset, error);
853 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
854 matches_ = new int[(capture_ + 1) * 3];
862 NSString *operator [](size_t match) {
863 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
866 bool operator ()(NSString *data) {
867 // XXX: length is for characters, not for bytes
868 return operator ()([data UTF8String], [data length]);
871 bool operator ()(const char *data, size_t size) {
873 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
877 /* Mime Addresses {{{ */
878 @interface Address : NSObject {
884 - (NSString *) address;
886 - (void) setAddress:(NSString *)address;
888 + (Address *) addressWithString:(NSString *)string;
889 - (Address *) initWithString:(NSString *)string;
892 @implementation Address
901 - (NSString *) name {
905 - (NSString *) address {
909 - (void) setAddress:(NSString *)address {
911 [address_ autorelease];
915 address_ = [address retain];
918 + (Address *) addressWithString:(NSString *)string {
919 return [[[Address alloc] initWithString:string] autorelease];
922 + (NSArray *) _attributeKeys {
923 return [NSArray arrayWithObjects:@"address", @"name", nil];
926 - (NSArray *) attributeKeys {
927 return [[self class] _attributeKeys];
930 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
931 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
934 - (Address *) initWithString:(NSString *)string {
935 if ((self = [super init]) != nil) {
936 const char *data = [string UTF8String];
937 size_t size = [string length];
939 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
941 if (address_r(data, size)) {
942 name_ = [address_r[1] retain];
943 address_ = [address_r[2] retain];
945 name_ = [string retain];
953 /* CoreGraphics Primitives {{{ */
958 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
959 CGFloat color[] = {red, green, blue, alpha};
960 return CGColorCreate(space, color);
969 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
970 color_(Create_(space, red, green, blue, alpha))
972 Set(space, red, green, blue, alpha);
977 CGColorRelease(color_);
984 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
986 color_ = Create_(space, red, green, blue, alpha);
989 operator CGColorRef() {
995 /* Random Global Variables {{{ */
996 static const int PulseInterval_ = 50000;
997 static const int ButtonBarWidth_ = 60;
998 static const int ButtonBarHeight_ = 48;
999 static const float KeyboardTime_ = 0.3f;
1002 static NSArray *Finishes_;
1004 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1005 #define NotifyConfig_ "/etc/notify.conf"
1007 static bool Queuing_;
1009 static CYColor Blue_;
1010 static CYColor Blueish_;
1011 static CYColor Black_;
1012 static CYColor Off_;
1013 static CYColor White_;
1014 static CYColor Gray_;
1015 static CYColor Green_;
1016 static CYColor Purple_;
1017 static CYColor Purplish_;
1019 static UIColor *InstallingColor_;
1020 static UIColor *RemovingColor_;
1022 static NSString *App_;
1023 static NSString *Home_;
1025 static BOOL Advanced_;
1026 static BOOL Ignored_;
1028 static UIFont *Font12_;
1029 static UIFont *Font12Bold_;
1030 static UIFont *Font14_;
1031 static UIFont *Font18Bold_;
1032 static UIFont *Font22Bold_;
1034 static const char *Machine_ = NULL;
1035 static NSString *System_ = nil;
1036 static NSString *SerialNumber_ = nil;
1037 static NSString *ChipID_ = nil;
1038 static NSString *Token_ = nil;
1039 static NSString *UniqueID_ = nil;
1040 static NSString *PLMN_ = nil;
1041 static NSString *Build_ = nil;
1042 static NSString *Product_ = nil;
1043 static NSString *Safari_ = nil;
1045 static CFLocaleRef Locale_;
1046 static NSArray *Languages_;
1047 static CGColorSpaceRef space_;
1049 static NSDictionary *SectionMap_;
1050 static NSMutableDictionary *Metadata_;
1051 static _transient NSMutableDictionary *Settings_;
1052 static _transient NSString *Role_;
1053 static _transient NSMutableDictionary *Packages_;
1054 static _transient NSMutableDictionary *Sections_;
1055 static _transient NSMutableDictionary *Sources_;
1056 static bool Changed_;
1059 static bool IsWildcat_;
1062 /* Display Helpers {{{ */
1063 inline float Interpolate(float begin, float end, float fraction) {
1064 return (end - begin) * fraction + begin;
1067 /* XXX: localize this! */
1068 NSString *SizeString(double size) {
1069 bool negative = size < 0;
1074 while (size > 1024) {
1079 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1081 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1084 static _finline const char *StripVersion_(const char *version) {
1085 const char *colon(strchr(version, ':'));
1087 version = colon + 1;
1091 NSString *LocalizeSection(NSString *section) {
1092 static Pcre title_r("^(.*?) \\((.*)\\)$");
1093 if (title_r(section)) {
1094 NSString *parent(title_r[1]);
1095 NSString *child(title_r[2]);
1097 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1098 LocalizeSection(parent),
1099 LocalizeSection(child)
1103 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1106 NSString *Simplify(NSString *title) {
1107 const char *data = [title UTF8String];
1108 size_t size = [title length];
1110 static Pcre square_r("^\\[(.*)\\]$");
1111 if (square_r(data, size))
1112 return Simplify(square_r[1]);
1114 static Pcre paren_r("^\\((.*)\\)$");
1115 if (paren_r(data, size))
1116 return Simplify(paren_r[1]);
1118 static Pcre title_r("^(.*?) \\((.*)\\)$");
1119 if (title_r(data, size))
1120 return Simplify(title_r[1]);
1126 NSString *GetLastUpdate() {
1127 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1130 return UCLocalize("NEVER_OR_UNKNOWN");
1132 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1133 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1135 CFRelease(formatter);
1137 return [(NSString *) formatted autorelease];
1140 bool isSectionVisible(NSString *section) {
1141 NSDictionary *metadata([Sections_ objectForKey:section]);
1142 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1143 return hidden == nil || ![hidden boolValue];
1148 /* Delegate Prototypes {{{ */
1152 @interface NSObject (ProgressDelegate)
1155 @protocol ProgressDelegate
1156 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1157 - (void) setProgressTitle:(NSString *)title;
1158 - (void) setProgressPercent:(float)percent;
1159 - (void) startProgress;
1160 - (void) addProgressOutput:(NSString *)output;
1161 - (bool) isCancelling:(size_t)received;
1164 @protocol ConfigurationDelegate
1165 - (void) repairWithSelector:(SEL)selector;
1166 - (void) setConfigurationData:(NSString *)data;
1169 @class PackageController;
1171 @protocol CydiaDelegate
1172 - (void) setPackageController:(PackageController *)view;
1173 - (void) clearPackage:(Package *)package;
1174 - (void) installPackage:(Package *)package;
1175 - (void) installPackages:(NSArray *)packages;
1176 - (void) removePackage:(Package *)package;
1177 - (void) beginUpdate;
1179 - (void) distUpgrade;
1181 - (void) updateData;
1183 - (void) showSettings;
1184 - (UIProgressHUD *) addProgressHUD;
1185 - (BOOL) hudIsShowing;
1186 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1187 - (CYViewController *) pageForPackage:(NSString *)name;
1188 - (PackageController *) packageController;
1189 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1193 /* Status Delegation {{{ */
1195 public pkgAcquireStatus
1198 _transient NSObject<ProgressDelegate> *delegate_;
1206 void setDelegate(id delegate) {
1207 delegate_ = delegate;
1210 NSObject<ProgressDelegate> *getDelegate() const {
1214 virtual bool MediaChange(std::string media, std::string drive) {
1218 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1221 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1222 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1223 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1226 virtual void Done(pkgAcquire::ItemDesc &item) {
1229 virtual void Fail(pkgAcquire::ItemDesc &item) {
1231 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1232 item.Owner->Status == pkgAcquire::Item::StatDone
1236 std::string &error(item.Owner->ErrorText);
1240 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1241 NSArray *fields([description componentsSeparatedByString:@" "]);
1242 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1244 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1245 withObject:[NSArray arrayWithObjects:
1246 [NSString stringWithUTF8String:error.c_str()],
1253 virtual bool Pulse(pkgAcquire *Owner) {
1254 bool value = pkgAcquireStatus::Pulse(Owner);
1257 double(CurrentBytes + CurrentItems) /
1258 double(TotalBytes + TotalItems)
1261 [delegate_ setProgressPercent:percent];
1262 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1265 virtual void Start() {
1266 [delegate_ startProgress];
1269 virtual void Stop() {
1273 /* Progress Delegation {{{ */
1278 _transient id<ProgressDelegate> delegate_;
1282 virtual void Update() {
1283 /*if (abs(Percent - percent_) > 2)
1284 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1288 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1289 [delegate_ setProgressPercent:(Percent / 100)];*/
1299 void setDelegate(id delegate) {
1300 delegate_ = delegate;
1303 id getDelegate() const {
1307 virtual void Done() {
1309 //[delegate_ setProgressPercent:1];
1314 /* Database Interface {{{ */
1315 typedef std::map< unsigned long, _H<Source> > SourceMap;
1317 @interface Database : NSObject {
1323 pkgCacheFile cache_;
1324 pkgDepCache::Policy *policy_;
1325 pkgRecords *records_;
1326 pkgProblemResolver *resolver_;
1327 pkgAcquire *fetcher_;
1329 SPtr<pkgPackageManager> manager_;
1330 pkgSourceList *list_;
1333 CFMutableArrayRef packages_;
1335 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1344 + (Database *) sharedInstance;
1347 - (void) _readCydia:(NSNumber *)fd;
1348 - (void) _readStatus:(NSNumber *)fd;
1349 - (void) _readOutput:(NSNumber *)fd;
1353 - (Package *) packageWithName:(NSString *)name;
1355 - (pkgCacheFile &) cache;
1356 - (pkgDepCache::Policy *) policy;
1357 - (pkgRecords *) records;
1358 - (pkgProblemResolver *) resolver;
1359 - (pkgAcquire &) fetcher;
1360 - (pkgSourceList &) list;
1361 - (NSArray *) packages;
1362 - (NSArray *) sources;
1363 - (void) reloadData;
1371 - (void) updateWithStatus:(Status &)status;
1373 - (void) setDelegate:(id)delegate;
1374 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1377 /* Delegate Helpers {{{ */
1378 @implementation NSObject (ProgressDelegate)
1380 - (void) _setProgressErrorPackage:(NSArray *)args {
1381 [self performSelector:@selector(setProgressError:forPackage:)
1382 withObject:[args objectAtIndex:0]
1383 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1387 - (void) _setProgressErrorTitle:(NSArray *)args {
1388 [self performSelector:@selector(setProgressError:withTitle:)
1389 withObject:[args objectAtIndex:0]
1390 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1394 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1395 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1396 withObject:[NSArray arrayWithObjects:error, title, nil]
1401 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1402 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1404 [self performSelector:@selector(setProgressError:withTitle:)
1406 withObject:(package == nil ? id : [package name])
1413 /* Source Class {{{ */
1414 @interface Source : NSObject {
1415 CYString depiction_;
1416 CYString description_;
1422 CYString distribution_;
1427 NSString *authority_;
1429 CYString defaultIcon_;
1431 NSDictionary *record_;
1435 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1437 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1439 - (NSString *) depictionForPackage:(NSString *)package;
1440 - (NSString *) supportForPackage:(NSString *)package;
1442 - (NSDictionary *) record;
1446 - (NSString *) distribution;
1447 - (NSString *) type;
1449 - (NSString *) host;
1451 - (NSString *) name;
1452 - (NSString *) description;
1453 - (NSString *) label;
1454 - (NSString *) origin;
1455 - (NSString *) version;
1457 - (NSString *) defaultIcon;
1461 @implementation Source
1465 distribution_.clear();
1468 description_.clear();
1474 defaultIcon_.clear();
1476 if (record_ != nil) {
1486 if (authority_ != nil) {
1487 [authority_ release];
1493 // XXX: this is a very inefficient way to call these deconstructors
1498 + (NSArray *) _attributeKeys {
1499 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1502 - (NSArray *) attributeKeys {
1503 return [[self class] _attributeKeys];
1506 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1507 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1510 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1513 trusted_ = index->IsTrusted();
1515 uri_.set(pool, index->GetURI());
1516 distribution_.set(pool, index->GetDist());
1517 type_.set(pool, index->GetType());
1519 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1520 if (dindex != NULL) {
1522 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1525 pkgTagFile tags(&fd);
1527 pkgTagSection section;
1534 {"default-icon", &defaultIcon_},
1535 {"depiction", &depiction_},
1536 {"description", &description_},
1538 {"origin", &origin_},
1539 {"support", &support_},
1540 {"version", &version_},
1543 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1544 const char *start, *end;
1546 if (section.Find(names[i].name_, start, end)) {
1547 CYString &value(*names[i].value_);
1548 value.set(pool, start, end - start);
1554 record_ = [Sources_ objectForKey:[self key]];
1556 record_ = [record_ retain];
1558 NSURL *url([NSURL URLWithString:uri_]);
1562 host_ = [[host_ lowercaseString] retain];
1567 authority_ = [url path];
1569 if (authority_ != nil)
1570 authority_ = [authority_ retain];
1573 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1574 if ((self = [super init]) != nil) {
1575 [self setMetaIndex:index inPool:pool];
1579 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1580 NSDictionary *lhr = [self record];
1581 NSDictionary *rhr = [source record];
1584 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1586 NSString *lhs = [self name];
1587 NSString *rhs = [source name];
1589 if ([lhs length] != 0 && [rhs length] != 0) {
1590 unichar lhc = [lhs characterAtIndex:0];
1591 unichar rhc = [rhs characterAtIndex:0];
1593 if (isalpha(lhc) && !isalpha(rhc))
1594 return NSOrderedAscending;
1595 else if (!isalpha(lhc) && isalpha(rhc))
1596 return NSOrderedDescending;
1599 return [lhs compare:rhs options:LaxCompareOptions_];
1602 - (NSString *) depictionForPackage:(NSString *)package {
1603 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1606 - (NSString *) supportForPackage:(NSString *)package {
1607 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1610 - (NSDictionary *) record {
1618 - (NSString *) uri {
1622 - (NSString *) distribution {
1623 return distribution_;
1626 - (NSString *) type {
1630 - (NSString *) key {
1631 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1634 - (NSString *) host {
1638 - (NSString *) name {
1639 return origin_.empty() ? authority_ : origin_;
1642 - (NSString *) description {
1643 return description_;
1646 - (NSString *) label {
1647 return label_.empty() ? authority_ : label_;
1650 - (NSString *) origin {
1654 - (NSString *) version {
1658 - (NSString *) defaultIcon {
1659 return defaultIcon_;
1664 /* Relationship Class {{{ */
1665 @interface Relationship : NSObject {
1670 - (NSString *) type;
1672 - (NSString *) name;
1676 @implementation Relationship
1684 - (NSString *) type {
1692 - (NSString *) name {
1699 /* Package Class {{{ */
1700 @interface Package : NSObject {
1704 pkgCache::VerIterator version_;
1705 pkgCache::PkgIterator iterator_;
1706 _transient Database *database_;
1707 pkgCache::VerFileIterator file_;
1713 _transient NSString *section$_;
1718 CYString installed_;
1724 CYString depiction_;
1735 NSMutableArray *tags_;
1738 NSMutableDictionary *metadata_;
1745 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1746 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1748 - (pkgCache::PkgIterator) iterator;
1751 - (NSString *) section;
1752 - (NSString *) simpleSection;
1754 - (NSString *) longSection;
1755 - (NSString *) shortSection;
1759 - (Address *) maintainer;
1761 - (NSString *) longDescription;
1762 - (NSString *) shortDescription;
1765 - (NSMutableDictionary *) metadata;
1767 - (BOOL) subscribed;
1770 - (NSString *) latest;
1771 - (NSString *) installed;
1772 - (BOOL) uninstalled;
1775 - (BOOL) upgradableAndEssential:(BOOL)essential;
1778 - (BOOL) unfiltered;
1782 - (BOOL) halfConfigured;
1783 - (BOOL) halfInstalled;
1785 - (NSString *) mode;
1788 - (NSString *) name;
1790 - (NSString *) homepage;
1791 - (NSString *) depiction;
1792 - (Address *) author;
1794 - (NSString *) support;
1796 - (NSArray *) files;
1797 - (NSArray *) warnings;
1798 - (NSArray *) applications;
1800 - (Source *) source;
1801 - (NSString *) role;
1803 - (BOOL) matches:(NSString *)text;
1805 - (bool) hasSupportingRole;
1806 - (BOOL) hasTag:(NSString *)tag;
1807 - (NSString *) primaryPurpose;
1808 - (NSArray *) purposes;
1809 - (bool) isCommercial;
1811 - (CYString &) cyname;
1813 - (uint32_t) compareBySection:(NSArray *)sections;
1818 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1819 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1820 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1821 - (bool) isVisibleInSection:(NSString *)section;
1822 - (bool) isVisibleInSource:(Source *)source;
1826 uint32_t PackageChangesRadix(Package *self, void *) {
1831 uint32_t timestamp : 30;
1832 uint32_t ignored : 1;
1833 uint32_t upgradable : 1;
1837 bool upgradable([self upgradableAndEssential:YES]);
1838 value.bits.upgradable = upgradable ? 1 : 0;
1841 value.bits.timestamp = 0;
1842 value.bits.ignored = [self ignored] ? 0 : 1;
1843 value.bits.upgradable = 1;
1845 value.bits.timestamp = static_cast<uint32_t>([self seen]) >> 2;
1846 value.bits.ignored = 0;
1847 value.bits.upgradable = 0;
1850 return _not(uint32_t) - value.key;
1853 _finline static void Stifle(uint8_t &value) {
1856 uint32_t PackagePrefixRadix(Package *self, void *context) {
1857 size_t offset(reinterpret_cast<size_t>(context));
1858 CYString &name([self cyname]);
1860 size_t size(name.size());
1863 char *text(name.data());
1866 if (!isdigit(text[0]))
1870 while (size != digits && isdigit(text[digits]))
1880 if (offset == 0 && zeros != 0) {
1881 memset(data, '0', zeros);
1882 memcpy(data + zeros, text, 4 - zeros);
1884 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1885 if (size <= offset - zeros)
1888 text += offset - zeros;
1889 size -= offset - zeros;
1892 memcpy(data, text, 4);
1894 memcpy(data, text, size);
1895 memset(data + size, 0, 4 - size);
1898 for (size_t i(0); i != 4; ++i)
1899 if (isalpha(data[i]))
1907 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1909 /* XXX: ntohl may be more honest */
1910 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1913 CYString &(*PackageName)(Package *self, SEL sel);
1915 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1916 _profile(PackageNameCompare)
1917 CYString &lhi(PackageName(lhs, @selector(cyname)));
1918 CYString &rhi(PackageName(rhs, @selector(cyname)));
1919 CFStringRef lhn(lhi), rhn(rhi);
1922 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1923 else if (rhn == NULL)
1924 return NSOrderedDescending;
1926 _profile(PackageNameCompare$NumbersLast)
1927 if (!lhi.empty() && !rhi.empty()) {
1928 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1929 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1930 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1931 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1932 return lha ? NSOrderedAscending : NSOrderedDescending;
1936 CFIndex length = CFStringGetLength(lhn);
1938 _profile(PackageNameCompare$Compare)
1939 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1944 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1945 return PackageNameCompare(*lhs, *rhs, context);
1948 struct PackageNameOrdering :
1949 std::binary_function<Package *, Package *, bool>
1951 _finline bool operator ()(Package *lhs, Package *rhs) const {
1952 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1956 @implementation Package
1958 - (NSString *) description {
1959 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1966 if (sponsor$_ != nil)
1967 [sponsor$_ release];
1968 if (author$_ != nil)
1975 if (metadata_ != nil)
1976 [metadata_ release];
1981 + (NSString *) webScriptNameForSelector:(SEL)selector {
1982 if (selector == @selector(hasTag:))
1988 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1989 return [self webScriptNameForSelector:selector] == nil;
1992 + (NSArray *) _attributeKeys {
1993 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];
1996 - (NSArray *) attributeKeys {
1997 return [[self class] _attributeKeys];
2000 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2001 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2011 _profile(Package$parse)
2012 pkgRecords::Parser *parser;
2014 _profile(Package$parse$Lookup)
2015 parser = &[database_ records]->Lookup(file_);
2020 _profile(Package$parse$Find)
2026 {"depiction", &depiction_},
2027 {"homepage", &homepage_},
2028 {"website", &website},
2030 {"support", &support_},
2031 {"sponsor", &sponsor_},
2032 {"author", &author_},
2035 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2036 const char *start, *end;
2038 if (parser->Find(names[i].name_, start, end)) {
2039 CYString &value(*names[i].value_);
2040 _profile(Package$parse$Value)
2041 value.set(pool_, start, end - start);
2047 _profile(Package$parse$Tagline)
2048 const char *start, *end;
2049 if (parser->ShortDesc(start, end)) {
2050 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2053 while (stop != start && stop[-1] == '\r')
2055 tagline_.set(pool_, start, stop - start);
2059 _profile(Package$parse$Retain)
2060 if (homepage_.empty())
2061 homepage_ = website;
2062 if (homepage_ == depiction_)
2068 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2069 if ((self = [super init]) != nil) {
2070 _profile(Package$initWithVersion)
2071 era_ = [database era];
2076 _profile(Package$initWithVersion$ParentPkg)
2077 iterator_ = version.ParentPkg();
2080 database_ = database;
2082 _profile(Package$initWithVersion$Latest)
2083 latest_.set(pool_, StripVersion_(version_.VerStr()));
2086 pkgCache::VerIterator current;
2087 _profile(Package$initWithVersion$Versions)
2088 current = iterator_.CurrentVer();
2090 installed_.set(pool_, StripVersion_(current.VerStr()));
2092 if (!version_.end())
2093 file_ = version_.FileList();
2095 pkgCache &cache([database_ cache]);
2096 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2100 _profile(Package$initWithVersion$Name)
2101 id_.set(pool_, iterator_.Name());
2102 name_.set(pool, iterator_.Display());
2105 _profile(Package$initWithVersion$lowercaseString)
2106 char *data(id_.data());
2107 for (size_t i(0), e(id_.size()); i != e; ++i)
2108 // XXX: do not use tolower() as this is not locale-specific? :(
2112 _profile(Package$initWithVersion$Tags)
2113 pkgCache::TagIterator tag(iterator_.TagList());
2115 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2117 const char *name(tag.Name());
2118 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2119 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2120 role_ = (NSString *) CYStringCreate(name + 6);
2122 } while (!tag.end());
2126 bool changed(false);
2128 _profile(Package$initWithVersion$Metadata)
2129 metadata_ = [Packages_ objectForKey:id_];
2131 if (metadata_ == nil) {
2134 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2135 [NSDate dateWithTimeIntervalSince1970:firstSeen_], @"FirstSeen",
2136 static_cast<id>(latest_), @"LastVersion",
2141 firstSeen_ = [[metadata_ objectForKey:@"FirstSeen"] timeIntervalSince1970];
2142 lastSeen_ = [[metadata_ objectForKey:@"LastSeen"] timeIntervalSince1970];
2144 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2145 subscribed_ = [subscribed boolValue];
2147 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2149 if (firstSeen_ == 0) {
2150 firstSeen_ = lastSeen_ == 0 ? now_ : lastSeen_;
2151 [metadata_ setObject:[NSDate dateWithTimeIntervalSince1970:firstSeen_] forKey:@"FirstSeen"];
2155 if (version == nil) {
2156 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2158 } else if (![version isEqualToString:latest_]) {
2159 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2161 [metadata_ setObject:[NSDate dateWithTimeIntervalSince1970:lastSeen_] forKey:@"LastSeen"];
2166 metadata_ = [metadata_ retain];
2169 [Packages_ setObject:metadata_ forKey:id_];
2174 _profile(Package$initWithVersion$Section)
2175 section_.set(pool_, iterator_.Section());
2178 _profile(Package$initWithVersion$hasTag)
2179 obsolete_ = [self hasTag:@"cydia::obsolete"];
2180 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2183 ignored_ = iterator_->SelectedState == pkgCache::State::Hold;
2187 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2188 pkgCache::VerIterator version;
2190 _profile(Package$packageWithIterator$GetCandidateVer)
2191 version = [database policy]->GetCandidateVer(iterator);
2197 return [[[Package alloc]
2198 initWithVersion:version
2205 - (pkgCache::PkgIterator) iterator {
2209 - (NSString *) section {
2210 if (section$_ == nil) {
2211 if (section_.empty())
2214 _profile(Package$section)
2215 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2216 NSString *name(section_);
2217 section$_ = [SectionMap_ objectForKey:name] ?: name;
2222 - (NSString *) simpleSection {
2223 if (NSString *section = [self section])
2224 return Simplify(section);
2229 - (NSString *) longSection {
2230 return LocalizeSection([self section]);
2233 - (NSString *) shortSection {
2234 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2237 - (NSString *) uri {
2240 pkgIndexFile *index;
2241 pkgCache::PkgFileIterator file(file_.File());
2242 if (![database_ list].FindIndex(file, index))
2244 return [NSString stringWithUTF8String:iterator_->Path];
2245 //return [NSString stringWithUTF8String:file.Site()];
2246 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2250 - (Address *) maintainer {
2251 @synchronized (database_) {
2252 if ([database_ era] != era_ || file_.end())
2255 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2256 const std::string &maintainer(parser->Maintainer());
2257 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2261 @synchronized (database_) {
2262 if ([database_ era] != era_ || version_.end())
2265 return version_->InstalledSize;
2268 - (NSString *) longDescription {
2269 @synchronized (database_) {
2270 if ([database_ era] != era_ || file_.end())
2273 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2274 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2276 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2277 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2278 if ([lines count] < 2)
2281 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2282 for (size_t i(1), e([lines count]); i != e; ++i) {
2283 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2284 [trimmed addObject:trim];
2287 return [trimmed componentsJoinedByString:@"\n"];
2290 - (NSString *) shortDescription {
2295 _profile(Package$index)
2296 CFStringRef name((CFStringRef) [self name]);
2297 if (CFStringGetLength(name) == 0)
2299 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2300 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2302 return toupper(character);
2306 - (NSMutableDictionary *) metadata {
2311 return subscribed_ ? lastSeen_ : firstSeen_;
2314 - (BOOL) subscribed {
2322 - (NSString *) latest {
2326 - (NSString *) installed {
2330 - (BOOL) uninstalled {
2331 return installed_.empty();
2335 return !version_.end();
2338 - (BOOL) upgradableAndEssential:(BOOL)essential {
2339 _profile(Package$upgradableAndEssential)
2340 pkgCache::VerIterator current(iterator_.CurrentVer());
2342 return essential && essential_;
2344 return !version_.end() && version_ != current;
2348 - (BOOL) essential {
2353 return [database_ cache][iterator_].InstBroken();
2356 - (BOOL) unfiltered {
2357 _profile(Package$unfiltered$obsolete)
2362 _profile(Package$unfiltered$hasSupportingRole)
2363 if (![self hasSupportingRole])
2371 if (![self unfiltered])
2374 NSString *section([self section]);
2376 _profile(Package$visible$isSectionVisible)
2377 if (section != nil && !isSectionVisible(section))
2385 unsigned char current(iterator_->CurrentState);
2386 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2389 - (BOOL) halfConfigured {
2390 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2393 - (BOOL) halfInstalled {
2394 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2398 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2399 return state.Mode != pkgDepCache::ModeKeep;
2402 - (NSString *) mode {
2403 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2405 switch (state.Mode) {
2406 case pkgDepCache::ModeDelete:
2407 if ((state.iFlags & pkgDepCache::Purge) != 0)
2411 case pkgDepCache::ModeKeep:
2412 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2413 return @"REINSTALL";
2414 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2418 case pkgDepCache::ModeInstall:
2419 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2420 return @"REINSTALL";
2421 else*/ switch (state.Status) {
2423 return @"DOWNGRADE";
2429 return @"NEW_INSTALL";
2440 - (NSString *) name {
2441 return name_.empty() ? id_ : name_;
2444 - (UIImage *) icon {
2445 NSString *section = [self simpleSection];
2449 if ([static_cast<id>(icon_) hasPrefix:@"file:///"])
2450 // XXX: correct escaping
2451 icon = [UIImage imageAtPath:[static_cast<id>(icon_) substringFromIndex:7]];
2452 if (icon == nil) if (section != nil)
2453 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2454 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2455 if ([dicon hasPrefix:@"file:///"])
2456 // XXX: correct escaping
2457 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2459 icon = [UIImage applicationImageNamed:@"unknown.png"];
2463 - (NSString *) homepage {
2467 - (NSString *) depiction {
2468 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2471 - (Address *) sponsor {
2472 if (sponsor$_ == nil) {
2473 if (sponsor_.empty())
2475 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2479 - (Address *) author {
2480 if (author$_ == nil) {
2481 if (author_.empty())
2483 author$_ = [[Address addressWithString:author_] retain];
2487 - (NSString *) support {
2488 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2491 - (NSArray *) files {
2492 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2493 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2496 fin.open([path UTF8String]);
2501 while (std::getline(fin, line))
2502 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2507 - (NSArray *) warnings {
2508 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2509 const char *name(iterator_.Name());
2511 size_t length(strlen(name));
2512 if (length < 2) invalid:
2513 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2514 else for (size_t i(0); i != length; ++i)
2516 /* XXX: technically this is not allowed */
2517 (name[i] < 'A' || name[i] > 'Z') &&
2518 (name[i] < 'a' || name[i] > 'z') &&
2519 (name[i] < '0' || name[i] > '9') &&
2520 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2523 if (strcmp(name, "cydia") != 0) {
2526 bool _private = false;
2529 bool repository = [[self section] isEqualToString:@"Repositories"];
2531 if (NSArray *files = [self files])
2532 for (NSString *file in files)
2533 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2535 else if (!user && [file isEqualToString:@"/User"])
2537 else if (!_private && [file isEqualToString:@"/private"])
2539 else if (!stash && [file isEqualToString:@"/var/stash"])
2542 /* XXX: this is not sensitive enough. only some folders are valid. */
2543 if (cydia && !repository)
2544 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2546 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2548 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2550 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2553 return [warnings count] == 0 ? nil : warnings;
2556 - (NSArray *) applications {
2557 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2559 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2561 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2562 if (NSArray *files = [self files])
2563 for (NSString *file in files)
2564 if (application_r(file)) {
2565 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2566 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2567 if ([id isEqualToString:me])
2570 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2572 display = application_r[1];
2574 NSString *bundle([file stringByDeletingLastPathComponent]);
2575 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2576 if (icon == nil || [icon length] == 0)
2578 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2580 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2581 [applications addObject:application];
2583 [application addObject:id];
2584 [application addObject:display];
2585 [application addObject:url];
2588 return [applications count] == 0 ? nil : applications;
2591 - (Source *) source {
2592 if (source_ == nil) {
2593 @synchronized (database_) {
2594 if ([database_ era] != era_ || file_.end())
2595 source_ = (Source *) [NSNull null];
2597 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2601 return source_ == (Source *) [NSNull null] ? nil : source_;
2604 - (NSString *) role {
2608 - (BOOL) matches:(NSString *)text {
2614 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2615 if (range.location != NSNotFound)
2618 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2619 if (range.location != NSNotFound)
2622 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2623 if (range.location != NSNotFound)
2629 - (bool) hasSupportingRole {
2632 if ([role_ isEqualToString:@"enduser"])
2634 if ([Role_ isEqualToString:@"User"])
2636 if ([role_ isEqualToString:@"hacker"])
2638 if ([Role_ isEqualToString:@"Hacker"])
2640 if ([role_ isEqualToString:@"developer"])
2642 if ([Role_ isEqualToString:@"Developer"])
2647 - (BOOL) hasTag:(NSString *)tag {
2648 return tags_ == nil ? NO : [tags_ containsObject:tag];
2651 - (NSString *) primaryPurpose {
2652 for (NSString *tag in tags_)
2653 if ([tag hasPrefix:@"purpose::"])
2654 return [tag substringFromIndex:9];
2658 - (NSArray *) purposes {
2659 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2660 for (NSString *tag in tags_)
2661 if ([tag hasPrefix:@"purpose::"])
2662 [purposes addObject:[tag substringFromIndex:9]];
2663 return [purposes count] == 0 ? nil : purposes;
2666 - (bool) isCommercial {
2667 return [self hasTag:@"cydia::commercial"];
2670 - (CYString &) cyname {
2671 return name_.empty() ? id_ : name_;
2674 - (uint32_t) compareBySection:(NSArray *)sections {
2675 NSString *section([self section]);
2676 for (size_t i(0), e([sections count]); i != e; ++i) {
2677 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2681 return _not(uint32_t);
2685 @synchronized (database_) {
2686 pkgProblemResolver *resolver = [database_ resolver];
2687 resolver->Clear(iterator_);
2689 pkgCacheFile &cache([database_ cache]);
2690 cache->SetReInstall(iterator_, false);
2691 cache->MarkKeep(iterator_, false);
2695 @synchronized (database_) {
2696 pkgProblemResolver *resolver = [database_ resolver];
2697 resolver->Clear(iterator_);
2698 resolver->Protect(iterator_);
2700 pkgCacheFile &cache([database_ cache]);
2701 cache->SetReInstall(iterator_, false);
2702 cache->MarkInstall(iterator_, false);
2704 pkgDepCache::StateCache &state((*cache)[iterator_]);
2705 if (!state.Install())
2706 cache->SetReInstall(iterator_, true);
2710 @synchronized (database_) {
2711 pkgProblemResolver *resolver = [database_ resolver];
2712 resolver->Clear(iterator_);
2713 resolver->Remove(iterator_);
2714 resolver->Protect(iterator_);
2716 pkgCacheFile &cache([database_ cache]);
2717 cache->SetReInstall(iterator_, false);
2718 cache->MarkDelete(iterator_, true);
2721 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2722 _profile(Package$isUnfilteredAndSearchedForBy)
2725 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2726 value &= [self unfiltered];
2729 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2730 value &= [self matches:search];
2737 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2738 if ([search length] == 0)
2741 _profile(Package$isUnfilteredAndSelectedForBy)
2744 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2745 value &= [self unfiltered];
2748 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2749 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2756 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2757 return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]);
2760 - (bool) isVisibleInSection:(NSString *)name {
2761 NSString *section([self section]);
2765 section == nil && [name length] == 0 ||
2766 [name isEqualToString:section]
2767 ) && [self visible];
2770 - (bool) isVisibleInSource:(Source *)source {
2771 return [self source] == source && [self visible];
2776 /* Section Class {{{ */
2777 @interface Section : NSObject {
2782 NSString *localized_;
2785 - (NSComparisonResult) compareByLocalized:(Section *)section;
2786 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2787 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2788 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2789 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2790 - (NSString *) name;
2797 - (void) addToCount;
2799 - (void) setCount:(size_t)count;
2800 - (NSString *) localized;
2804 @implementation Section
2808 if (localized_ != nil)
2809 [localized_ release];
2813 - (NSComparisonResult) compareByLocalized:(Section *)section {
2814 NSString *lhs(localized_);
2815 NSString *rhs([section localized]);
2817 /*if ([lhs length] != 0 && [rhs length] != 0) {
2818 unichar lhc = [lhs characterAtIndex:0];
2819 unichar rhc = [rhs characterAtIndex:0];
2821 if (isalpha(lhc) && !isalpha(rhc))
2822 return NSOrderedAscending;
2823 else if (!isalpha(lhc) && isalpha(rhc))
2824 return NSOrderedDescending;
2827 return [lhs compare:rhs options:LaxCompareOptions_];
2830 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2831 if ((self = [self initWithName:name localize:NO]) != nil) {
2832 if (localized != nil)
2833 localized_ = [localized retain];
2837 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2838 return [self initWithName:name row:0 localize:localize];
2841 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2842 if ((self = [super init]) != nil) {
2843 name_ = [name retain];
2847 localized_ = [LocalizeSection(name_) retain];
2851 /* XXX: localize the index thingees */
2852 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2853 if ((self = [super init]) != nil) {
2854 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2860 - (NSString *) name {
2880 - (void) addToCount {
2884 - (void) setCount:(size_t)count {
2888 - (NSString *) localized {
2895 static NSString *Colon_;
2896 static NSString *Elision_;
2897 static NSString *Error_;
2898 static NSString *Warning_;
2900 /* Database Implementation {{{ */
2901 @implementation Database
2903 + (Database *) sharedInstance {
2904 static Database *instance;
2905 if (instance == nil)
2906 instance = [[Database alloc] init];
2914 - (void) releasePackages {
2915 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
2916 CFArrayRemoveAllValues(packages_);
2920 // XXX: actually implement this thing
2922 [self releasePackages];
2923 apr_pool_destroy(pool_);
2924 NSRecycleZone(zone_);
2928 - (void) _readCydia:(NSNumber *)fd { _pooled
2929 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2930 std::istream is(&ib);
2933 static Pcre finish_r("^finish:([^:]*)$");
2935 while (std::getline(is, line)) {
2936 const char *data(line.c_str());
2937 size_t size = line.size();
2938 lprintf("C:%s\n", data);
2940 if (finish_r(data, size)) {
2941 NSString *finish = finish_r[1];
2942 int index = [Finishes_ indexOfObject:finish];
2943 if (index != INT_MAX && index > Finish_)
2951 - (void) _readStatus:(NSNumber *)fd { _pooled
2952 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2953 std::istream is(&ib);
2956 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2957 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2959 while (std::getline(is, line)) {
2960 const char *data(line.c_str());
2961 size_t size(line.size());
2962 lprintf("S:%s\n", data);
2964 if (conffile_r(data, size)) {
2965 [delegate_ setConfigurationData:conffile_r[1]];
2966 } else if (strncmp(data, "status: ", 8) == 0) {
2967 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2968 [delegate_ setProgressTitle:string];
2969 } else if (pmstatus_r(data, size)) {
2970 std::string type([pmstatus_r[1] UTF8String]);
2971 NSString *id = pmstatus_r[2];
2973 float percent([pmstatus_r[3] floatValue]);
2974 [delegate_ setProgressPercent:(percent / 100)];
2976 NSString *string = pmstatus_r[4];
2978 if (type == "pmerror")
2979 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
2980 withObject:[NSArray arrayWithObjects:string, id, nil]
2983 else if (type == "pmstatus") {
2984 [delegate_ setProgressTitle:string];
2985 } else if (type == "pmconffile")
2986 [delegate_ setConfigurationData:string];
2988 lprintf("E:unknown pmstatus\n");
2990 lprintf("E:unknown status\n");
2996 - (void) _readOutput:(NSNumber *)fd { _pooled
2997 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2998 std::istream is(&ib);
3001 while (std::getline(is, line)) {
3002 lprintf("O:%s\n", line.c_str());
3003 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3013 - (Package *) packageWithName:(NSString *)name {
3014 @synchronized (self) {
3015 if (static_cast<pkgDepCache *>(cache_) == NULL)
3017 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3018 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3022 if ((self = [super init]) != nil) {
3029 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3030 apr_pool_create(&pool_, NULL);
3032 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
3036 _assert(pipe(fds) != -1);
3039 _config->Set("APT::Keep-Fds::", cydiafd_);
3040 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3043 detachNewThreadSelector:@selector(_readCydia:)
3045 withObject:[NSNumber numberWithInt:fds[0]]
3048 _assert(pipe(fds) != -1);
3052 detachNewThreadSelector:@selector(_readStatus:)
3054 withObject:[NSNumber numberWithInt:fds[0]]
3057 _assert(pipe(fds) != -1);
3058 _assert(dup2(fds[0], 0) != -1);
3059 _assert(close(fds[0]) != -1);
3061 input_ = fdopen(fds[1], "a");
3063 _assert(pipe(fds) != -1);
3064 _assert(dup2(fds[1], 1) != -1);
3065 _assert(close(fds[1]) != -1);
3068 detachNewThreadSelector:@selector(_readOutput:)
3070 withObject:[NSNumber numberWithInt:fds[0]]
3075 - (pkgCacheFile &) cache {
3079 - (pkgDepCache::Policy *) policy {
3083 - (pkgRecords *) records {
3087 - (pkgProblemResolver *) resolver {
3091 - (pkgAcquire &) fetcher {
3095 - (pkgSourceList &) list {
3099 - (NSArray *) packages {
3100 return (NSArray *) packages_;
3103 - (NSArray *) sources {
3104 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3105 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3106 [sources addObject:i->second];
3110 - (NSArray *) issues {
3111 if (cache_->BrokenCount() == 0)
3114 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3116 for (Package *package in [self packages]) {
3117 if (![package broken])
3119 pkgCache::PkgIterator pkg([package iterator]);
3121 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3122 [entry addObject:[package name]];
3123 [issues addObject:entry];
3125 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3129 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3130 pkgCache::DepIterator start;
3131 pkgCache::DepIterator end;
3132 dep.GlobOr(start, end); // ++dep
3134 if (!cache_->IsImportantDep(end))
3136 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3139 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3140 [entry addObject:failure];
3141 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3143 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3144 if (Package *package = [self packageWithName:name])
3145 name = [package name];
3146 [failure addObject:name];
3148 pkgCache::PkgIterator target(start.TargetPkg());
3149 if (target->ProvidesList != 0)
3150 [failure addObject:@"?"];
3152 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3154 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3155 else if (!cache_[target].CandidateVerIter(cache_).end())
3156 [failure addObject:@"-"];
3157 else if (target->ProvidesList == 0)
3158 [failure addObject:@"!"];
3160 [failure addObject:@"%"];
3164 if (start.TargetVer() != 0)
3165 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3176 - (bool) popErrorWithTitle:(NSString *)title {
3178 std::string message;
3180 while (!_error->empty()) {
3182 bool warning(!_error->PopMessage(error));
3186 size_t size(error.size());
3187 if (size == 0 || error[size - 1] != '\n')
3189 error.resize(size - 1);
3191 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3193 if (!message.empty())
3198 if (fatal && !message.empty())
3199 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3204 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3205 return [self popErrorWithTitle:title] || !success;
3208 - (void) reloadData { CYPoolStart() {
3209 @synchronized (self) {
3212 [self releasePackages];
3233 apr_pool_clear(pool_);
3234 NSRecycleZone(zone_);
3236 int chk(creat("/tmp/cydia.chk", 0644));
3240 NSString *title(UCLocalize("DATABASE"));
3243 if (!cache_.Open(progress_, true)) { pop:
3245 bool warning(!_error->PopMessage(error));
3246 lprintf("cache_.Open():[%s]\n", error.c_str());
3248 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3249 [delegate_ repairWithSelector:@selector(configure)];
3250 else if (error == "The package lists or status file could not be parsed or opened.")
3251 [delegate_ repairWithSelector:@selector(update)];
3252 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3253 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3254 // else if (error == "The list of sources could not be read.")
3256 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3265 unlink("/tmp/cydia.chk");
3267 now_ = [[NSDate date] timeIntervalSince1970];
3269 policy_ = new pkgDepCache::Policy();
3270 records_ = new pkgRecords(cache_);
3271 resolver_ = new pkgProblemResolver(cache_);
3272 fetcher_ = new pkgAcquire(&status_);
3275 list_ = new pkgSourceList();
3276 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3279 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3280 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3284 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3287 if (cache_->BrokenCount() != 0) {
3288 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3291 if (cache_->BrokenCount() != 0) {
3292 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3296 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3300 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3301 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3302 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3303 // XXX: this could be more intelligent
3304 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3305 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3307 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3312 /*std::vector<Package *> packages;
3313 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3314 [packages_ release];
3319 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3320 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3321 //packages.push_back(package);
3322 CFArrayAppendValue(packages_, [package retain]);
3326 /*if (packages.empty())
3327 packages_ = [[NSArray alloc] init];
3329 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3332 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3333 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3334 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3342 /*if (!packages.empty())
3343 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3344 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3346 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3348 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3350 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3354 } } CYPoolEnd() _trace(); }
3357 @synchronized (self) {
3359 resolver_ = new pkgProblemResolver(cache_);
3361 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3362 if (!cache_[iterator].Keep()) {
3363 cache_->MarkKeep(iterator, false);
3364 cache_->SetReInstall(iterator, false);
3369 - (void) configure {
3370 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3371 system([dpkg UTF8String]);
3375 // XXX: I don't remember this condition
3380 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3382 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3384 if ([self popErrorWithTitle:title])
3388 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3391 public pkgArchiveCleaner
3394 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3399 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3406 fetcher_->Shutdown();
3408 pkgRecords records(cache_);
3410 lock_ = new FileFd();
3411 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3413 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3415 if ([self popErrorWithTitle:title])
3419 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3422 manager_ = (_system->CreatePM(cache_));
3423 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3430 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3432 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3434 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3436 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3437 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3440 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3445 bool failed = false;
3446 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3447 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3449 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3452 std::string uri = (*item)->DescURI();
3453 std::string error = (*item)->ErrorText;
3455 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3458 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3459 withObject:[NSArray arrayWithObjects:
3460 [NSString stringWithUTF8String:error.c_str()],
3472 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3474 if (_error->PendingError()) {
3479 if (result == pkgPackageManager::Failed) {
3484 if (result != pkgPackageManager::Completed) {
3489 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3491 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3493 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3494 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3497 if (![before isEqualToArray:after])
3502 NSString *title(UCLocalize("UPGRADE"));
3503 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3509 [self updateWithStatus:status_];
3512 - (void) updateWithStatus:(Status &)status {
3513 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3514 NSString *title(UCLocalize("REFRESHING_DATA"));
3517 if (!list.ReadMainList())
3518 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3521 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3522 if ([self popErrorWithTitle:title])
3525 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3526 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3527 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3529 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3533 - (void) setDelegate:(id)delegate {
3534 delegate_ = delegate;
3535 status_.setDelegate(delegate);
3536 progress_.setDelegate(delegate);
3539 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3540 SourceMap::const_iterator i(sources_.find(file->ID));
3541 return i == sources_.end() ? nil : i->second;
3547 /* Confirmation Controller {{{ */
3548 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3549 if (!iterator.end())
3550 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3551 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3553 pkgCache::PkgIterator package(dep.TargetPkg());
3556 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3564 /* Web Scripting {{{ */
3565 @interface CydiaObject : NSObject {
3567 _transient id delegate_;
3570 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3573 @implementation CydiaObject
3576 [indirect_ release];
3580 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3581 if ((self = [super init]) != nil) {
3582 indirect_ = [indirect retain];
3586 - (void) setDelegate:(id)delegate {
3587 delegate_ = delegate;
3590 + (NSArray *) _attributeKeys {
3591 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3594 - (NSArray *) attributeKeys {
3595 return [[self class] _attributeKeys];
3598 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3599 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3602 - (NSString *) device {
3603 return [[UIDevice currentDevice] uniqueIdentifier];
3606 #if 0 // XXX: implement!
3607 - (NSString *) mac {
3608 if (![indirect_ promptForSensitive:@"Mac Address"])
3612 - (NSString *) serial {
3613 if (![indirect_ promptForSensitive:@"Serial #"])
3617 - (NSString *) firewire {
3618 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3622 - (NSString *) imei {
3623 if (![indirect_ promptForSensitive:@"IMEI"])
3628 + (NSString *) webScriptNameForSelector:(SEL)selector {
3629 if (selector == @selector(close))
3631 else if (selector == @selector(getInstalledPackages))
3632 return @"getInstalledPackages";
3633 else if (selector == @selector(getPackageById:))
3634 return @"getPackageById";
3635 else if (selector == @selector(installPackages:))
3636 return @"installPackages";
3637 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3638 return @"setButtonImage";
3639 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3640 return @"setButtonTitle";
3641 else if (selector == @selector(setPopupHook:))
3642 return @"setPopupHook";
3643 else if (selector == @selector(setSpecial:))
3644 return @"setSpecial";
3645 else if (selector == @selector(setToken:))
3647 else if (selector == @selector(setViewportWidth:))
3648 return @"setViewportWidth";
3649 else if (selector == @selector(supports:))
3651 else if (selector == @selector(stringWithFormat:arguments:))
3653 else if (selector == @selector(localizedStringForKey:value:table:))
3655 else if (selector == @selector(du:))
3657 else if (selector == @selector(statfs:))
3663 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3664 return [self webScriptNameForSelector:selector] == nil;
3667 - (BOOL) supports:(NSString *)feature {
3668 return [feature isEqualToString:@"window.open"];
3671 - (NSArray *) getInstalledPackages {
3672 NSArray *packages([[Database sharedInstance] packages]);
3673 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3674 for (Package *package in packages)
3675 if ([package installed] != nil)
3676 [installed addObject:package];
3680 - (Package *) getPackageById:(NSString *)id {
3681 Package *package([[Database sharedInstance] packageWithName:id]);
3686 - (NSArray *) statfs:(NSString *)path {
3689 if (path == nil || statfs([path UTF8String], &stat) == -1)
3692 return [NSArray arrayWithObjects:
3693 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3694 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3695 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3699 - (NSNumber *) du:(NSString *)path {
3700 NSNumber *value(nil);
3703 _assert(pipe(fds) != -1);
3705 pid_t pid(ExecFork());
3707 _assert(dup2(fds[1], 1) != -1);
3708 _assert(close(fds[0]) != -1);
3709 _assert(close(fds[1]) != -1);
3710 /* XXX: this should probably not use du */
3711 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3716 _assert(close(fds[1]) != -1);
3718 if (FILE *du = fdopen(fds[0], "r")) {
3720 while (fgets(line, sizeof(line), du) != NULL) {
3721 size_t length(strlen(line));
3722 while (length != 0 && line[length - 1] == '\n')
3723 line[--length] = '\0';
3724 if (char *tab = strchr(line, '\t')) {
3726 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3731 } else _assert(close(fds[0]));
3735 if (waitpid(pid, &status, 0) == -1)
3738 else _assert(false);
3747 - (void) installPackages:(NSArray *)packages {
3748 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3751 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3752 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3755 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3756 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3759 - (void) setSpecial:(id)function {
3760 [indirect_ setSpecial:function];
3763 - (void) setToken:(NSString *)token {
3766 Token_ = [token retain];
3768 [Metadata_ setObject:Token_ forKey:@"Token"];
3772 - (void) setPopupHook:(id)function {
3773 [indirect_ setPopupHook:function];
3776 - (void) setViewportWidth:(float)width {
3777 [indirect_ setViewportWidth:width];
3780 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3781 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3782 unsigned count([arguments count]);
3784 for (unsigned i(0); i != count; ++i)
3785 values[i] = [arguments objectAtIndex:i];
3786 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3789 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3790 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3792 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3794 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3800 /* Cydia Browser Controller {{{ */
3801 @interface CYBrowserController : BrowserController {
3802 CydiaObject *cydia_;
3807 @implementation CYBrowserController
3814 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3817 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3818 [super webView:view didClearWindowObject:window forFrame:frame];
3820 WebDataSource *source([frame dataSource]);
3821 NSURLResponse *response([source response]);
3822 NSURL *url([response URL]);
3823 NSString *scheme([url scheme]);
3825 NSHTTPURLResponse *http;
3826 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3827 http = (NSHTTPURLResponse *) response;
3831 NSDictionary *headers([http allHeaderFields]);
3832 NSString *host([url host]);
3833 [self setHeaders:headers forHost:host];
3836 [host isEqualToString:@"cydia.saurik.com"] ||
3837 [host hasSuffix:@".cydia.saurik.com"] ||
3838 [scheme isEqualToString:@"file"]
3840 [window setValue:cydia_ forKey:@"cydia"];
3843 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3844 if (System_ != NULL)
3845 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3846 if (Machine_ != NULL)
3847 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3849 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3851 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3854 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3855 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3856 [self _setMoreHeaders:copy];
3860 - (void) setDelegate:(id)delegate {
3861 [super setDelegate:delegate];
3862 [cydia_ setDelegate:delegate];
3866 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3867 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3869 WebView *webview([[webview_ _documentView] webView]);
3871 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3873 NSString *application = package == nil ? @"Cydia" : [NSString
3874 stringWithFormat:@"Cydia/%@",
3879 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3881 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3882 if (Product_ != nil)
3883 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3885 [webview setApplicationNameForUserAgent:application];
3892 /* Confirmation {{{ */
3893 @protocol ConfirmationControllerDelegate
3894 - (void) cancelAndClear:(bool)clear;
3895 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3899 @interface ConfirmationController : CYBrowserController {
3900 _transient Database *database_;
3901 UIAlertView *essential_;
3908 - (id) initWithDatabase:(Database *)database;
3912 @implementation ConfirmationController
3919 if (essential_ != nil)
3920 [essential_ release];
3924 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3925 NSString *context([alert context]);
3927 if ([context isEqualToString:@"remove"]) {
3928 if (button == [alert cancelButtonIndex]) {
3929 [self dismissModalViewControllerAnimated:YES];
3930 } else if (button == [alert firstOtherButtonIndex]) {
3933 [delegate_ confirmWithNavigationController:[self navigationController]];
3936 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3937 } else if ([context isEqualToString:@"unable"]) {
3938 [self dismissModalViewControllerAnimated:YES];
3939 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3941 [super alertView:alert clickedButtonAtIndex:button];
3945 - (void) _doContinue {
3946 [self dismissModalViewControllerAnimated:YES];
3947 [delegate_ cancelAndClear:NO];
3950 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
3951 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
3955 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3956 [super webView:view didClearWindowObject:window forFrame:frame];
3957 [window setValue:changes_ forKey:@"changes"];
3958 [window setValue:issues_ forKey:@"issues"];
3959 [window setValue:sizes_ forKey:@"sizes"];
3960 [window setValue:self forKey:@"queue"];
3963 - (id) initWithDatabase:(Database *)database {
3964 if ((self = [super init]) != nil) {
3965 database_ = database;
3967 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
3969 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3970 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3971 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3972 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3973 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3977 pkgDepCache::Policy *policy([database_ policy]);
3979 pkgCacheFile &cache([database_ cache]);
3980 NSArray *packages = [database_ packages];
3981 for (Package *package in packages) {
3982 pkgCache::PkgIterator iterator = [package iterator];
3983 pkgDepCache::StateCache &state(cache[iterator]);
3985 NSString *name([package name]);
3987 if (state.NewInstall())
3988 [installing addObject:name];
3989 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3990 [reinstalling addObject:name];
3991 else if (state.Upgrade())
3992 [upgrading addObject:name];
3993 else if (state.Downgrade())
3994 [downgrading addObject:name];
3995 else if (state.Delete()) {
3996 if ([package essential])
3998 [removing addObject:name];
4001 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4002 substrate_ |= DepSubstrate(iterator.CurrentVer());
4007 else if (Advanced_) {
4008 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4010 essential_ = [[UIAlertView alloc]
4011 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4012 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4014 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4015 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4018 [essential_ setContext:@"remove"];
4020 essential_ = [[UIAlertView alloc]
4021 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4022 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4024 cancelButtonTitle:UCLocalize("OKAY")
4025 otherButtonTitles:nil
4028 [essential_ setContext:@"unable"];
4031 changes_ = [[NSArray alloc] initWithObjects:
4039 issues_ = [database_ issues];
4041 issues_ = [issues_ retain];
4043 sizes_ = [[NSArray alloc] initWithObjects:
4044 SizeString([database_ fetcher].FetchNeeded()),
4045 SizeString([database_ fetcher].PartialPresent()),
4048 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4050 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4051 initWithTitle:UCLocalize("CANCEL")
4052 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4053 style:UIBarButtonItemStylePlain
4055 action:@selector(cancelButtonClicked)
4060 - (void) applyRightButton {
4061 #if !AlwaysReload && !IgnoreInstall
4062 if (issues_ == nil && ![self isLoading])
4063 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4064 initWithTitle:UCLocalize("CONFIRM")
4065 style:UIBarButtonItemStylePlain
4067 action:@selector(confirmButtonClicked)
4070 [super applyRightButton];
4072 [[self navigationItem] setRightBarButtonItem:nil];
4076 - (void) cancelButtonClicked {
4077 [self dismissModalViewControllerAnimated:YES];
4078 [delegate_ cancelAndClear:YES];
4082 - (void) confirmButtonClicked {
4086 if (essential_ != nil)
4091 [delegate_ confirmWithNavigationController:[self navigationController]];
4099 /* Progress Data {{{ */
4100 @interface ProgressData : NSObject {
4102 // XXX: should these really both be _transient?
4103 _transient id target_;
4104 _transient id object_;
4107 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4114 @implementation ProgressData
4116 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4117 if ((self = [super init]) != nil) {
4118 selector_ = selector;
4138 /* Progress Controller {{{ */
4139 @interface ProgressController : CYViewController <
4140 ConfigurationDelegate,
4143 _transient Database *database_;
4144 UIProgressBar *progress_;
4145 UITextView *output_;
4146 UITextLabel *status_;
4147 UIPushButton *close_;
4149 SHA1SumValue springlist_;
4150 SHA1SumValue notifyconf_;
4154 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4156 - (void) _retachThread;
4157 - (void) _detachNewThreadData:(ProgressData *)data;
4158 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4164 @protocol ProgressControllerDelegate
4165 - (void) progressControllerIsComplete:(ProgressController *)sender;
4168 @implementation ProgressController
4171 [database_ setDelegate:nil];
4172 [progress_ release];
4181 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4182 if ((self = [super init]) != nil) {
4183 database_ = database;
4184 [database_ setDelegate:self];
4185 delegate_ = delegate;
4187 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4189 progress_ = [[UIProgressBar alloc] init];
4190 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4191 [progress_ setStyle:0];
4193 status_ = [[UITextLabel alloc] init];
4194 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4195 [status_ setColor:[UIColor whiteColor]];
4196 [status_ setBackgroundColor:[UIColor clearColor]];
4197 [status_ setCentersHorizontally:YES];
4198 //[status_ setFont:font];
4200 output_ = [[UITextView alloc] init];
4202 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4203 //[output_ setTextFont:@"Courier New"];
4204 [output_ setFont:[[output_ font] fontWithSize:12]];
4205 [output_ setTextColor:[UIColor whiteColor]];
4206 [output_ setBackgroundColor:[UIColor clearColor]];
4207 [output_ setMarginTop:0];
4208 [output_ setAllowsRubberBanding:YES];
4209 [output_ setEditable:NO];
4210 [[self view] addSubview:output_];
4212 close_ = [[UIPushButton alloc] init];
4213 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4214 [close_ setAutosizesToFit:NO];
4215 [close_ setDrawsShadow:YES];
4216 [close_ setStretchBackground:YES];
4217 [close_ setEnabled:YES];
4218 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4219 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4220 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4221 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4225 - (void) positionViews {
4226 CGRect bounds = [[self view] bounds];
4227 CGSize prgsize = [UIProgressBar defaultSize];
4230 (bounds.size.width - prgsize.width) / 2,
4231 bounds.size.height - prgsize.height - 20
4234 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4236 [progress_ setFrame:prgrect];
4237 [status_ setFrame:CGRectMake(
4239 bounds.size.height - prgsize.height - 50,
4240 bounds.size.width - 20,
4243 [output_ setFrame:CGRectMake(
4246 bounds.size.width - 20,
4247 bounds.size.height - 62
4249 [close_ setFrame:CGRectMake(
4250 (bounds.size.width - closewidth) / 2,
4251 bounds.size.height - prgsize.height - 50,
4257 - (void) viewWillAppear:(BOOL)animated {
4258 [super viewDidAppear:animated];
4259 [[self navigationItem] setHidesBackButton:YES];
4260 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4262 [self positionViews];
4265 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4266 [self positionViews];
4269 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4270 NSString *context([alert context]);
4272 if ([context isEqualToString:@"conffile"]) {
4273 FILE *input = [database_ input];
4274 if (button == [alert cancelButtonIndex])
4275 fprintf(input, "N\n");
4276 else if (button == [alert firstOtherButtonIndex])
4277 fprintf(input, "Y\n");
4282 - (void) closeButtonPushed {
4285 UpdateExternalStatus(0);
4289 [self dismissModalViewControllerAnimated:YES];
4293 [delegate_ terminateWithSuccess];
4294 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4295 [delegate_ suspendWithAnimation:YES];
4297 [delegate_ suspend];*/
4301 system("launchctl stop com.apple.SpringBoard");
4305 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4314 - (void) _retachThread {
4315 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4317 [[self view] addSubview:close_];
4318 [progress_ removeFromSuperview];
4319 [status_ removeFromSuperview];
4321 [database_ popErrorWithTitle:title_];
4322 [delegate_ progressControllerIsComplete:self];
4326 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4329 MMap mmap(file, MMap::ReadOnly);
4331 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4332 if (!(notifyconf_ == sha1.Result()))
4339 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4342 MMap mmap(file, MMap::ReadOnly);
4344 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4345 if (!(springlist_ == sha1.Result()))
4351 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4352 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4353 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4354 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4355 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4358 system("su -c /usr/bin/uicache mobile");
4360 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4362 [delegate_ setStatusBarShowsProgress:NO];
4365 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4366 [[data target] performSelector:[data selector] withObject:[data object]];
4367 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4370 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4371 UpdateExternalStatus(1);
4378 title_ = [title retain];
4380 [[self navigationItem] setTitle:title_];
4382 [status_ setText:nil];
4383 [output_ setText:@""];
4384 [progress_ setProgress:0];
4386 [close_ removeFromSuperview];
4387 [[self view] addSubview:progress_];
4388 [[self view] addSubview:status_];
4390 [delegate_ setStatusBarShowsProgress:YES];
4395 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4398 MMap mmap(file, MMap::ReadOnly);
4400 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4401 notifyconf_ = sha1.Result();
4407 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4410 MMap mmap(file, MMap::ReadOnly);
4412 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4413 springlist_ = sha1.Result();
4418 detachNewThreadSelector:@selector(_detachNewThreadData:)
4420 withObject:[[[ProgressData alloc]
4421 initWithSelector:selector
4428 - (void) repairWithSelector:(SEL)selector {
4430 detachNewThreadSelector:selector
4433 title:UCLocalize("REPAIRING")
4437 - (void) setConfigurationData:(NSString *)data {
4439 performSelectorOnMainThread:@selector(_setConfigurationData:)
4445 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4446 CYActionSheet *sheet([[[CYActionSheet alloc]
4448 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4449 defaultButtonIndex:0
4452 [sheet setMessage:error];
4453 [sheet yieldToPopupAlertAnimated:YES];
4457 - (void) setProgressTitle:(NSString *)title {
4459 performSelectorOnMainThread:@selector(_setProgressTitle:)
4465 - (void) setProgressPercent:(float)percent {
4467 performSelectorOnMainThread:@selector(_setProgressPercent:)
4468 withObject:[NSNumber numberWithFloat:percent]
4473 - (void) startProgress {
4476 - (void) addProgressOutput:(NSString *)output {
4478 performSelectorOnMainThread:@selector(_addProgressOutput:)
4484 - (bool) isCancelling:(size_t)received {
4488 - (void) _setConfigurationData:(NSString *)data {
4489 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4491 if (!conffile_r(data)) {
4492 lprintf("E:invalid conffile\n");
4496 NSString *ofile = conffile_r[1];
4497 //NSString *nfile = conffile_r[2];
4499 UIAlertView *alert = [[[UIAlertView alloc]
4500 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4501 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4503 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4504 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4505 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4509 [alert setContext:@"conffile"];
4513 - (void) _setProgressTitle:(NSString *)title {
4514 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4515 for (size_t i(0), e([words count]); i != e; ++i) {
4516 NSString *word([words objectAtIndex:i]);
4517 if (Package *package = [database_ packageWithName:word])
4518 [words replaceObjectAtIndex:i withObject:[package name]];
4521 [status_ setText:[words componentsJoinedByString:@" "]];
4524 - (void) _setProgressPercent:(NSNumber *)percent {
4525 [progress_ setProgress:[percent floatValue]];
4528 - (void) _addProgressOutput:(NSString *)output {
4529 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4530 CGSize size = [output_ contentSize];
4531 CGRect rect = {{0, size.height}, {size.width, 0}};
4532 [output_ scrollRectToVisible:rect animated:YES];
4535 - (BOOL) isRunning {
4542 /* Cell Content View {{{ */
4543 @protocol ContentDelegate
4544 - (void) drawContentRect:(CGRect)rect;
4547 @interface ContentView : UIView {
4548 _transient id<ContentDelegate> delegate_;
4553 @implementation ContentView
4555 - (id) initWithFrame:(CGRect)frame {
4556 if ((self = [super initWithFrame:frame]) != nil) {
4557 [self setNeedsDisplayOnBoundsChange:YES];
4561 - (void) setDelegate:(id<ContentDelegate>)delegate {
4562 delegate_ = delegate;
4565 - (void) drawRect:(CGRect)rect {
4566 [super drawRect:rect];
4567 [delegate_ drawContentRect:rect];
4572 /* Cydia TableView Cell {{{ */
4573 @interface CYTableViewCell : UITableViewCell {
4574 ContentView *content_;
4580 @implementation CYTableViewCell
4587 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4588 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4590 if (view == content_) {
4591 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4592 highlighted_ = highlighted;
4595 [super _updateHighlightColorsForView:view highlighted:highlighted];
4598 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4599 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4600 highlighted_ = selected;
4602 [super setSelected:selected animated:animated];
4603 [content_ setNeedsDisplay];
4608 /* Package Cell {{{ */
4609 @interface PackageCell : CYTableViewCell <
4614 NSString *description_;
4622 - (PackageCell *) init;
4623 - (void) setPackage:(Package *)package;
4625 + (int) heightForPackage:(Package *)package;
4626 - (void) drawContentRect:(CGRect)rect;
4630 @implementation PackageCell
4632 - (void) clearPackage {
4643 if (description_ != nil) {
4644 [description_ release];
4648 if (source_ != nil) {
4653 if (badge_ != nil) {
4658 if (placard_ != nil) {
4668 [self clearPackage];
4672 - (PackageCell *) init {
4673 CGRect frame(CGRectMake(0, 0, 320, 74));
4674 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4675 UIView *content([self contentView]);
4676 CGRect bounds([content bounds]);
4678 content_ = [[ContentView alloc] initWithFrame:bounds];
4679 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4680 [content addSubview:content_];
4682 [content_ setDelegate:self];
4683 [content_ setOpaque:YES];
4687 - (void) _setBackgroundColor {
4689 if (NSString *mode = [package_ mode]) {
4690 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4691 color = remove ? RemovingColor_ : InstallingColor_;
4693 color = [UIColor whiteColor];
4695 [content_ setBackgroundColor:color];
4696 [self setNeedsDisplay];
4699 - (void) setPackage:(Package *)package {
4700 [self clearPackage];
4703 Source *source = [package source];
4705 icon_ = [[package icon] retain];
4706 name_ = [[package name] retain];
4709 description_ = [package longDescription];
4710 if (description_ == nil)
4711 description_ = [package shortDescription];
4712 if (description_ != nil)
4713 description_ = [description_ retain];
4715 commercial_ = [package isCommercial];
4717 package_ = [package retain];
4719 NSString *label = nil;
4720 bool trusted = false;
4722 if (source != nil) {
4723 label = [source label];
4724 trusted = [source trusted];
4725 } else if ([[package id] isEqualToString:@"firmware"])
4726 label = UCLocalize("APPLE");
4728 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4730 NSString *from(label);
4732 NSString *section = [package simpleSection];
4733 if (section != nil && ![section isEqualToString:label]) {
4734 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4735 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4738 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4739 source_ = [from retain];
4741 if (NSString *purpose = [package primaryPurpose])
4742 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4743 badge_ = [badge_ retain];
4745 if ([package installed] != nil)
4746 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4747 placard_ = [placard_ retain];
4749 [self _setBackgroundColor];
4750 [content_ setNeedsDisplay];
4753 - (void) drawContentRect:(CGRect)rect {
4754 bool highlighted(highlighted_);
4755 float width([self bounds].size.width);
4758 CGContextRef context(UIGraphicsGetCurrentContext());
4759 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4760 CGContextFillRect(context, rect);
4765 rect.size = [icon_ size];
4767 rect.size.width /= 2;
4768 rect.size.height /= 2;
4770 rect.origin.x = 25 - rect.size.width / 2;
4771 rect.origin.y = 25 - rect.size.height / 2;
4773 [icon_ drawInRect:rect];
4776 if (badge_ != nil) {
4777 CGSize size = [badge_ size];
4779 [badge_ drawAtPoint:CGPointMake(
4780 36 - size.width / 2,
4781 36 - size.height / 2
4789 UISetColor(commercial_ ? Purple_ : Black_);
4790 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4791 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4794 UISetColor(commercial_ ? Purplish_ : Gray_);
4795 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4797 if (placard_ != nil)
4798 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4801 + (int) heightForPackage:(Package *)package {
4807 /* Section Cell {{{ */
4808 @interface SectionCell : CYTableViewCell <
4820 - (void) setSection:(Section *)section editing:(BOOL)editing;
4824 @implementation SectionCell
4826 - (void) clearSection {
4827 if (basic_ != nil) {
4832 if (section_ != nil) {
4842 if (count_ != nil) {
4849 [self clearSection];
4855 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4856 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4857 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4858 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4859 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4861 UIView *content([self contentView]);
4862 CGRect bounds([content bounds]);
4864 content_ = [[ContentView alloc] initWithFrame:bounds];
4865 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4866 [content addSubview:content_];
4867 [content_ setBackgroundColor:[UIColor whiteColor]];
4869 [content_ setDelegate:self];
4873 - (void) onSwitch:(id)sender {
4874 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4875 if (metadata == nil) {
4876 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4877 [Sections_ setObject:metadata forKey:basic_];
4881 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4884 - (void) setSection:(Section *)section editing:(BOOL)editing {
4885 if (editing != editing_) {
4887 [switch_ removeFromSuperview];
4889 [self addSubview:switch_];
4893 [self clearSection];
4895 if (section == nil) {
4896 name_ = [UCLocalize("ALL_PACKAGES") retain];
4899 basic_ = [section name];
4901 basic_ = [basic_ retain];
4903 section_ = [section localized];
4904 if (section_ != nil)
4905 section_ = [section_ retain];
4907 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4908 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4911 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4914 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4915 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
4917 [content_ setNeedsDisplay];
4920 - (void) setFrame:(CGRect)frame {
4921 [super setFrame:frame];
4923 CGRect rect([switch_ frame]);
4924 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4927 - (void) drawContentRect:(CGRect)rect {
4928 bool highlighted(highlighted_);
4930 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4935 float width(rect.size.width);
4941 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4943 CGSize size = [count_ sizeWithFont:Font14_];
4947 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4953 /* File Table {{{ */
4954 @interface FileTable : CYViewController <
4955 UITableViewDataSource,
4958 _transient Database *database_;
4961 NSMutableArray *files_;
4965 - (id) initWithDatabase:(Database *)database;
4966 - (void) setPackage:(Package *)package;
4970 @implementation FileTable
4973 if (package_ != nil)
4982 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
4983 return files_ == nil ? 0 : [files_ count];
4986 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
4990 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
4991 static NSString *reuseIdentifier = @"Cell";
4993 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
4995 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
4996 [cell setFont:[UIFont systemFontOfSize:16]];
4998 [cell setText:[files_ objectAtIndex:indexPath.row]];
4999 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5004 - (id) initWithDatabase:(Database *)database {
5005 if ((self = [super init]) != nil) {
5006 database_ = database;
5008 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5010 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5012 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5013 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5014 [list_ setRowHeight:24.0f];
5015 [[self view] addSubview:list_];
5017 [list_ setDataSource:self];
5018 [list_ setDelegate:self];
5022 - (void) setPackage:(Package *)package {
5023 if (package_ != nil) {
5024 [package_ autorelease];
5033 [files_ removeAllObjects];
5035 if (package != nil) {
5036 package_ = [package retain];
5037 name_ = [[package id] retain];
5039 if (NSArray *files = [package files])
5040 [files_ addObjectsFromArray:files];
5042 if ([files_ count] != 0) {
5043 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5044 [files_ removeObjectAtIndex:0];
5045 [files_ sortUsingSelector:@selector(compareByPath:)];
5047 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5048 [stack addObject:@"/"];
5050 for (int i(0), e([files_ count]); i != e; ++i) {
5051 NSString *file = [files_ objectAtIndex:i];
5052 while (![file hasPrefix:[stack lastObject]])
5053 [stack removeLastObject];
5054 NSString *directory = [stack lastObject];
5055 [stack addObject:[file stringByAppendingString:@"/"]];
5056 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5057 ([stack count] - 2) * 3, "",
5058 [file substringFromIndex:[directory length]]
5067 - (void) reloadData {
5068 [self setPackage:[database_ packageWithName:name_]];
5073 /* Package Controller {{{ */
5074 @interface PackageController : CYBrowserController <
5075 UIActionSheetDelegate
5077 _transient Database *database_;
5081 NSMutableArray *buttons_;
5082 UIBarButtonItem *button_;
5085 - (id) initWithDatabase:(Database *)database;
5086 - (void) setPackage:(Package *)package;
5090 @implementation PackageController
5093 if (package_ != nil)
5107 if ([self retainCount] == 1)
5108 [delegate_ setPackageController:self];
5112 /* XXX: this is not safe at all... localization of /fail/ */
5113 - (void) _clickButtonWithName:(NSString *)name {
5114 if ([name isEqualToString:UCLocalize("CLEAR")])
5115 [delegate_ clearPackage:package_];
5116 else if ([name isEqualToString:UCLocalize("INSTALL")])
5117 [delegate_ installPackage:package_];
5118 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5119 [delegate_ installPackage:package_];
5120 else if ([name isEqualToString:UCLocalize("REMOVE")])
5121 [delegate_ removePackage:package_];
5122 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5123 [delegate_ installPackage:package_];
5124 else _assert(false);
5127 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5128 NSString *context([sheet context]);
5130 if ([context isEqualToString:@"modify"]) {
5131 if (button != [sheet cancelButtonIndex]) {
5132 NSString *buttonName = [buttons_ objectAtIndex:button];
5133 [self _clickButtonWithName:buttonName];
5136 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5140 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5141 [super webView:view didClearWindowObject:window forFrame:frame];
5142 [window setValue:package_ forKey:@"package"];
5145 - (bool) _allowJavaScriptPanel {
5150 - (void) _customButtonClicked {
5151 int count([buttons_ count]);
5156 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5158 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5159 [buttons addObjectsFromArray:buttons_];
5161 UIActionSheet *sheet = [[[UIActionSheet alloc]
5164 cancelButtonTitle:nil
5165 destructiveButtonTitle:nil
5166 otherButtonTitles:nil
5169 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5171 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5172 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5174 [sheet setContext:@"modify"];
5176 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5180 // We don't want to allow non-commercial packages to do custom things to the install button,
5181 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5182 - (void) customButtonClicked {
5184 [super customButtonClicked];
5186 [self _customButtonClicked];
5189 - (void) reloadButtonClicked {
5190 // Don't reload a package view by clicking the button.
5193 - (void) applyLoadingTitle {
5194 // Don't show "Loading" as the title. Ever.
5197 - (UIBarButtonItem *) rightButton {
5202 - (id) initWithDatabase:(Database *)database {
5203 if ((self = [super init]) != nil) {
5204 database_ = database;
5205 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5206 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5210 - (void) setPackage:(Package *)package {
5211 if (package_ != nil) {
5212 [package_ autorelease];
5221 [buttons_ removeAllObjects];
5223 if (package != nil) {
5226 package_ = [package retain];
5227 name_ = [[package id] retain];
5228 commercial_ = [package isCommercial];
5230 if ([package_ mode] != nil)
5231 [buttons_ addObject:UCLocalize("CLEAR")];
5232 if ([package_ source] == nil);
5233 else if ([package_ upgradableAndEssential:NO])
5234 [buttons_ addObject:UCLocalize("UPGRADE")];
5235 else if ([package_ uninstalled])
5236 [buttons_ addObject:UCLocalize("INSTALL")];
5238 [buttons_ addObject:UCLocalize("REINSTALL")];
5239 if (![package_ uninstalled])
5240 [buttons_ addObject:UCLocalize("REMOVE")];
5247 switch ([buttons_ count]) {
5248 case 0: title = nil; break;
5249 case 1: title = [buttons_ objectAtIndex:0]; break;
5250 default: title = UCLocalize("MODIFY"); break;
5253 button_ = [[UIBarButtonItem alloc]
5255 style:UIBarButtonItemStylePlain
5257 action:@selector(customButtonClicked)
5263 - (bool) isLoading {
5264 return commercial_ ? [super isLoading] : false;
5267 - (void) reloadData {
5268 [self setPackage:[database_ packageWithName:name_]];
5273 /* Package Table {{{ */
5274 @interface PackageTable : UIView <
5275 UITableViewDataSource,
5278 _transient Database *database_;
5279 NSMutableArray *packages_;
5280 NSMutableArray *sections_;
5282 NSMutableArray *index_;
5283 NSMutableDictionary *indices_;
5284 // XXX: this target_ seems to be delegate_. :(
5285 _transient id target_;
5287 // XXX: why do we even have this delegate_?
5288 _transient id delegate_;
5291 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5293 - (void) setDelegate:(id)delegate;
5295 - (void) reloadData;
5296 - (void) resetCursor;
5298 - (UITableView *) list;
5300 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5302 - (void) deselectWithAnimation:(BOOL)animated;
5306 @implementation PackageTable
5309 [packages_ release];
5310 [sections_ release];
5318 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5319 NSInteger count([sections_ count]);
5320 return count == 0 ? 1 : count;
5323 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5324 if ([sections_ count] == 0)
5326 return [[sections_ objectAtIndex:section] name];
5329 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5330 if ([sections_ count] == 0)
5332 return [[sections_ objectAtIndex:section] count];
5335 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5336 Section *section([sections_ objectAtIndex:[path section]]);
5337 NSInteger row([path row]);
5338 Package *package([packages_ objectAtIndex:([section row] + row)]);
5342 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5343 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5345 cell = [[[PackageCell alloc] init] autorelease];
5346 [cell setPackage:[self packageAtIndexPath:path]];
5350 - (void) deselectWithAnimation:(BOOL)animated {
5351 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5354 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5355 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5358 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5359 Package *package([self packageAtIndexPath:path]);
5360 package = [database_ packageWithName:[package id]];
5361 [target_ performSelector:action_ withObject:package];
5365 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5366 return [packages_ count] > 20 ? index_ : nil;
5369 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5373 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5374 if ((self = [super initWithFrame:frame]) != nil) {
5375 database_ = database;
5380 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5381 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5383 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5384 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5386 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5387 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5388 [list_ setRowHeight:73.0f];
5389 [self addSubview:list_];
5391 [list_ setDataSource:self];
5392 [list_ setDelegate:self];
5396 - (void) setDelegate:(id)delegate {
5397 delegate_ = delegate;
5400 - (bool) hasPackage:(Package *)package {
5404 - (void) reloadData {
5405 NSArray *packages = [database_ packages];
5407 [packages_ removeAllObjects];
5408 [sections_ removeAllObjects];
5410 _profile(PackageTable$reloadData$Filter)
5411 for (Package *package in packages)
5412 if ([self hasPackage:package])
5413 [packages_ addObject:package];
5416 [index_ removeAllObjects];
5417 [indices_ removeAllObjects];
5419 Section *section = nil;
5421 _profile(PackageTable$reloadData$Section)
5422 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5426 _profile(PackageTable$reloadData$Section$Package)
5427 package = [packages_ objectAtIndex:offset];
5428 index = [package index];
5431 if (section == nil || [section index] != index) {
5432 _profile(PackageTable$reloadData$Section$Allocate)
5433 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5436 [index_ addObject:[section name]];
5437 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5439 _profile(PackageTable$reloadData$Section$Add)
5440 [sections_ addObject:section];
5444 [section addToCount];
5448 _profile(PackageTable$reloadData$List)
5453 - (void) resetCursor {
5454 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5457 - (UITableView *) list {
5461 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5462 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5467 /* Filtered Package Table {{{ */
5468 @interface FilteredPackageTable : PackageTable {
5474 - (void) setObject:(id)object;
5475 - (void) setObject:(id)object forFilter:(SEL)filter;
5477 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5481 @implementation FilteredPackageTable
5489 - (void) setFilter:(SEL)filter {
5492 /* XXX: this is an unsafe optimization of doomy hell */
5493 Method method(class_getInstanceMethod([Package class], filter));
5494 _assert(method != NULL);
5495 imp_ = method_getImplementation(method);
5496 _assert(imp_ != NULL);
5499 - (void) setObject:(id)object {
5505 object_ = [object retain];
5508 - (void) setObject:(id)object forFilter:(SEL)filter {
5509 [self setFilter:filter];
5510 [self setObject:object];
5513 - (bool) hasPackage:(Package *)package {
5514 _profile(FilteredPackageTable$hasPackage)
5515 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5519 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5520 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5521 [self setFilter:filter];
5522 object_ = [object retain];
5530 /* Filtered Package Controller {{{ */
5531 @interface FilteredPackageController : CYViewController {
5532 _transient Database *database_;
5533 FilteredPackageTable *packages_;
5537 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5541 @implementation FilteredPackageController
5544 [packages_ release];
5550 - (void) viewDidAppear:(BOOL)animated {
5551 [super viewDidAppear:animated];
5552 [packages_ deselectWithAnimation:animated];
5555 - (void) didSelectPackage:(Package *)package {
5556 PackageController *view([delegate_ packageController]);
5557 [view setPackage:package];
5558 [view setDelegate:delegate_];
5559 [[self navigationController] pushViewController:view animated:YES];
5562 - (NSString *) title { return title_; }
5564 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5565 if ((self = [super init]) != nil) {
5566 database_ = database;
5567 title_ = [title copy];
5568 [[self navigationItem] setTitle:title_];
5570 packages_ = [[FilteredPackageTable alloc]
5571 initWithFrame:[[self view] bounds]
5574 action:@selector(didSelectPackage:)
5579 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5580 [[self view] addSubview:packages_];
5584 - (void) reloadData {
5585 [packages_ reloadData];
5588 - (void) setDelegate:(id)delegate {
5589 [super setDelegate:delegate];
5590 [packages_ setDelegate:delegate];
5597 /* Add Source Controller {{{ */
5598 @interface AddSourceController : CYViewController {
5599 _transient Database *database_;
5602 - (id) initWithDatabase:(Database *)database;
5606 @implementation AddSourceController
5608 - (id) initWithDatabase:(Database *)database {
5609 if ((self = [super init]) != nil) {
5610 database_ = database;
5616 /* Source Cell {{{ */
5617 @interface SourceCell : CYTableViewCell <
5622 NSString *description_;
5626 - (void) setSource:(Source *)source;
5630 @implementation SourceCell
5632 - (void) clearSource {
5635 [description_ release];
5644 - (void) setSource:(Source *)source {
5648 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5650 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5651 icon_ = [icon_ retain];
5653 origin_ = [[source name] retain];
5654 label_ = [[source uri] retain];
5655 description_ = [[source description] retain];
5657 [content_ setNeedsDisplay];
5665 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5666 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5667 UIView *content([self contentView]);
5668 CGRect bounds([content bounds]);
5670 content_ = [[ContentView alloc] initWithFrame:bounds];
5671 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5672 [content_ setBackgroundColor:[UIColor whiteColor]];
5673 [content addSubview:content_];
5675 [content_ setDelegate:self];
5676 [content_ setOpaque:YES];
5680 - (void) drawContentRect:(CGRect)rect {
5681 bool highlighted(highlighted_);
5682 float width(rect.size.width);
5685 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5692 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5696 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5700 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5705 /* Source Table {{{ */
5706 @interface SourceTable : CYViewController <
5707 UITableViewDataSource,
5710 _transient Database *database_;
5712 NSMutableArray *sources_;
5716 UIProgressHUD *hud_;
5719 //NSURLConnection *installer_;
5720 NSURLConnection *trivial_;
5721 NSURLConnection *trivial_bz2_;
5722 NSURLConnection *trivial_gz_;
5723 //NSURLConnection *automatic_;
5728 - (id) initWithDatabase:(Database *)database;
5730 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5734 @implementation SourceTable
5736 - (void) _releaseConnection:(NSURLConnection *)connection {
5737 if (connection != nil) {
5738 [connection cancel];
5739 //[connection setDelegate:nil];
5740 [connection release];
5752 //[self _releaseConnection:installer_];
5753 [self _releaseConnection:trivial_];
5754 [self _releaseConnection:trivial_gz_];
5755 [self _releaseConnection:trivial_bz2_];
5756 //[self _releaseConnection:automatic_];
5763 - (void) viewDidAppear:(BOOL)animated {
5764 [super viewDidAppear:animated];
5765 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5768 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5769 return offset_ == 0 ? 1 : 2;
5772 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5773 switch (section + (offset_ == 0 ? 1 : 0)) {
5774 case 0: return UCLocalize("ENTERED_BY_USER");
5775 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5781 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5782 int count = [sources_ count];
5784 case 0: return (offset_ == 0 ? count : offset_);
5785 case 1: return count - offset_;
5791 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5793 switch (indexPath.section) {
5794 case 0: idx = indexPath.row; break;
5795 case 1: idx = indexPath.row + offset_; break;
5799 return [sources_ objectAtIndex:idx];
5802 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5803 Source *source = [self sourceAtIndexPath:indexPath];
5804 return [source description] == nil ? 56 : 73;
5807 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5808 static NSString *cellIdentifier = @"SourceCell";
5810 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5811 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5812 [cell setSource:[self sourceAtIndexPath:indexPath]];
5817 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5818 return UITableViewCellAccessoryDisclosureIndicator;
5821 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5822 Source *source = [self sourceAtIndexPath:indexPath];
5824 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5825 initWithDatabase:database_
5826 title:[source label]
5827 filter:@selector(isVisibleInSource:)
5831 [packages setDelegate:delegate_];
5833 [[self navigationController] pushViewController:packages animated:YES];
5836 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5837 Source *source = [self sourceAtIndexPath:indexPath];
5838 return [source record] != nil;
5841 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5842 Source *source = [self sourceAtIndexPath:indexPath];
5843 [Sources_ removeObjectForKey:[source key]];
5844 [delegate_ syncData];
5848 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5851 @"./", @"Distribution",
5852 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5854 [delegate_ syncData];
5857 - (NSString *) getWarning {
5858 NSString *href(href_);
5859 NSRange colon([href rangeOfString:@"://"]);
5860 if (colon.location != NSNotFound)
5861 href = [href substringFromIndex:(colon.location + 3)];
5862 href = [href stringByAddingPercentEscapes];
5863 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5864 href = [href stringByCachingURLWithCurrentCDN];
5866 NSURL *url([NSURL URLWithString:href]);
5868 NSStringEncoding encoding;
5869 NSError *error(nil);
5871 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5872 return [warning length] == 0 ? nil : warning;
5876 - (void) _endConnection:(NSURLConnection *)connection {
5877 // XXX: the memory management in this method is horribly awkward
5879 NSURLConnection **field = NULL;
5880 if (connection == trivial_)
5882 else if (connection == trivial_bz2_)
5883 field = &trivial_bz2_;
5884 else if (connection == trivial_gz_)
5885 field = &trivial_gz_;
5886 _assert(field != NULL);
5887 [connection release];
5892 trivial_bz2_ == nil &&
5898 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5901 UIAlertView *alert = [[[UIAlertView alloc]
5902 initWithTitle:UCLocalize("SOURCE_WARNING")
5905 cancelButtonTitle:UCLocalize("CANCEL")
5906 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5909 [alert setContext:@"warning"];
5910 [alert setNumberOfRows:1];
5914 } else if (error_ != nil) {
5915 UIAlertView *alert = [[[UIAlertView alloc]
5916 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5917 message:[error_ localizedDescription]
5919 cancelButtonTitle:UCLocalize("OK")
5920 otherButtonTitles:nil
5923 [alert setContext:@"urlerror"];
5926 UIAlertView *alert = [[[UIAlertView alloc]
5927 initWithTitle:UCLocalize("NOT_REPOSITORY")
5928 message:UCLocalize("NOT_REPOSITORY_EX")
5930 cancelButtonTitle:UCLocalize("OK")
5931 otherButtonTitles:nil
5934 [alert setContext:@"trivial"];
5938 [delegate_ setStatusBarShowsProgress:NO];
5939 [delegate_ removeProgressHUD:hud_];
5949 if (error_ != nil) {
5956 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5957 switch ([response statusCode]) {
5963 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5964 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5966 error_ = [error retain];
5967 [self _endConnection:connection];
5970 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5971 [self _endConnection:connection];
5974 - (NSString *) title { return UCLocalize("SOURCES"); }
5976 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5977 NSMutableURLRequest *request = [NSMutableURLRequest
5978 requestWithURL:[NSURL URLWithString:href]
5979 cachePolicy:NSURLRequestUseProtocolCachePolicy
5980 timeoutInterval:120.0
5983 [request setHTTPMethod:method];
5985 if (Machine_ != NULL)
5986 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5987 if (UniqueID_ != nil)
5988 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5990 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5992 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5995 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5996 NSString *context([alert context]);
5998 if ([context isEqualToString:@"source"]) {
6001 NSString *href = [[alert textField] text];
6003 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6005 if (![href hasSuffix:@"/"])
6006 href_ = [href stringByAppendingString:@"/"];
6009 href_ = [href_ retain];
6011 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6012 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6013 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6014 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6018 // XXX: this is stupid
6019 hud_ = [[delegate_ addProgressHUD] retain];
6020 [hud_ setText:UCLocalize("VERIFYING_URL")];
6029 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6030 } else if ([context isEqualToString:@"trivial"])
6031 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6032 else if ([context isEqualToString:@"urlerror"])
6033 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6034 else if ([context isEqualToString:@"warning"]) {
6049 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6053 - (id) initWithDatabase:(Database *)database {
6054 if ((self = [super init]) != nil) {
6055 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6056 [self updateButtonsForEditingStatus:NO animated:NO];
6058 database_ = database;
6059 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6061 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6062 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6063 [[self view] addSubview:list_];
6065 [list_ setDataSource:self];
6066 [list_ setDelegate:self];
6072 - (void) reloadData {
6074 if (!list.ReadMainList())
6077 [sources_ removeAllObjects];
6078 [sources_ addObjectsFromArray:[database_ sources]];
6080 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6083 int count([sources_ count]);
6085 for (int i = 0; i != count; i++) {
6086 if ([[sources_ objectAtIndex:i] record] == nil)
6091 [list_ setEditing:NO];
6092 [self updateButtonsForEditingStatus:NO animated:NO];
6096 - (void) addButtonClicked {
6097 /*[book_ pushPage:[[[AddSourceController alloc]
6102 UIAlertView *alert = [[[UIAlertView alloc]
6103 initWithTitle:UCLocalize("ENTER_APT_URL")
6106 cancelButtonTitle:UCLocalize("CANCEL")
6107 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6110 [alert setContext:@"source"];
6111 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6113 [alert setNumberOfRows:1];
6114 [alert addTextFieldWithValue:@"http://" label:@""];
6116 UITextInputTraits *traits = [[alert textField] textInputTraits];
6117 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6118 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6119 [traits setKeyboardType:UIKeyboardTypeURL];
6120 // XXX: UIReturnKeyDone
6121 [traits setReturnKeyType:UIReturnKeyNext];
6126 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6127 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6128 initWithTitle:UCLocalize("ADD")
6129 style:UIBarButtonItemStylePlain
6131 action:@selector(addButtonClicked)
6132 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6134 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6135 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6136 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6138 action:@selector(editButtonClicked)
6139 ] autorelease] animated:animated];
6141 if (IsWildcat_ && !editing)
6142 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6143 initWithTitle:UCLocalize("SETTINGS")
6144 style:UIBarButtonItemStylePlain
6146 action:@selector(settingsButtonClicked)
6150 - (void) settingsButtonClicked {
6151 [delegate_ showSettings];
6154 - (void) editButtonClicked {
6155 [list_ setEditing:![list_ isEditing] animated:YES];
6157 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6163 /* Installed Controller {{{ */
6164 @interface InstalledController : FilteredPackageController {
6168 - (id) initWithDatabase:(Database *)database;
6170 - (void) updateRoleButton;
6171 - (void) queueStatusDidChange;
6175 @implementation InstalledController
6181 - (NSString *) title { return UCLocalize("INSTALLED"); }
6183 - (id) initWithDatabase:(Database *)database {
6184 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
6185 [self updateRoleButton];
6186 [self queueStatusDidChange];
6191 - (void) queueButtonClicked {
6196 - (void) queueStatusDidChange {
6200 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6201 initWithTitle:UCLocalize("QUEUE")
6202 style:UIBarButtonItemStyleDone
6204 action:@selector(queueButtonClicked)
6207 [[self navigationItem] setLeftBarButtonItem:nil];
6213 - (void) reloadData {
6214 [packages_ reloadData];
6217 - (void) updateRoleButton {
6218 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6219 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6220 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6221 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6223 action:@selector(roleButtonClicked)
6227 - (void) roleButtonClicked {
6228 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6229 [packages_ reloadData];
6232 [self updateRoleButton];
6235 - (void) setDelegate:(id)delegate {
6236 [super setDelegate:delegate];
6237 [packages_ setDelegate:delegate];
6243 /* Home Controller {{{ */
6244 @interface HomeController : CYBrowserController {
6249 @implementation HomeController
6251 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6252 [super _setMoreHeaders:request];
6255 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6256 if (UniqueID_ != nil)
6257 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6259 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6262 - (void) aboutButtonClicked {
6263 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6265 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6266 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6267 [alert setCancelButtonIndex:0];
6270 @"Copyright (C) 2008-2010\n"
6271 "Jay Freeman (saurik)\n"
6272 "saurik@saurik.com\n"
6273 "http://www.saurik.com/"
6279 - (void) viewWillAppear:(BOOL)animated {
6280 [super viewWillAppear:animated];
6281 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6284 - (void) viewWillDisappear:(BOOL)animated {
6285 [super viewWillDisappear:animated];
6286 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6290 if ((self = [super init]) != nil) {
6291 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6292 initWithTitle:UCLocalize("ABOUT")
6293 style:UIBarButtonItemStylePlain
6295 action:@selector(aboutButtonClicked)
6302 /* Manage Controller {{{ */
6303 @interface ManageController : CYBrowserController {
6306 - (void) queueStatusDidChange;
6309 @implementation ManageController
6312 if ((self = [super init]) != nil) {
6313 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6315 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6316 initWithTitle:UCLocalize("SETTINGS")
6317 style:UIBarButtonItemStylePlain
6319 action:@selector(settingsButtonClicked)
6322 [self queueStatusDidChange];
6326 - (void) settingsButtonClicked {
6327 [delegate_ showSettings];
6331 - (void) queueButtonClicked {
6335 - (void) applyLoadingTitle {
6336 // No "Loading" title.
6339 - (void) applyRightButton {
6344 - (void) queueStatusDidChange {
6346 if (!IsWildcat_ && Queuing_) {
6347 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6348 initWithTitle:UCLocalize("QUEUE")
6349 style:UIBarButtonItemStyleDone
6351 action:@selector(queueButtonClicked)
6354 [[self navigationItem] setRightBarButtonItem:nil];
6359 - (bool) isLoading {
6366 /* Refresh Bar {{{ */
6367 @interface RefreshBar : UINavigationBar {
6368 UIProgressIndicator *indicator_;
6369 UITextLabel *prompt_;
6370 UIProgressBar *progress_;
6371 UINavigationButton *cancel_;
6376 @implementation RefreshBar
6379 [indicator_ release];
6381 [progress_ release];
6386 - (void) positionViews {
6387 CGRect frame = [cancel_ frame];
6388 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6389 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6390 [cancel_ setFrame:frame];
6392 CGSize prgsize = {75, 100};
6394 [self frame].size.width - prgsize.width - 10,
6395 ([self frame].size.height - prgsize.height) / 2
6397 [progress_ setFrame:prgrect];
6399 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6400 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6401 CGRect indrect = {{indoffset, indoffset}, indsize};
6402 [indicator_ setFrame:indrect];
6404 CGSize prmsize = {215, indsize.height + 4};
6406 indoffset * 2 + indsize.width,
6407 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6409 [prompt_ setFrame:prmrect];
6412 - (void)setFrame:(CGRect)frame {
6413 [super setFrame:frame];
6415 [self positionViews];
6418 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6419 if ((self = [super initWithFrame:frame])) {
6420 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6422 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6423 [self setBarStyle:UIBarStyleBlack];
6425 UIBarStyle barstyle([self _barStyle:NO]);
6426 bool ugly(barstyle == UIBarStyleDefault);
6428 UIProgressIndicatorStyle style = ugly ?
6429 UIProgressIndicatorStyleMediumBrown :
6430 UIProgressIndicatorStyleMediumWhite;
6432 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6433 [indicator_ setStyle:style];
6434 [indicator_ startAnimation];
6435 [self addSubview:indicator_];
6437 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6438 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6439 [prompt_ setBackgroundColor:[UIColor clearColor]];
6440 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6441 [self addSubview:prompt_];
6443 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6444 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6445 [progress_ setStyle:0];
6446 [self addSubview:progress_];
6448 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6449 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6450 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6451 [cancel_ setBarStyle:barstyle];
6453 [self positionViews];
6458 [cancel_ removeFromSuperview];
6462 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6463 [progress_ setProgress:0];
6464 [self addSubview:cancel_];
6468 [cancel_ removeFromSuperview];
6471 - (void) setPrompt:(NSString *)prompt {
6472 [prompt_ setText:prompt];
6475 - (void) setProgress:(float)progress {
6476 [progress_ setProgress:progress];
6482 @class CYNavigationController;
6484 /* Cydia Tab Bar Controller {{{ */
6485 @interface CYTabBarController : UITabBarController {
6486 _transient Database *database_;
6491 @implementation CYTabBarController
6493 /* XXX: some logic should probably go here related to
6494 freeing the view controllers on tab change */
6496 - (void) reloadData {
6497 size_t count([[self viewControllers] count]);
6498 for (size_t i(0); i != count; ++i) {
6499 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6504 - (id) initWithDatabase:(Database *)database {
6505 if ((self = [super init]) != nil) {
6506 database_ = database;
6513 /* Cydia Navigation Controller {{{ */
6514 @interface CYNavigationController : UINavigationController {
6515 _transient Database *database_;
6516 _transient id<UINavigationControllerDelegate> delegate_;
6519 - (id) initWithDatabase:(Database *)database;
6520 - (void) reloadData;
6525 @implementation CYNavigationController
6527 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6528 // Inherit autorotation settings for modal parents.
6529 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6530 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6532 return [super shouldAutorotateToInterfaceOrientation:orientation];
6540 - (void) reloadData {
6541 size_t count([[self viewControllers] count]);
6542 for (size_t i(0); i != count; ++i) {
6543 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6548 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6549 delegate_ = delegate;
6552 - (id) initWithDatabase:(Database *)database {
6553 if ((self = [super init]) != nil) {
6554 database_ = database;
6560 /* Cydia:// Protocol {{{ */
6561 @interface CydiaURLProtocol : NSURLProtocol {
6566 @implementation CydiaURLProtocol
6568 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6569 NSURL *url([request URL]);
6572 NSString *scheme([[url scheme] lowercaseString]);
6573 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6578 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6582 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6583 id<NSURLProtocolClient> client([self client]);
6585 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6587 NSData *data(UIImagePNGRepresentation(icon));
6589 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6590 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6591 [client URLProtocol:self didLoadData:data];
6592 [client URLProtocolDidFinishLoading:self];
6596 - (void) startLoading {
6597 id<NSURLProtocolClient> client([self client]);
6598 NSURLRequest *request([self request]);
6600 NSURL *url([request URL]);
6601 NSString *href([url absoluteString]);
6603 NSString *path([href substringFromIndex:8]);
6604 NSRange slash([path rangeOfString:@"/"]);
6607 if (slash.location == NSNotFound) {
6611 command = [path substringToIndex:slash.location];
6612 path = [path substringFromIndex:(slash.location + 1)];
6615 Database *database([Database sharedInstance]);
6617 if ([command isEqualToString:@"package-icon"]) {
6620 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6621 Package *package([database packageWithName:path]);
6624 UIImage *icon([package icon]);
6625 [self _returnPNGWithImage:icon forRequest:request];
6626 } else if ([command isEqualToString:@"source-icon"]) {
6629 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6630 NSString *source(Simplify(path));
6631 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6633 icon = [UIImage applicationImageNamed:@"unknown.png"];
6634 [self _returnPNGWithImage:icon forRequest:request];
6635 } else if ([command isEqualToString:@"uikit-image"]) {
6638 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6639 UIImage *icon(_UIImageWithName(path));
6640 [self _returnPNGWithImage:icon forRequest:request];
6641 } else if ([command isEqualToString:@"section-icon"]) {
6644 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6645 NSString *section(Simplify(path));
6646 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6648 icon = [UIImage applicationImageNamed:@"unknown.png"];
6649 [self _returnPNGWithImage:icon forRequest:request];
6651 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6655 - (void) stopLoading {
6661 /* Sections Controller {{{ */
6662 @interface SectionsController : CYViewController <
6663 UITableViewDataSource,
6666 _transient Database *database_;
6667 NSMutableArray *sections_;
6668 NSMutableArray *filtered_;
6674 - (id) initWithDatabase:(Database *)database;
6675 - (void) reloadData;
6678 - (void) editButtonClicked;
6682 @implementation SectionsController
6685 [list_ setDataSource:nil];
6686 [list_ setDelegate:nil];
6688 [sections_ release];
6689 [filtered_ release];
6691 [accessory_ release];
6695 - (void) viewDidAppear:(BOOL)animated {
6696 [super viewDidAppear:animated];
6697 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6700 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6701 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6705 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6706 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6709 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6713 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6714 static NSString *reuseIdentifier = @"SectionCell";
6716 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6718 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6720 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6725 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6729 Section *section = [self sectionAtIndexPath:indexPath];
6730 NSString *name = [section name];
6733 if ([indexPath row] == 0) {
6736 title = UCLocalize("ALL_PACKAGES");
6739 name = [NSString stringWithString:name];
6740 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6743 title = UCLocalize("NO_SECTION");
6747 FilteredPackageController *table = [[[FilteredPackageController alloc]
6748 initWithDatabase:database_
6750 filter:@selector(isVisibleInSection:)
6754 [table setDelegate:delegate_];
6756 [[self navigationController] pushViewController:table animated:YES];
6759 - (NSString *) title { return UCLocalize("SECTIONS"); }
6761 - (id) initWithDatabase:(Database *)database {
6762 if ((self = [super init]) != nil) {
6763 database_ = database;
6765 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6767 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6768 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6770 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6771 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6772 [list_ setRowHeight:45.0f];
6773 [[self view] addSubview:list_];
6775 [list_ setDataSource:self];
6776 [list_ setDelegate:self];
6782 - (void) reloadData {
6783 NSArray *packages = [database_ packages];
6785 [sections_ removeAllObjects];
6786 [filtered_ removeAllObjects];
6788 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6791 for (Package *package in packages) {
6792 NSString *name([package section]);
6793 NSString *key(name == nil ? @"" : name);
6797 _profile(SectionsView$reloadData$Section)
6798 section = [sections objectForKey:key];
6799 if (section == nil) {
6800 _profile(SectionsView$reloadData$Section$Allocate)
6801 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6802 [sections setObject:section forKey:key];
6807 [section addToCount];
6809 _profile(SectionsView$reloadData$Filter)
6810 if (![package valid] || ![package visible])
6818 [sections_ addObjectsFromArray:[sections allValues]];
6820 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6822 for (Section *section in sections_) {
6823 size_t count([section row]);
6827 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6828 [section setCount:count];
6829 [filtered_ addObject:section];
6832 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6833 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
6834 style:UIBarButtonItemStylePlain
6836 action:@selector(editButtonClicked)
6837 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6843 - (void) resetView {
6845 [self editButtonClicked];
6848 - (void) editButtonClicked {
6849 if ((editing_ = !editing_))
6852 [delegate_ updateData];
6854 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6855 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6856 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6859 - (UIView *) accessoryView {
6865 /* Changes Controller {{{ */
6866 @interface ChangesController : CYViewController <
6867 UITableViewDataSource,
6870 _transient Database *database_;
6871 CFMutableArrayRef packages_;
6872 NSMutableArray *sections_;
6875 BOOL hasSentFirstLoad_;
6878 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6879 - (void) reloadData;
6883 @implementation ChangesController
6886 [list_ setDelegate:nil];
6887 [list_ setDataSource:nil];
6889 CFRelease(packages_);
6891 [sections_ release];
6896 - (void) viewDidAppear:(BOOL)animated {
6897 [super viewDidAppear:animated];
6898 if (!hasSentFirstLoad_) {
6899 hasSentFirstLoad_ = YES;
6900 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6902 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6906 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6907 NSInteger count([sections_ count]);
6908 return count == 0 ? 1 : count;
6911 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6912 if ([sections_ count] == 0)
6914 return [[sections_ objectAtIndex:section] name];
6917 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6918 if ([sections_ count] == 0)
6920 return [[sections_ objectAtIndex:section] count];
6923 - (Package *) packageAtIndex:(NSUInteger)index {
6924 return (Package *) CFArrayGetValueAtIndex(packages_, index);
6927 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6928 Section *section([sections_ objectAtIndex:[path section]]);
6929 NSInteger row([path row]);
6930 return [self packageAtIndex:([section row] + row)];
6933 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6934 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6936 cell = [[[PackageCell alloc] init] autorelease];
6937 [cell setPackage:[self packageAtIndexPath:path]];
6941 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
6942 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
6945 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6946 Package *package([self packageAtIndexPath:path]);
6947 PackageController *view([delegate_ packageController]);
6948 [view setDelegate:delegate_];
6949 [view setPackage:package];
6950 [[self navigationController] pushViewController:view animated:YES];
6954 - (void) refreshButtonClicked {
6955 [delegate_ beginUpdate];
6956 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
6959 - (void) upgradeButtonClicked {
6960 [delegate_ distUpgrade];
6963 - (NSString *) title { return UCLocalize("CHANGES"); }
6965 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
6966 if ((self = [super init]) != nil) {
6967 database_ = database;
6968 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
6970 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
6972 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6974 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6975 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6976 [list_ setRowHeight:73.0f];
6977 [[self view] addSubview:list_];
6979 [list_ setDataSource:self];
6980 [list_ setDelegate:self];
6982 delegate_ = delegate;
6986 - (void) _reloadPackages:(NSArray *)packages {
6988 for (Package *package in packages)
6989 if ([package upgradableAndEssential:YES] || [package visible])
6990 CFArrayAppendValue(packages_, package);
6993 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6997 - (void) reloadData {
6998 NSArray *packages = [database_ packages];
7000 CFArrayRemoveAllValues(packages_);
7002 [sections_ removeAllObjects];
7005 UIProgressHUD *hud([delegate_ addProgressHUD]);
7006 [hud setText:UCLocalize("LOADING")];
7007 //NSLog(@"HUD:%@::%@", delegate_, hud);
7008 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7009 [delegate_ removeProgressHUD:hud];
7011 [self _reloadPackages:packages];
7014 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7015 Section *ignored = nil;
7016 Section *section = nil;
7020 bool unseens = false;
7022 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7024 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7025 Package *package = [self packageAtIndex:offset];
7027 BOOL uae = [package upgradableAndEssential:YES];
7031 time_t seen([package seen]);
7033 if (section == nil || last != seen) {
7037 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7040 _profile(ChangesController$reloadData$Allocate)
7041 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7042 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7043 [sections_ addObject:section];
7047 [section addToCount];
7048 } else if ([package ignored]) {
7049 if (ignored == nil) {
7050 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7052 [ignored addToCount];
7055 [upgradable addToCount];
7060 CFRelease(formatter);
7063 Section *last = [sections_ lastObject];
7064 size_t count = [last count];
7065 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7066 [sections_ removeLastObject];
7069 if ([ignored count] != 0)
7070 [sections_ insertObject:ignored atIndex:0];
7072 [sections_ insertObject:upgradable atIndex:0];
7077 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7078 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7079 style:UIBarButtonItemStylePlain
7081 action:@selector(upgradeButtonClicked)
7084 if (![delegate_ updating])
7085 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7086 initWithTitle:UCLocalize("REFRESH")
7087 style:UIBarButtonItemStylePlain
7089 action:@selector(refreshButtonClicked)
7095 /* Search Controller {{{ */
7096 @interface SearchController : FilteredPackageController <
7099 UISearchBar *search_;
7102 - (id) initWithDatabase:(Database *)database;
7103 - (void) reloadData;
7107 @implementation SearchController
7114 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7115 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7116 [search_ resignFirstResponder];
7120 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7121 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7125 - (NSString *) title { return nil; }
7127 - (id) initWithDatabase:(Database *)database {
7128 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7131 - (void)viewDidAppear:(BOOL)animated {
7132 [super viewDidAppear:animated];
7134 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7135 [search_ layoutSubviews];
7136 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7137 UITextField *textField = [search_ searchField];
7138 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7139 [search_ setDelegate:self];
7140 [textField setEnablesReturnKeyAutomatically:NO];
7141 [[self navigationItem] setTitleView:textField];
7145 - (void) _reloadData {
7148 - (void) reloadData {
7149 _profile(SearchController$reloadData)
7150 [packages_ reloadData];
7153 [packages_ resetCursor];
7156 - (void) didSelectPackage:(Package *)package {
7157 [search_ resignFirstResponder];
7158 [super didSelectPackage:package];
7163 /* Settings Controller {{{ */
7164 @interface SettingsController : CYViewController <
7165 UITableViewDataSource,
7168 _transient Database *database_;
7171 UITableView *table_;
7172 UISwitch *subscribedSwitch_;
7173 UISwitch *ignoredSwitch_;
7174 UITableViewCell *subscribedCell_;
7175 UITableViewCell *ignoredCell_;
7178 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7182 @implementation SettingsController
7186 if (package_ != nil)
7189 [subscribedSwitch_ release];
7190 [ignoredSwitch_ release];
7191 [subscribedCell_ release];
7192 [ignoredCell_ release];
7197 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7198 if (package_ == nil)
7204 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7205 if (package_ == nil)
7211 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7212 return UCLocalize("SHOW_ALL_CHANGES_EX");
7215 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7216 if (package_ == nil)
7219 NSMutableDictionary *metadata([package_ metadata]);
7222 if (NSNumber *number = [metadata objectForKey:key])
7223 before = [number boolValue];
7227 if (value != before) {
7228 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7230 [delegate_ updateData];
7234 - (void) onSubscribed:(id)control {
7235 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7238 - (void) onIgnored:(id)control {
7239 // TODO: set Held state - possibly call out to dpkg, etc.
7242 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7243 if (package_ == nil)
7246 switch ([indexPath row]) {
7247 case 0: return subscribedCell_;
7248 case 1: return ignoredCell_;
7256 - (NSString *) title { return UCLocalize("SETTINGS"); }
7258 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7259 if ((self = [super init])) {
7260 database_ = database;
7261 name_ = [package retain];
7263 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7265 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7266 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7267 [[self view] addSubview:table_];
7269 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7270 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7271 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7273 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7274 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7275 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7277 subscribedCell_ = [[UITableViewCell alloc] init];
7278 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7279 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7280 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7282 ignoredCell_ = [[UITableViewCell alloc] init];
7283 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7284 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7285 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7287 [table_ setDataSource:self];
7288 [table_ setDelegate:self];
7293 - (void) reloadData {
7294 if (package_ != nil)
7295 [package_ autorelease];
7296 package_ = [database_ packageWithName:name_];
7297 if (package_ != nil) {
7299 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7300 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7303 [table_ reloadData];
7308 /* Signature Controller {{{ */
7309 @interface SignatureController : CYBrowserController {
7310 _transient Database *database_;
7314 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7318 @implementation SignatureController
7325 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7327 [super webView:view didClearWindowObject:window forFrame:frame];
7330 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7331 if ((self = [super init]) != nil) {
7332 database_ = database;
7333 package_ = [package retain];
7338 - (void) reloadData {
7339 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7345 /* Role Controller {{{ */
7346 @interface RoleController : CYViewController <
7347 UITableViewDataSource,
7350 _transient Database *database_;
7351 // XXX: ok, "roledelegate_"?...
7352 _transient id roledelegate_;
7353 UITableView *table_;
7354 UISegmentedControl *segment_;
7358 - (void) showDoneButton;
7359 - (void) resizeSegmentedControl;
7363 @implementation RoleController
7367 [container_ release];
7372 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7373 if ((self = [super init])) {
7374 database_ = database;
7375 roledelegate_ = delegate;
7377 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7379 NSArray *items = [NSArray arrayWithObjects:
7381 UCLocalize("HACKER"),
7382 UCLocalize("DEVELOPER"),
7384 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7385 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7386 [container_ addSubview:segment_];
7389 if ([Role_ isEqualToString:@"User"]) index = 0;
7390 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7391 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7393 [segment_ setSelectedSegmentIndex:index];
7394 [self showDoneButton];
7397 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7398 [self resizeSegmentedControl];
7400 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7401 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7402 [table_ setDelegate:self];
7403 [table_ setDataSource:self];
7404 [[self view] addSubview:table_];
7405 [table_ reloadData];
7409 - (void) resizeSegmentedControl {
7410 CGFloat width = [[self view] frame].size.width;
7411 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7414 - (void) viewWillAppear:(BOOL)animated {
7415 [super viewWillAppear:animated];
7417 [self resizeSegmentedControl];
7420 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7421 [self resizeSegmentedControl];
7424 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7425 [self resizeSegmentedControl];
7429 NSString *role(nil);
7431 switch ([segment_ selectedSegmentIndex]) {
7432 case 0: role = @"User"; break;
7433 case 1: role = @"Hacker"; break;
7434 case 2: role = @"Developer"; break;
7439 if (![role isEqualToString:Role_]) {
7440 bool rolling(Role_ == nil);
7443 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7447 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7452 [roledelegate_ loadData];
7454 [roledelegate_ updateData];
7458 - (void) segmentChanged:(UISegmentedControl *)control {
7459 [self showDoneButton];
7462 - (void) saveAndClose {
7465 [[self navigationItem] setRightBarButtonItem:nil];
7466 [[self navigationController] dismissModalViewControllerAnimated:YES];
7469 - (void) doneButtonClicked {
7470 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7471 [spinner startAnimating];
7472 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7473 [[self navigationItem] setRightBarButtonItem:spinItem];
7475 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7478 - (void) showDoneButton {
7479 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7480 initWithTitle:UCLocalize("DONE")
7481 style:UIBarButtonItemStyleDone
7483 action:@selector(doneButtonClicked)
7484 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
7487 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7488 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7492 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7496 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7497 return nil; // This method is required by the protocol.
7500 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7502 return UCLocalize("ROLE_EX");
7504 return [NSString stringWithFormat:
7505 @"%@: %@\n%@: %@\n%@: %@",
7506 UCLocalize("USER"), UCLocalize("USER_EX"),
7507 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7508 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7513 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7514 return section == 3 ? 44.0f : 0;
7517 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7518 return section == 3 ? container_ : nil;
7523 /* Stash Controller {{{ */
7524 @interface CYStashController : CYViewController {
7525 // XXX: just delete these things
7526 _transient UIActivityIndicatorView *spinner_;
7527 _transient UILabel *status_;
7528 _transient UILabel *caption_;
7532 @implementation CYStashController
7534 if ((self = [super init])) {
7535 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7537 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
7538 CGRect spinrect = [spinner_ frame];
7539 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7540 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7541 [spinner_ setFrame:spinrect];
7542 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7543 [[self view] addSubview:spinner_];
7544 [spinner_ startAnimating];
7547 captrect.size.width = [[self view] frame].size.width;
7548 captrect.size.height = 40.0f;
7549 captrect.origin.x = 0;
7550 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7551 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
7552 [caption_ setText:@"Initializing Filesystem"];
7553 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7554 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7555 [caption_ setTextColor:[UIColor whiteColor]];
7556 [caption_ setBackgroundColor:[UIColor clearColor]];
7557 [caption_ setShadowColor:[UIColor blackColor]];
7558 [caption_ setTextAlignment:UITextAlignmentCenter];
7559 [[self view] addSubview:caption_];
7562 statusrect.size.width = [[self view] frame].size.width;
7563 statusrect.size.height = 30.0f;
7564 statusrect.origin.x = 0;
7565 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7566 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
7567 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7568 [status_ setText:@"(Cydia will exit when complete.)"];
7569 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7570 [status_ setTextColor:[UIColor whiteColor]];
7571 [status_ setBackgroundColor:[UIColor clearColor]];
7572 [status_ setShadowColor:[UIColor blackColor]];
7573 [status_ setTextAlignment:UITextAlignmentCenter];
7574 [[self view] addSubview:status_];
7578 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7579 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7584 /* Cydia Container {{{ */
7585 @interface CYContainer : UIViewController <ProgressDelegate> {
7586 _transient Database *database_;
7587 RefreshBar *refreshbar_;
7591 // XXX: ok, "updatedelegate_"?...
7592 _transient NSObject<CydiaDelegate> *updatedelegate_;
7593 // XXX: can't we query for this variable when we need it?
7594 _transient UITabBarController *root_;
7597 - (void) setTabBarController:(UITabBarController *)controller;
7599 - (void) dropBar:(BOOL)animated;
7600 - (void) beginUpdate;
7601 - (void) raiseBar:(BOOL)animated;
7606 @implementation CYContainer
7608 - (BOOL) _reallyWantsFullScreenLayout {
7612 // NOTE: UIWindow only sends the top controller these messages,
7613 // So we have to forward them on.
7615 - (void) viewDidAppear:(BOOL)animated {
7616 [super viewDidAppear:animated];
7617 [root_ viewDidAppear:animated];
7620 - (void) viewWillAppear:(BOOL)animated {
7621 [super viewWillAppear:animated];
7622 [root_ viewWillAppear:animated];
7625 - (void) viewDidDisappear:(BOOL)animated {
7626 [super viewDidDisappear:animated];
7627 [root_ viewDidDisappear:animated];
7630 - (void) viewWillDisappear:(BOOL)animated {
7631 [super viewWillDisappear:animated];
7632 [root_ viewWillDisappear:animated];
7635 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7636 return ![updatedelegate_ hudIsShowing] && (IsWildcat_ || orientation == UIInterfaceOrientationPortrait);
7639 - (void) setTabBarController:(UITabBarController *)controller {
7641 [[self view] addSubview:[root_ view]];
7644 - (void) setUpdate:(NSDate *)date {
7648 - (void) beginUpdate {
7650 [refreshbar_ start];
7655 detachNewThreadSelector:@selector(performUpdate)
7661 - (void) performUpdate { _pooled
7663 status.setDelegate(self);
7664 [database_ updateWithStatus:status];
7667 performSelectorOnMainThread:@selector(completeUpdate)
7673 - (void) completeUpdate {
7678 [self raiseBar:YES];
7680 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7683 - (void) cancelUpdate {
7685 [self raiseBar:YES];
7687 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7690 - (void) cancelPressed {
7691 [self cancelUpdate];
7698 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7699 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7702 - (void) startProgress {
7705 - (void) setProgressTitle:(NSString *)title {
7707 performSelectorOnMainThread:@selector(_setProgressTitle:)
7713 - (bool) isCancelling:(size_t)received {
7717 - (void) setProgressPercent:(float)percent {
7719 performSelectorOnMainThread:@selector(_setProgressPercent:)
7720 withObject:[NSNumber numberWithFloat:percent]
7725 - (void) addProgressOutput:(NSString *)output {
7727 performSelectorOnMainThread:@selector(_addProgressOutput:)
7733 - (void) _setProgressTitle:(NSString *)title {
7734 [refreshbar_ setPrompt:title];
7737 - (void) _setProgressPercent:(NSNumber *)percent {
7738 [refreshbar_ setProgress:[percent floatValue]];
7741 - (void) _addProgressOutput:(NSString *)output {
7744 - (void) setUpdateDelegate:(id)delegate {
7745 updatedelegate_ = delegate;
7748 - (CGFloat) statusBarHeight {
7749 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7750 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7752 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7756 - (void) dropBar:(BOOL)animated {
7761 [[self view] addSubview:refreshbar_];
7763 CGFloat sboffset = [self statusBarHeight];
7765 CGRect barframe = [refreshbar_ frame];
7766 barframe.origin.y = sboffset;
7767 [refreshbar_ setFrame:barframe];
7770 [UIView beginAnimations:nil context:NULL];
7771 CGRect viewframe = [[root_ view] frame];
7772 viewframe.origin.y += barframe.size.height + sboffset;
7773 viewframe.size.height -= barframe.size.height + sboffset;
7774 [[root_ view] setFrame:viewframe];
7776 [UIView commitAnimations];
7778 // Ensure bar has the proper width for our view, it might have changed
7779 barframe.size.width = viewframe.size.width;
7780 [refreshbar_ setFrame:barframe];
7782 // XXX: fix Apple's layout bug
7783 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7786 - (void) raiseBar:(BOOL)animated {
7791 [refreshbar_ removeFromSuperview];
7793 CGFloat sboffset = [self statusBarHeight];
7796 [UIView beginAnimations:nil context:NULL];
7797 CGRect barframe = [refreshbar_ frame];
7798 CGRect viewframe = [[root_ view] frame];
7799 viewframe.origin.y -= barframe.size.height + sboffset;
7800 viewframe.size.height += barframe.size.height + sboffset;
7801 [[root_ view] setFrame:viewframe];
7803 [UIView commitAnimations];
7805 // XXX: fix Apple's layout bug
7806 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7809 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7810 // XXX: fix Apple's layout bug
7811 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7814 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7820 // XXX: fix Apple's layout bug
7821 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7824 - (void) statusBarFrameChanged:(NSNotification *)notification {
7832 [refreshbar_ release];
7833 [[NSNotificationCenter defaultCenter] removeObserver:self];
7837 - (id) initWithDatabase:(Database *)database {
7838 if ((self = [super init]) != nil) {
7839 database_ = database;
7841 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7842 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7844 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7861 @interface Cydia : UIApplication <
7862 ConfirmationControllerDelegate,
7863 ProgressControllerDelegate,
7865 UINavigationControllerDelegate,
7866 UITabBarControllerDelegate
7868 // XXX: evaluate all fields for _transient
7871 CYContainer *container_;
7872 CYTabBarController *tabbar_;
7874 NSMutableArray *essential_;
7875 NSMutableArray *broken_;
7877 Database *database_;
7883 SectionsController *sections_;
7884 ChangesController *changes_;
7885 ManageController *manage_;
7886 SearchController *search_;
7887 SourceTable *sources_;
7888 InstalledController *installed_;
7891 CYStashController *stash_;
7896 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7897 - (void) setPage:(CYViewController *)page;
7902 static _finline void _setHomePage(Cydia *self) {
7903 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7906 @implementation Cydia
7908 - (void) beginUpdate {
7909 [container_ beginUpdate];
7913 return [container_ updating];
7916 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7921 if ([broken_ count] != 0) {
7922 int count = [broken_ count];
7924 UIAlertView *alert = [[[UIAlertView alloc]
7925 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7926 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7928 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7929 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
7932 [alert setContext:@"fixhalf"];
7934 } else if (!Ignored_ && [essential_ count] != 0) {
7935 int count = [essential_ count];
7937 UIAlertView *alert = [[[UIAlertView alloc]
7938 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7939 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
7941 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
7942 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
7945 [alert setContext:@"upgrade"];
7950 - (void) _saveConfig {
7953 NSString *error(nil);
7954 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7956 NSError *error(nil);
7957 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7958 NSLog(@"failure to save metadata data: %@", error);
7961 NSLog(@"failure to serialize metadata: %@", error);
7969 - (void) _updateData {
7972 /* XXX: this is just stupid */
7973 if (tag_ != 1 && sections_ != nil)
7974 [sections_ reloadData];
7975 if (tag_ != 2 && changes_ != nil)
7976 [changes_ reloadData];
7977 if (tag_ != 4 && search_ != nil)
7978 [search_ reloadData];
7980 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
7983 - (int)indexOfTabWithTag:(int)tag {
7985 for (UINavigationController *controller in [tabbar_ viewControllers]) {
7986 if ([[controller tabBarItem] tag] == tag)
7994 - (void) _refreshIfPossible {
7995 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
7997 bool recently = false;
7998 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
7999 if (update != nil) {
8000 NSTimeInterval interval([update timeIntervalSinceNow]);
8001 if (interval <= 0 && interval > -(15*60))
8005 // Don't automatic refresh if:
8006 // - We already refreshed recently.
8007 // - We already auto-refreshed this launch.
8008 // - Auto-refresh is disabled.
8009 if (recently || loaded_ || ManualRefresh) {
8010 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8012 // If we are cancelling due to ManualRefresh or a recent refresh
8013 // we need to make sure it knows it's already loaded.
8017 // We are going to load, so remember that.
8021 SCNetworkReachabilityFlags flags; {
8022 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8023 SCNetworkReachabilityGetFlags(reachability, &flags);
8024 CFRelease(reachability);
8027 // XXX: this elaborate mess is what Apple is using to determine this? :(
8028 // XXX: do we care if the user has to intervene? maybe that's ok?
8030 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8031 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8032 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8033 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8034 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8035 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8039 // If we can reach the server, auto-refresh!
8041 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8046 - (void) refreshIfPossible {
8047 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8050 - (void) _reloadData {
8051 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8052 [hud setText:UCLocalize("RELOADING_DATA")];
8054 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8057 [self removeProgressHUD:hud];
8061 [essential_ removeAllObjects];
8062 [broken_ removeAllObjects];
8064 NSArray *packages([database_ packages]);
8065 for (Package *package in packages) {
8067 [broken_ addObject:package];
8068 if ([package upgradableAndEssential:NO]) {
8069 if ([package essential])
8070 [essential_ addObject:package];
8075 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8077 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8078 [changesItem setBadgeValue:badge];
8079 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8081 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8082 [self setApplicationBadge:badge];
8084 [self setApplicationBadgeString:badge];
8086 [changesItem setBadgeValue:nil];
8087 [changesItem setAnimatedBadge:NO];
8089 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8090 [self removeApplicationBadge];
8091 else // XXX: maybe use setApplicationBadgeString also?
8092 [self setApplicationIconBadgeNumber:0];
8097 [self refreshIfPossible];
8100 - (void) updateData {
8109 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8110 _assert(file != NULL);
8112 for (NSString *key in [Sources_ allKeys]) {
8113 NSDictionary *source([Sources_ objectForKey:key]);
8115 fprintf(file, "%s %s %s\n",
8116 [[source objectForKey:@"Type"] UTF8String],
8117 [[source objectForKey:@"URI"] UTF8String],
8118 [[source objectForKey:@"Distribution"] UTF8String]
8126 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8127 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8129 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8130 [container_ presentModalViewController:navigation animated:YES];
8133 detachNewThreadSelector:@selector(update_)
8136 title:UCLocalize("UPDATING_SOURCES")
8140 - (void) reloadData {
8141 @synchronized (self) {
8147 pkgProblemResolver *resolver = [database_ resolver];
8149 resolver->InstallProtect();
8150 if (!resolver->Resolve(true))
8154 - (CGRect) popUpBounds {
8155 return [[tabbar_ view] bounds];
8159 if (![database_ prepare])
8162 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8163 [page setDelegate:self];
8164 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8165 [confirm_ setDelegate:self];
8168 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8169 [container_ presentModalViewController:confirm_ animated:YES];
8175 @synchronized (self) {
8180 - (void) clearPackage:(Package *)package {
8181 @synchronized (self) {
8188 - (void) installPackages:(NSArray *)packages {
8189 @synchronized (self) {
8190 for (Package *package in packages)
8197 - (void) installPackage:(Package *)package {
8198 @synchronized (self) {
8205 - (void) removePackage:(Package *)package {
8206 @synchronized (self) {
8213 - (void) distUpgrade {
8214 @synchronized (self) {
8215 if (![database_ upgrade])
8222 @synchronized (self) {
8227 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8228 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8230 if (navigation != nil) {
8231 [navigation pushViewController:progress animated:YES];
8233 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8235 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8236 [container_ presentModalViewController:navigation animated:YES];
8240 detachNewThreadSelector:@selector(perform)
8243 title:UCLocalize("RUNNING")
8247 - (void) progressControllerIsComplete:(ProgressController *)progress {
8251 - (void) setPage:(CYViewController *)page {
8252 [page setDelegate:self];
8254 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8255 [navController setViewControllers:[NSArray arrayWithObject:page]];
8256 for (CYNavigationController *page in [tabbar_ viewControllers])
8257 if (page != navController)
8258 [page setViewControllers:nil];
8261 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8262 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8263 [browser loadURL:url];
8267 - (SectionsController *) sectionsController {
8268 if (sections_ == nil)
8269 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8273 - (ChangesController *) changesController {
8274 if (changes_ == nil)
8275 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8279 - (ManageController *) manageController {
8280 if (manage_ == nil) {
8281 manage_ = (ManageController *) [[self
8282 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8283 withClass:[ManageController class]
8286 queueDelegate_ = manage_;
8291 - (SearchController *) searchController {
8293 search_ = [[SearchController alloc] initWithDatabase:database_];
8297 - (SourceTable *) sourcesController {
8298 if (sources_ == nil)
8299 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8303 - (InstalledController *) installedController {
8304 if (installed_ == nil) {
8305 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8307 queueDelegate_ = installed_;
8312 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8313 int tag = [[viewController tabBarItem] tag];
8315 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8317 } else if (tag_ == 1) {
8318 [[self sectionsController] resetView];
8322 case kCydiaTag: _setHomePage(self); break;
8324 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8325 case kChangesTag: [self setPage:[self changesController]]; break;
8326 case kManageTag: [self setPage:[self manageController]]; break;
8327 case kInstalledTag: [self setPage:[self installedController]]; break;
8328 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8329 case kSearchTag: [self setPage:[self searchController]]; break;
8337 - (void) showSettings {
8338 RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease];
8339 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8341 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8342 [container_ presentModalViewController:nav animated:YES];
8345 - (void) setPackageController:(PackageController *)view {
8347 [view setPackage:nil];
8351 - (PackageController *) _packageController {
8352 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8355 - (PackageController *) packageController {
8356 return [self _packageController];
8359 // Returns the navigation controller for the queuing badge.
8360 - (id) queueBadgeController {
8361 int index = [self indexOfTabWithTag:kManageTag];
8363 index = [self indexOfTabWithTag:kInstalledTag];
8365 return [[tabbar_ viewControllers] objectAtIndex:index];
8368 - (void) cancelAndClear:(bool)clear {
8369 @synchronized (self) {
8375 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
8379 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8383 [queueDelegate_ queueStatusDidChange];
8387 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8388 NSString *context([alert context]);
8390 if ([context isEqualToString:@"fixhalf"]) {
8391 if (button == [alert firstOtherButtonIndex]) {
8392 @synchronized (self) {
8393 for (Package *broken in broken_) {
8396 NSString *id = [broken id];
8397 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8398 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8399 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8400 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8406 } else if (button == [alert cancelButtonIndex]) {
8407 [broken_ removeAllObjects];
8411 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8412 } else if ([context isEqualToString:@"upgrade"]) {
8413 if (button == [alert firstOtherButtonIndex]) {
8414 @synchronized (self) {
8415 for (Package *essential in essential_)
8416 [essential install];
8421 } else if (button == [alert firstOtherButtonIndex] + 1) {
8423 } else if (button == [alert cancelButtonIndex]) {
8427 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8431 - (void) system:(NSString *)command { _pooled
8432 system([command UTF8String]);
8435 - (void) applicationWillSuspend {
8437 [super applicationWillSuspend];
8440 - (BOOL) hudIsShowing {
8441 return (hudcount_ > 0);
8444 - (void) applicationSuspend:(__GSEvent *)event {
8445 // Use external process status API internally.
8446 // This is probably a really bad idea.
8447 uint64_t status = 0;
8449 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8450 notify_get_state(notify_token, &status);
8451 notify_cancel(notify_token);
8454 if (![self hudIsShowing] && status == 0)
8455 [super applicationSuspend:event];
8458 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8459 if (![self hudIsShowing])
8460 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8463 - (void) _setSuspended:(BOOL)value {
8464 if (![self hudIsShowing])
8465 [super _setSuspended:value];
8468 - (UIProgressHUD *) addProgressHUD {
8469 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8470 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8472 [window_ setUserInteractionEnabled:NO];
8475 UIViewController *target = container_;
8476 while ([target modalViewController] != nil) target = [target modalViewController];
8477 [[target view] addSubview:hud];
8483 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8485 [hud removeFromSuperview];
8486 [window_ setUserInteractionEnabled:YES];
8490 - (CYViewController *) pageForPackage:(NSString *)name {
8491 if (Package *package = [database_ packageWithName:name]) {
8492 PackageController *view([self packageController]);
8493 [view setPackage:package];
8496 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8497 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8498 return [self _pageForURL:url withClass:[CYBrowserController class]];
8502 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8506 NSString *href([url absoluteString]);
8507 if ([href hasPrefix:@"apptapp://package/"])
8508 return [self pageForPackage:[href substringFromIndex:18]];
8510 NSString *scheme([[url scheme] lowercaseString]);
8511 if (![scheme isEqualToString:@"cydia"])
8513 NSString *path([url absoluteString]);
8514 if ([path length] < 8)
8516 path = [path substringFromIndex:8];
8517 if (![path hasPrefix:@"/"])
8518 path = [@"/" stringByAppendingString:path];
8520 if ([path isEqualToString:@"/add-source"])
8521 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8522 else if ([path isEqualToString:@"/storage"])
8523 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8524 else if ([path isEqualToString:@"/sources"])
8525 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8526 else if ([path isEqualToString:@"/packages"])
8527 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8528 else if ([path hasPrefix:@"/url/"])
8529 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8530 else if ([path hasPrefix:@"/launch/"])
8531 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8532 else if ([path hasPrefix:@"/package-settings/"])
8533 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8534 else if ([path hasPrefix:@"/package-signature/"])
8535 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8536 else if ([path hasPrefix:@"/package/"])
8537 return [self pageForPackage:[path substringFromIndex:9]];
8538 else if ([path hasPrefix:@"/files/"]) {
8539 NSString *name = [path substringFromIndex:7];
8541 if (Package *package = [database_ packageWithName:name]) {
8542 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8543 [files setPackage:package];
8551 - (BOOL) openCydiaURL:(NSURL *)url {
8552 CYViewController *page = nil;
8555 NSLog(@"open url: %@", url);
8557 if ((page = [self pageForURL:url hasTag:&tag])) {
8558 [self setPage:page];
8560 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8566 - (void) applicationOpenURL:(NSURL *)url {
8567 [super applicationOpenURL:url];
8568 NSLog(@"first: %@", url);
8569 if (!loaded_) starturl_ = [url retain];
8570 else [self openCydiaURL:url];
8573 - (void) applicationWillResignActive:(UIApplication *)application {
8574 // Stop refreshing if you get a phone call or lock the device.
8575 if ([container_ updating])
8576 [container_ cancelUpdate];
8578 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8579 [super applicationWillResignActive:application];
8582 - (void) addStashController {
8583 stash_ = [[CYStashController alloc] init];
8584 [window_ addSubview:[stash_ view]];
8587 - (void) removeStashController {
8588 [[stash_ view] removeFromSuperview];
8593 [self setIdleTimerDisabled:YES];
8595 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8596 [self setStatusBarShowsProgress:YES];
8597 UpdateExternalStatus(1);
8599 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8601 UpdateExternalStatus(0);
8602 [self setStatusBarShowsProgress:NO];
8604 [self removeStashController];
8606 if (ExecFork() == 0) {
8607 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8608 perror("launchctl stop");
8612 - (void) setupTabBarController {
8613 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8614 [tabbar_ setDelegate:self];
8616 NSMutableArray *items([NSMutableArray arrayWithObjects:
8617 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8618 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8619 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8620 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8624 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8625 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8627 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8630 NSMutableArray *controllers([NSMutableArray array]);
8632 for (UITabBarItem *item in items) {
8633 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8634 [controller setTabBarItem:item];
8635 [controllers addObject:controller];
8638 [tabbar_ setViewControllers:controllers];
8641 - (void) applicationDidFinishLaunching:(id)unused {
8642 [CYBrowserController _initialize];
8644 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8646 Font12_ = [[UIFont systemFontOfSize:12] retain];
8647 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8648 Font14_ = [[UIFont systemFontOfSize:14] retain];
8649 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8650 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8654 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8655 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8657 UIScreen *screen([UIScreen mainScreen]);
8659 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8660 [window_ orderFront:self];
8661 [window_ makeKey:self];
8662 [window_ setHidden:NO];
8665 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8666 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8667 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8668 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8669 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8670 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8671 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8672 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8673 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8676 [self addStashController];
8677 // XXX: this would be much cleaner as a yieldToSelector:
8678 // that way the removeStashController could happen right here inline
8679 // we also could no longer require the useless stash_ field anymore
8680 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8684 database_ = [Database sharedInstance];
8686 [self setupTabBarController];
8688 container_ = [[CYContainer alloc] initWithDatabase:database_];
8689 [container_ setUpdateDelegate:self];
8690 [container_ setTabBarController:tabbar_];
8691 [window_ addSubview:[container_ view]];
8693 // Show pinstripes while loading data.
8694 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8696 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8703 [self showSettings];
8707 [window_ setUserInteractionEnabled:NO];
8709 UIView *container = [[[UIView alloc] init] autorelease];
8710 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8712 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
8713 [spinner startAnimating];
8714 [container addSubview:spinner];
8716 UILabel *label = [[[UILabel alloc] init] autorelease];
8717 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8718 [label setBackgroundColor:[UIColor clearColor]];
8719 [label setTextColor:[UIColor blackColor]];
8720 [label setShadowColor:[UIColor whiteColor]];
8721 [label setShadowOffset:CGSizeMake(0, 1)];
8722 [label setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
8723 [container addSubview:label];
8725 CGSize viewsize = [[tabbar_ view] frame].size;
8726 CGSize spinnersize = [spinner bounds].size;
8727 CGSize textsize = [[label text] sizeWithFont:[label font]];
8728 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8730 CGRect containrect = {
8731 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8732 CGSizeMake(bothwidth, spinnersize.height)
8735 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8743 [container setFrame:containrect];
8744 [spinner setFrame:spinrect];
8745 [label setFrame:textrect];
8746 [[container_ view] addSubview:container];
8751 // Show the initial page
8752 if (starturl_ == nil || ![self openCydiaURL:starturl_]) {
8753 [tabbar_ setSelectedIndex:0];
8757 [starturl_ release];
8760 [window_ setUserInteractionEnabled:YES];
8762 // XXX: does this actually slow anything down?
8763 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8764 [container removeFromSuperview];
8767 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8768 if (item != nil && IsWildcat_) {
8769 [sheet showFromBarButtonItem:item animated:YES];
8771 [sheet showInView:window_];
8778 id Alloc_(id self, SEL selector) {
8779 id object = alloc_(self, selector);
8780 lprintf("[%s]A-%p\n", self->isa->name, object);
8785 id Dealloc_(id self, SEL selector) {
8786 id object = dealloc_(self, selector);
8787 lprintf("[%s]D-%p\n", self->isa->name, object);
8791 Class $WebDefaultUIKitDelegate;
8793 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8794 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8795 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8796 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8799 static NSNumber *shouldPlayKeyboardSounds;
8803 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8805 case 1104: // Keyboard Button Clicked
8806 case 1105: // Keyboard Delete Repeated
8807 if (shouldPlayKeyboardSounds == nil) {
8808 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8809 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8812 if (![shouldPlayKeyboardSounds boolValue])
8816 _UIHardware$_playSystemSound$(self, _cmd, sound);
8820 int main(int argc, char *argv[]) { _pooled
8823 if (Class $UIDevice = objc_getClass("UIDevice")) {
8824 UIDevice *device([$UIDevice currentDevice]);
8825 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8829 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8831 /* Library Hacks {{{ */
8832 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8834 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8835 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8836 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8837 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8838 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8841 $UIHardware = objc_getClass("UIHardware");
8842 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8843 if (UIHardware$_playSystemSound$ != NULL) {
8844 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8845 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8848 /* Set Locale {{{ */
8849 Locale_ = CFLocaleCopyCurrent();
8850 Languages_ = [NSLocale preferredLanguages];
8851 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8852 //NSLog(@"%@", [Languages_ description]);
8855 if (Languages_ == nil || [Languages_ count] == 0)
8856 // XXX: consider just setting to C and then falling through?
8859 lang = [[Languages_ objectAtIndex:0] UTF8String];
8860 setenv("LANG", lang, true);
8863 //std::setlocale(LC_ALL, lang);
8864 NSLog(@"Setting Language: %s", lang);
8867 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8869 /* Parse Arguments {{{ */
8870 bool substrate(false);
8876 for (int argi(1); argi != argc; ++argi)
8877 if (strcmp(argv[argi], "--") == 0) {
8879 argv[argi] = argv[0];
8885 for (int argi(1); argi != arge; ++argi)
8886 if (strcmp(args[argi], "--substrate") == 0)
8889 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8893 App_ = [[NSBundle mainBundle] bundlePath];
8894 Home_ = NSHomeDirectory();
8900 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8901 alloc_ = alloc->method_imp;
8902 alloc->method_imp = (IMP) &Alloc_;*/
8904 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8905 dealloc_ = dealloc->method_imp;
8906 dealloc->method_imp = (IMP) &Dealloc_;*/
8908 /* System Information {{{ */
8912 size = sizeof(maxproc);
8913 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8914 perror("sysctlbyname(\"kern.maxproc\", ?)");
8915 else if (maxproc < 64) {
8917 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8918 perror("sysctlbyname(\"kern.maxproc\", #)");
8921 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8922 char *osversion = new char[size];
8923 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8924 perror("sysctlbyname(\"kern.osversion\", ?)");
8926 System_ = [NSString stringWithUTF8String:osversion];
8928 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8929 char *machine = new char[size];
8930 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8931 perror("sysctlbyname(\"hw.machine\", ?)");
8935 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8936 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8937 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8938 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8942 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8943 NSData *data((NSData *) ecid);
8944 size_t length([data length]);
8945 uint8_t bytes[length];
8946 [data getBytes:bytes];
8947 char string[length * 2 + 1];
8948 for (size_t i(0); i != length; ++i)
8949 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8950 ChipID_ = [NSString stringWithUTF8String:string];
8954 IOObjectRelease(service);
8958 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8960 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
8961 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
8962 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
8964 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
8965 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
8966 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
8968 if (mcc != NULL && mnc != NULL)
8969 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
8976 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8977 Build_ = [system objectForKey:@"ProductBuildVersion"];
8978 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8979 Product_ = [info objectForKey:@"SafariProductVersion"];
8980 Safari_ = [info objectForKey:@"CFBundleVersion"];
8983 /* Load Database {{{ */
8985 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8987 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8989 if (Metadata_ == NULL)
8990 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8992 Settings_ = [Metadata_ objectForKey:@"Settings"];
8994 Packages_ = [Metadata_ objectForKey:@"Packages"];
8995 Sections_ = [Metadata_ objectForKey:@"Sections"];
8996 Sources_ = [Metadata_ objectForKey:@"Sources"];
8998 Token_ = [Metadata_ objectForKey:@"Token"];
9001 if (Settings_ != nil)
9002 Role_ = [Settings_ objectForKey:@"Role"];
9004 if (Packages_ == nil) {
9005 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
9006 [Metadata_ setObject:Packages_ forKey:@"Packages"];
9009 if (Sections_ == nil) {
9010 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9011 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9014 if (Sources_ == nil) {
9015 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9016 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9020 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9022 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9023 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9024 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9025 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9026 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9027 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9029 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9031 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9032 unlink("/tmp/.cydia.fw");
9034 } else if (access("/User", F_OK) != 0 || version < 2) {
9037 system("/usr/libexec/cydia/firmware.sh");
9041 _assert([[NSFileManager defaultManager]
9042 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9043 withIntermediateDirectories:YES
9048 if (access("/tmp/cydia.chk", F_OK) == 0) {
9049 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9050 _assert(errno == ENOENT);
9051 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9052 _assert(errno == ENOENT);
9055 /* APT Initialization {{{ */
9056 _assert(pkgInitConfig(*_config));
9057 _assert(pkgInitSystem(*_config, _system));
9060 _config->Set("APT::Acquire::Translation", lang);
9062 // XXX: this timeout might be important :(
9063 //_config->Set("Acquire::http::Timeout", 15);
9065 _config->Set("Acquire::http::MaxParallel", 3);
9067 /* Color Choices {{{ */
9068 space_ = CGColorSpaceCreateDeviceRGB();
9070 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9071 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9072 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9073 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9074 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9075 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9076 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9077 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9078 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9080 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9081 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9083 /* UIKit Configuration {{{ */
9084 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9085 if ($GSFontSetUseLegacyFontMetrics != NULL)
9086 $GSFontSetUseLegacyFontMetrics(YES);
9088 // XXX: I have a feeling this was important
9089 //UIKeyboardDisableAutomaticAppearance();
9092 Colon_ = UCLocalize("COLON_DELIMITED");
9093 Elision_ = UCLocalize("ELISION");
9094 Error_ = UCLocalize("ERROR");
9095 Warning_ = UCLocalize("WARNING");
9098 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9100 CGColorSpaceRelease(space_);