1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 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>
105 #include <sys/reboot.h>
112 #include <mach-o/nlist.h>
122 #include <Cytore.hpp>
124 #include "UICaboodle/BrowserView.h"
125 #include "SDURLCache/SDURLCache.h"
127 #include "substrate.h"
134 #define _timestamp ({ \
136 gettimeofday(&tv, NULL); \
137 tv.tv_sec * 1000000 + tv.tv_usec; \
140 typedef std::vector<class ProfileTime *> TimeList;
150 ProfileTime(const char *name) :
154 times_.push_back(this);
157 void AddTime(uint64_t time) {
164 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
176 ProfileTimer(ProfileTime &time) :
183 time_.AddTime(_timestamp - start_);
188 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
190 std::cerr << "========" << std::endl;
193 #define _profile(name) { \
194 static ProfileTime name(#name); \
195 ProfileTimer _ ## name(name);
200 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
202 #define CYPoolStart() \
203 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
205 #define CYPoolEnd() \
209 // Hash Functions/Structures {{{
210 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
218 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
220 void NSLogPoint(const char *fix, const CGPoint &point) {
221 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
224 void NSLogRect(const char *fix, const CGRect &rect) {
225 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
228 static _finline NSString *CydiaURL(NSString *path) {
230 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
231 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
232 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
233 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
234 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
235 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
238 static _finline void UpdateExternalStatus(uint64_t newStatus) {
240 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
241 notify_set_state(notify_token, newStatus);
242 notify_cancel(notify_token);
244 notify_post("com.saurik.Cydia.status");
247 /* [NSObject yieldToSelector:(withObject:)] {{{*/
248 @interface NSObject (Cydia)
249 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
250 - (id) yieldToSelector:(SEL)selector;
253 @implementation NSObject (Cydia)
258 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
259 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
260 id object([[context objectAtIndex:1] nonretainedObjectValue]);
261 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
263 /* XXX: deal with exceptions */
264 id value([self performSelector:selector withObject:object]);
266 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
267 [context removeAllObjects];
268 if ([signature methodReturnLength] != 0 && value != nil)
269 [context addObject:value];
274 performSelectorOnMainThread:@selector(doNothing)
280 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
281 volatile bool stopped(false);
283 NSMutableArray *context([NSMutableArray arrayWithObjects:
284 [NSValue valueWithPointer:selector],
285 [NSValue valueWithNonretainedObject:object],
286 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
289 NSThread *thread([[[NSThread alloc]
291 selector:@selector(_yieldToContext:)
297 NSRunLoop *loop([NSRunLoop currentRunLoop]);
298 NSDate *future([NSDate distantFuture]);
300 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
302 return [context count] == 0 ? nil : [context objectAtIndex:0];
305 - (id) yieldToSelector:(SEL)selector {
306 return [self yieldToSelector:selector withObject:nil];
312 /* Cydia Action Sheet {{{ */
313 @interface CYActionSheet : UIAlertView {
317 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
320 @implementation CYActionSheet
322 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
323 if ((self = [super init])) {
324 [self setTitle:title];
325 [self setDelegate:self];
326 for (NSString *button in buttons) [self addButtonWithTitle:button];
327 [self setCancelButtonIndex:index];
331 - (void) _updateFrameForDisplay {
332 [super _updateFrameForDisplay];
333 if ([self cancelButtonIndex] == -1) {
334 NSArray *buttons = [self buttons];
335 if ([buttons count]) {
336 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
337 for (UIThreePartButton *button in buttons)
338 [button setBackground:background forState:0];
343 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
344 button_ = buttonIndex + 1;
348 [self dismissWithClickedButtonIndex:-1 animated:YES];
351 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
352 [self setRunsModal:YES];
361 /* NSForcedOrderingSearch doesn't work on the iPhone */
362 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
363 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
364 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
366 /* Information Dictionaries {{{ */
367 @interface NSMutableArray (Cydia)
368 - (void) addInfoDictionary:(NSDictionary *)info;
371 @implementation NSMutableArray (Cydia)
373 - (void) addInfoDictionary:(NSDictionary *)info {
374 [self addObject:info];
379 @interface NSMutableDictionary (Cydia)
380 - (void) addInfoDictionary:(NSDictionary *)info;
383 @implementation NSMutableDictionary (Cydia)
385 - (void) addInfoDictionary:(NSDictionary *)info {
386 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
392 #define lprintf(args...) fprintf(stderr, args)
395 #define TraceLogging (1 && !ForRelease)
396 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
397 #define ProfileTimes (0 && !ForRelease)
398 #define ForSaurik (0 && !ForRelease)
399 #define LogBrowser (0 && !ForRelease)
400 #define TrackResize (0 && !ForRelease)
401 #define ManualRefresh (1 && !ForRelease)
402 #define ShowInternals (0 && !ForRelease)
403 #define IgnoreInstall (0 && !ForRelease)
404 #define AlwaysReload (0 && !ForRelease)
405 #define TryIndexedCollation (0 && !ForRelease)
409 #define _trace(args...)
414 #define _profile(name) {
417 #define PrintTimes() do {} while (false)
421 typedef uint32_t (*SKRadixFunction)(id, void *);
423 @interface NSMutableArray (Radix)
424 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
432 @implementation NSMutableArray (Radix)
434 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
435 size_t count([self count]);
436 struct RadixItem_ *swap(new RadixItem_[count * 2]);
438 for (size_t i(0); i != count; ++i) {
439 RadixItem_ &item(swap[i]);
442 id object([self objectAtIndex:i]);
443 item.key = function(object, argument);
446 struct RadixItem_ *lhs(swap), *rhs(swap + count);
448 static const size_t width = 32;
449 static const size_t bits = 11;
450 static const size_t slots = 1 << bits;
451 static const size_t passes = (width + (bits - 1)) / bits;
453 size_t *hist(new size_t[slots]);
455 for (size_t pass(0); pass != passes; ++pass) {
456 memset(hist, 0, sizeof(size_t) * slots);
458 for (size_t i(0); i != count; ++i) {
459 uint32_t key(lhs[i].key);
461 key &= _not(uint32_t) >> width - bits;
466 for (size_t i(0); i != slots; ++i) {
467 size_t local(offset);
472 for (size_t i(0); i != count; ++i) {
473 uint32_t key(lhs[i].key);
475 key &= _not(uint32_t) >> width - bits;
476 rhs[hist[key]++] = lhs[i];
479 RadixItem_ *tmp(lhs);
486 const void **values(new const void *[count]);
487 for (size_t i(0); i != count; ++i)
488 values[i] = [self objectAtIndex:lhs[i].index];
489 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
497 /* Insertion Sort {{{ */
499 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
500 const char *ptr = (const char *)list;
502 CFIndex half = count / 2;
503 const char *probe = ptr + elementSize * half;
504 CFComparisonResult cr = comparator(element, probe, context);
505 if (0 == cr) return (probe - (const char *)list) / elementSize;
506 ptr = (cr < 0) ? ptr : probe + elementSize;
507 count = (cr < 0) ? half : (half + (count & 1) - 1);
509 return (ptr - (const char *)list) / elementSize;
512 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
513 const char *ptr = (const char *)list;
515 CFIndex half = count / 2;
516 const char *probe = ptr + elementSize * half;
517 CFComparisonResult cr = comparator(element, probe, context);
518 if (0 == cr) return (probe - (const char *)list) / elementSize;
519 ptr = (cr < 0) ? ptr : probe + elementSize;
520 count = (cr < 0) ? half : (half + (count & 1) - 1);
522 return (ptr - (const char *)list) / elementSize;
525 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
526 if (range.length == 0)
528 const void **values(new const void *[range.length]);
529 CFArrayGetValues(array, range, values);
531 #if HistogramInsertionSort > 0
532 uint32_t total(0), *offsets(new uint32_t[range.length]);
535 for (CFIndex index(1); index != range.length; ++index) {
536 const void *value(values[index]);
537 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
538 CFIndex correct(index);
539 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
540 #if HistogramInsertionSort > 1
541 NSLog(@"%@ < %@", value, values[correct - 1]);
546 if (correct != index) {
547 size_t offset(index - correct);
548 #if HistogramInsertionSort
552 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
554 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
555 values[correct] = value;
559 CFArrayReplaceValues(array, range, values, range.length);
562 #if HistogramInsertionSort > 0
563 for (CFIndex index(0); index != range.length; ++index)
564 if (offsets[index] != 0)
565 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
566 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
573 /* Apple Bug Fixes {{{ */
574 @implementation UIWebDocumentView (Cydia)
576 - (void) _setScrollerOffset:(CGPoint)offset {
577 UIScroller *scroller([self _scroller]);
579 CGSize size([scroller contentSize]);
580 CGSize bounds([scroller bounds].size);
583 max.x = size.width - bounds.width;
584 max.y = size.height - bounds.height;
592 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
593 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
595 [scroller setOffset:offset];
601 @implementation WebScriptObject (NSFastEnumeration)
603 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
604 size_t length([self count] - state->state);
607 else if (length > count)
609 for (size_t i(0); i != length; ++i)
610 objects[i] = [self objectAtIndex:state->state++];
611 state->itemsPtr = objects;
612 state->mutationsPtr = (unsigned long *) self;
618 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
619 size_t length([self length] - state->state);
622 else if (length > count)
624 for (size_t i(0); i != length; ++i)
625 objects[i] = [self item:state->state++];
626 state->itemsPtr = objects;
627 state->mutationsPtr = (unsigned long *) self;
631 /* Cydia NSString Additions {{{ */
632 @interface NSString (Cydia)
633 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
634 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
635 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
636 - (NSComparisonResult) compareByPath:(NSString *)other;
637 - (NSString *) stringByCachingURLWithCurrentCDN;
638 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
641 @implementation NSString (Cydia)
643 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
644 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
647 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
648 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
649 memcpy(data, bytes, length);
650 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
653 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
654 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
657 - (NSComparisonResult) compareByPath:(NSString *)other {
658 NSString *prefix = [self commonPrefixWithString:other options:0];
659 size_t length = [prefix length];
661 NSRange lrange = NSMakeRange(length, [self length] - length);
662 NSRange rrange = NSMakeRange(length, [other length] - length);
664 lrange = [self rangeOfString:@"/" options:0 range:lrange];
665 rrange = [other rangeOfString:@"/" options:0 range:rrange];
667 NSComparisonResult value;
669 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
670 value = NSOrderedSame;
671 else if (lrange.location == NSNotFound)
672 value = NSOrderedAscending;
673 else if (rrange.location == NSNotFound)
674 value = NSOrderedDescending;
676 value = NSOrderedSame;
678 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
679 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
680 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
681 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
683 NSComparisonResult result = [lpath compare:rpath];
684 return result == NSOrderedSame ? value : result;
687 - (NSString *) stringByCachingURLWithCurrentCDN {
689 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
690 withString:@"://cache.cydia.saurik.com/"
694 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
695 return [(id)CFURLCreateStringByAddingPercentEscapes(
700 kCFStringEncodingUTF8
707 /* C++ NSString Wrapper Cache {{{ */
708 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
709 return size == 0 ? NULL :
710 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
711 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
714 static _finline CFStringRef CYStringCreate(const char *data) {
715 return CYStringCreate(data, strlen(data));
724 _finline void clear_() {
725 if (cache_ != NULL) {
732 _finline bool empty() const {
736 _finline size_t size() const {
740 _finline char *data() const {
744 _finline void clear() {
749 _finline CYString() :
756 _finline ~CYString() {
760 void operator =(const CYString &rhs) {
764 if (rhs.cache_ == nil)
767 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
770 void copy(apr_pool_t *pool) {
771 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
772 memcpy(temp, data_, size_);
777 void set(apr_pool_t *pool, const char *data, size_t size) {
783 data_ = const_cast<char *>(data);
791 _finline void set(apr_pool_t *pool, const char *data) {
792 set(pool, data, data == NULL ? 0 : strlen(data));
795 _finline void set(apr_pool_t *pool, const std::string &rhs) {
796 set(pool, rhs.data(), rhs.size());
799 bool operator ==(const CYString &rhs) const {
800 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
803 _finline operator CFStringRef() {
805 cache_ = CYStringCreate(data_, size_);
809 _finline operator id() {
810 return (NSString *) static_cast<CFStringRef>(*this);
813 _finline operator const char *() {
814 return reinterpret_cast<const char *>(data_);
818 /* C++ NSString Algorithm Adapters {{{ */
820 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
823 struct NSStringMapHash :
824 std::unary_function<NSString *, size_t>
826 _finline size_t operator ()(NSString *value) const {
827 return CFStringHashNSString((CFStringRef) value);
831 struct NSStringMapLess :
832 std::binary_function<NSString *, NSString *, bool>
834 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
835 return [lhs compare:rhs] == NSOrderedAscending;
839 struct NSStringMapEqual :
840 std::binary_function<NSString *, NSString *, bool>
842 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
843 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
844 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
845 //[lhs isEqualToString:rhs];
850 /* Perl-Compatible RegEx {{{ */
860 Pcre(const char *regex) :
865 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
868 lprintf("%d:%s\n", offset, error);
872 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
873 matches_ = new int[(capture_ + 1) * 3];
881 NSString *operator [](size_t match) {
882 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
885 bool operator ()(NSString *data) {
886 // XXX: length is for characters, not for bytes
887 return operator ()([data UTF8String], [data length]);
890 bool operator ()(const char *data, size_t size) {
892 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
896 /* Mime Addresses {{{ */
897 @interface Address : NSObject {
903 - (NSString *) address;
905 - (void) setAddress:(NSString *)address;
907 + (Address *) addressWithString:(NSString *)string;
908 - (Address *) initWithString:(NSString *)string;
911 @implementation Address
920 - (NSString *) name {
924 - (NSString *) address {
928 - (void) setAddress:(NSString *)address {
930 [address_ autorelease];
934 address_ = [address retain];
937 + (Address *) addressWithString:(NSString *)string {
938 return [[[Address alloc] initWithString:string] autorelease];
941 + (NSArray *) _attributeKeys {
942 return [NSArray arrayWithObjects:@"address", @"name", nil];
945 - (NSArray *) attributeKeys {
946 return [[self class] _attributeKeys];
949 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
950 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
953 - (Address *) initWithString:(NSString *)string {
954 if ((self = [super init]) != nil) {
955 const char *data = [string UTF8String];
956 size_t size = [string length];
958 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
960 if (address_r(data, size)) {
961 name_ = [address_r[1] retain];
962 address_ = [address_r[2] retain];
964 name_ = [string retain];
972 /* CoreGraphics Primitives {{{ */
977 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
978 CGFloat color[] = {red, green, blue, alpha};
979 return CGColorCreate(space, color);
988 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
989 color_(Create_(space, red, green, blue, alpha))
991 Set(space, red, green, blue, alpha);
996 CGColorRelease(color_);
1003 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1005 color_ = Create_(space, red, green, blue, alpha);
1008 operator CGColorRef() {
1014 /* Random Global Variables {{{ */
1015 static const int PulseInterval_ = 50000;
1018 static NSArray *Finishes_;
1020 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1021 #define NotifyConfig_ "/etc/notify.conf"
1023 static bool Queuing_;
1025 static CYColor Blue_;
1026 static CYColor Blueish_;
1027 static CYColor Black_;
1028 static CYColor Off_;
1029 static CYColor White_;
1030 static CYColor Gray_;
1031 static CYColor Green_;
1032 static CYColor Purple_;
1033 static CYColor Purplish_;
1035 static UIColor *InstallingColor_;
1036 static UIColor *RemovingColor_;
1038 static NSString *App_;
1039 static NSString *Home_;
1041 static BOOL Advanced_;
1042 static BOOL Ignored_;
1044 static UIFont *Font12_;
1045 static UIFont *Font12Bold_;
1046 static UIFont *Font14_;
1047 static UIFont *Font18Bold_;
1048 static UIFont *Font22Bold_;
1050 static const char *Machine_ = NULL;
1051 static NSString *System_ = nil;
1052 static NSString *SerialNumber_ = nil;
1053 static NSString *ChipID_ = nil;
1054 static NSString *Token_ = nil;
1055 static NSString *UniqueID_ = nil;
1056 static NSString *PLMN_ = nil;
1057 static NSString *Build_ = nil;
1058 static NSString *Product_ = nil;
1059 static NSString *Safari_ = nil;
1061 static CFLocaleRef Locale_;
1062 static NSArray *Languages_;
1063 static CGColorSpaceRef space_;
1065 static NSDictionary *SectionMap_;
1066 static NSMutableDictionary *Metadata_;
1067 static _transient NSMutableDictionary *Settings_;
1068 static _transient NSString *Role_;
1069 static _transient NSMutableDictionary *Packages_;
1070 static _transient NSMutableDictionary *Sections_;
1071 static _transient NSMutableDictionary *Sources_;
1072 static bool Changed_;
1078 /* Display Helpers {{{ */
1079 inline float Interpolate(float begin, float end, float fraction) {
1080 return (end - begin) * fraction + begin;
1083 /* XXX: localize this! */
1084 NSString *SizeString(double size) {
1085 bool negative = size < 0;
1090 while (size > 1024) {
1095 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1097 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1100 static _finline const char *StripVersion_(const char *version) {
1101 const char *colon(strchr(version, ':'));
1102 return colon == NULL ? version : colon + 1;
1105 NSString *LocalizeSection(NSString *section) {
1106 static Pcre title_r("^(.*?) \\((.*)\\)$");
1107 if (title_r(section)) {
1108 NSString *parent(title_r[1]);
1109 NSString *child(title_r[2]);
1111 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1112 LocalizeSection(parent),
1113 LocalizeSection(child)
1117 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1120 NSString *Simplify(NSString *title) {
1121 const char *data = [title UTF8String];
1122 size_t size = [title length];
1124 static Pcre square_r("^\\[(.*)\\]$");
1125 if (square_r(data, size))
1126 return Simplify(square_r[1]);
1128 static Pcre paren_r("^\\((.*)\\)$");
1129 if (paren_r(data, size))
1130 return Simplify(paren_r[1]);
1132 static Pcre title_r("^(.*?) \\((.*)\\)$");
1133 if (title_r(data, size))
1134 return Simplify(title_r[1]);
1140 NSString *GetLastUpdate() {
1141 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1144 return UCLocalize("NEVER_OR_UNKNOWN");
1146 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1147 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1149 CFRelease(formatter);
1151 return [(NSString *) formatted autorelease];
1154 bool isSectionVisible(NSString *section) {
1155 NSDictionary *metadata([Sections_ objectForKey:section]);
1156 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1157 return hidden == nil || ![hidden boolValue];
1162 /* Delegate Prototypes {{{ */
1166 @interface NSObject (ProgressDelegate)
1169 @protocol ProgressDelegate
1170 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1171 - (void) setProgressTitle:(NSString *)title;
1172 - (void) setProgressPercent:(float)percent;
1173 - (void) startProgress;
1174 - (void) addProgressOutput:(NSString *)output;
1175 - (bool) isCancelling:(size_t)received;
1178 @protocol ConfigurationDelegate
1179 - (void) repairWithSelector:(SEL)selector;
1180 - (void) setConfigurationData:(NSString *)data;
1183 @class CYPackageController;
1185 @protocol CydiaDelegate
1186 - (void) retainNetworkActivityIndicator;
1187 - (void) releaseNetworkActivityIndicator;
1188 - (void) clearPackage:(Package *)package;
1189 - (void) installPackage:(Package *)package;
1190 - (void) installPackages:(NSArray *)packages;
1191 - (void) removePackage:(Package *)package;
1192 - (void) beginUpdate;
1194 - (void) distUpgrade;
1196 - (void) updateData;
1198 - (void) showSettings;
1199 - (UIProgressHUD *) addProgressHUD;
1200 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1201 - (CYViewController *) pageForPackage:(NSString *)name;
1202 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1205 static id<CydiaDelegate> CydiaApp;
1208 /* Status Delegation {{{ */
1210 public pkgAcquireStatus
1213 _transient NSObject<ProgressDelegate> *delegate_;
1221 void setDelegate(id delegate) {
1222 delegate_ = delegate;
1225 NSObject<ProgressDelegate> *getDelegate() const {
1229 virtual bool MediaChange(std::string media, std::string drive) {
1233 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1236 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1237 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1238 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1241 virtual void Done(pkgAcquire::ItemDesc &item) {
1244 virtual void Fail(pkgAcquire::ItemDesc &item) {
1246 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1247 item.Owner->Status == pkgAcquire::Item::StatDone
1251 std::string &error(item.Owner->ErrorText);
1255 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1256 NSArray *fields([description componentsSeparatedByString:@" "]);
1257 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1259 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1260 withObject:[NSArray arrayWithObjects:
1261 [NSString stringWithUTF8String:error.c_str()],
1268 virtual bool Pulse(pkgAcquire *Owner) {
1269 bool value = pkgAcquireStatus::Pulse(Owner);
1272 double(CurrentBytes + CurrentItems) /
1273 double(TotalBytes + TotalItems)
1276 [delegate_ setProgressPercent:percent];
1277 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1280 virtual void Start() {
1281 [delegate_ startProgress];
1284 virtual void Stop() {
1288 /* Progress Delegation {{{ */
1293 _transient id<ProgressDelegate> delegate_;
1297 virtual void Update() {
1298 /*if (abs(Percent - percent_) > 2)
1299 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1303 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1304 [delegate_ setProgressPercent:(Percent / 100)];*/
1314 void setDelegate(id delegate) {
1315 delegate_ = delegate;
1318 id getDelegate() const {
1322 virtual void Done() {
1324 //[delegate_ setProgressPercent:1];
1329 /* Database Interface {{{ */
1330 typedef std::map< unsigned long, _H<Source> > SourceMap;
1332 @interface Database : NSObject {
1338 pkgCacheFile cache_;
1339 pkgDepCache::Policy *policy_;
1340 pkgRecords *records_;
1341 pkgProblemResolver *resolver_;
1342 pkgAcquire *fetcher_;
1344 SPtr<pkgPackageManager> manager_;
1345 pkgSourceList *list_;
1348 CFMutableArrayRef deadSources_;
1349 CFMutableArrayRef packages_;
1351 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1359 std::map<const char *, _H<NSString> > sections_;
1362 + (Database *) sharedInstance;
1365 - (void) _readCydia:(NSNumber *)fd;
1366 - (void) _readStatus:(NSNumber *)fd;
1367 - (void) _readOutput:(NSNumber *)fd;
1371 - (Package *) packageWithName:(NSString *)name;
1373 - (pkgCacheFile &) cache;
1374 - (pkgDepCache::Policy *) policy;
1375 - (pkgRecords *) records;
1376 - (pkgProblemResolver *) resolver;
1377 - (pkgAcquire &) fetcher;
1378 - (pkgSourceList &) list;
1379 - (NSArray *) packages;
1380 - (NSArray *) sources;
1381 - (void) reloadData;
1389 - (void) updateWithStatus:(Status &)status;
1391 - (void) setDelegate:(id)delegate;
1392 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1394 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1398 /* Delegate Helpers {{{ */
1399 @implementation NSObject (ProgressDelegate)
1401 - (void) _setProgressErrorPackage:(NSArray *)args {
1402 [self performSelector:@selector(setProgressError:forPackage:)
1403 withObject:[args objectAtIndex:0]
1404 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1408 - (void) _setProgressErrorTitle:(NSArray *)args {
1409 [self performSelector:@selector(setProgressError:withTitle:)
1410 withObject:[args objectAtIndex:0]
1411 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1415 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1416 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1417 withObject:[NSArray arrayWithObjects:error, title, nil]
1422 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1423 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1425 [self performSelector:@selector(setProgressError:withTitle:)
1427 withObject:(package == nil ? id : [package name])
1434 // Cytore Definitions {{{
1435 struct PackageValue :
1438 Cytore::Offset<PackageValue> next_;
1440 uint32_t index_ : 23;
1441 uint32_t subscribed_ : 1;
1458 Cytore::Offset<PackageValue> packages_[1 << 16];
1461 static Cytore::File<MetaValue> MetaFile_;
1463 // Cytore Helper Functions {{{
1464 static PackageValue *PackageFind(const char *name, size_t length) {
1465 SplitHash nhash = { hashlittle(name, length) };
1467 PackageValue *metadata;
1469 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1470 offset: if (offset->IsNull()) {
1471 *offset = MetaFile_.New<PackageValue>(length + 1);
1472 metadata = &MetaFile_.Get(*offset);
1474 memcpy(metadata->name_, name, length + 1);
1475 metadata->nhash_ = nhash.u16[1];
1477 metadata = &MetaFile_.Get(*offset);
1479 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1480 offset = &metadata->next_;
1488 static void PackageImport(const void *key, const void *value, void *context) {
1490 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1491 NSLog(@"failed to import package %@", key);
1495 PackageValue *metadata(PackageFind(buffer, strlen(buffer)));
1496 NSDictionary *package((NSDictionary *) value);
1498 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1499 if ([subscribed boolValue] && !metadata->subscribed_)
1500 metadata->subscribed_ = true;
1502 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1503 time_t time([date timeIntervalSince1970]);
1504 if (metadata->first_ > time || metadata->first_ == 0)
1505 metadata->first_ = time;
1508 NSDate *date([package objectForKey:@"LastSeen"]);
1509 NSString *version([package objectForKey:@"LastVersion"]);
1511 if (date != nil && version != nil) {
1512 time_t time([date timeIntervalSince1970]);
1513 if (metadata->last_ < time || metadata->last_ == 0)
1514 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1515 size_t length(strlen(buffer));
1516 uint16_t vhash(hashlittle(buffer, length));
1518 size_t capped(std::min<size_t>(8, length));
1519 char *latest(buffer + length - capped);
1521 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1522 metadata->vhash_ = vhash;
1524 metadata->last_ = time;
1530 /* Source Class {{{ */
1531 @interface Source : NSObject {
1532 CYString depiction_;
1533 CYString description_;
1539 CYString distribution_;
1544 NSString *authority_;
1546 CYString defaultIcon_;
1548 NSDictionary *record_;
1552 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1554 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1556 - (NSString *) depictionForPackage:(NSString *)package;
1557 - (NSString *) supportForPackage:(NSString *)package;
1559 - (NSDictionary *) record;
1563 - (NSString *) distribution;
1564 - (NSString *) type;
1566 - (NSString *) host;
1568 - (NSString *) name;
1569 - (NSString *) description;
1570 - (NSString *) label;
1571 - (NSString *) origin;
1572 - (NSString *) version;
1574 - (NSString *) defaultIcon;
1578 @implementation Source
1582 distribution_.clear();
1585 description_.clear();
1591 defaultIcon_.clear();
1593 if (record_ != nil) {
1603 if (authority_ != nil) {
1604 [authority_ release];
1610 // XXX: this is a very inefficient way to call these deconstructors
1615 + (NSArray *) _attributeKeys {
1616 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1619 - (NSArray *) attributeKeys {
1620 return [[self class] _attributeKeys];
1623 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1624 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1627 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1630 trusted_ = index->IsTrusted();
1632 uri_.set(pool, index->GetURI());
1633 distribution_.set(pool, index->GetDist());
1634 type_.set(pool, index->GetType());
1636 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1637 if (dindex != NULL) {
1639 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1642 pkgTagFile tags(&fd);
1644 pkgTagSection section;
1651 {"default-icon", &defaultIcon_},
1652 {"depiction", &depiction_},
1653 {"description", &description_},
1655 {"origin", &origin_},
1656 {"support", &support_},
1657 {"version", &version_},
1660 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1661 const char *start, *end;
1663 if (section.Find(names[i].name_, start, end)) {
1664 CYString &value(*names[i].value_);
1665 value.set(pool, start, end - start);
1671 record_ = [Sources_ objectForKey:[self key]];
1673 record_ = [record_ retain];
1675 NSURL *url([NSURL URLWithString:uri_]);
1679 host_ = [[host_ lowercaseString] retain];
1684 authority_ = [url path];
1686 if (authority_ != nil)
1687 authority_ = [authority_ retain];
1690 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1691 if ((self = [super init]) != nil) {
1692 [self setMetaIndex:index inPool:pool];
1696 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1697 NSDictionary *lhr = [self record];
1698 NSDictionary *rhr = [source record];
1701 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1703 NSString *lhs = [self name];
1704 NSString *rhs = [source name];
1706 if ([lhs length] != 0 && [rhs length] != 0) {
1707 unichar lhc = [lhs characterAtIndex:0];
1708 unichar rhc = [rhs characterAtIndex:0];
1710 if (isalpha(lhc) && !isalpha(rhc))
1711 return NSOrderedAscending;
1712 else if (!isalpha(lhc) && isalpha(rhc))
1713 return NSOrderedDescending;
1716 return [lhs compare:rhs options:LaxCompareOptions_];
1719 - (NSString *) depictionForPackage:(NSString *)package {
1720 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1723 - (NSString *) supportForPackage:(NSString *)package {
1724 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1727 - (NSDictionary *) record {
1735 - (NSString *) uri {
1739 - (NSString *) distribution {
1740 return distribution_;
1743 - (NSString *) type {
1747 - (NSString *) key {
1748 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1751 - (NSString *) host {
1755 - (NSString *) name {
1756 return origin_.empty() ? authority_ : origin_;
1759 - (NSString *) description {
1760 return description_;
1763 - (NSString *) label {
1764 return label_.empty() ? authority_ : label_;
1767 - (NSString *) origin {
1771 - (NSString *) version {
1775 - (NSString *) defaultIcon {
1776 return defaultIcon_;
1781 /* Relationship Class {{{ */
1782 @interface Relationship : NSObject {
1787 - (NSString *) type;
1789 - (NSString *) name;
1793 @implementation Relationship
1801 - (NSString *) type {
1809 - (NSString *) name {
1816 /* Package Class {{{ */
1817 struct ParsedPackage {
1822 CYString depiction_;
1832 @interface Package : NSObject {
1835 uint32_t essential_ : 1;
1836 uint32_t obsolete_ : 1;
1837 uint32_t ignored_ : 1;
1841 _transient Database *database_;
1843 pkgCache::VerIterator version_;
1844 pkgCache::PkgIterator iterator_;
1845 pkgCache::VerFileIterator file_;
1851 CYString installed_;
1853 const char *section_;
1854 _transient NSString *section$_;
1858 PackageValue *metadata_;
1859 ParsedPackage *parsed_;
1861 NSMutableArray *tags_;
1864 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1865 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1867 - (pkgCache::PkgIterator) iterator;
1870 - (NSString *) section;
1871 - (NSString *) simpleSection;
1873 - (NSString *) longSection;
1874 - (NSString *) shortSection;
1878 - (Address *) maintainer;
1880 - (NSString *) longDescription;
1881 - (NSString *) shortDescription;
1884 - (PackageValue *) metadata;
1887 - (bool) subscribed;
1888 - (bool) setSubscribed:(bool)subscribed;
1892 - (NSString *) latest;
1893 - (NSString *) installed;
1894 - (BOOL) uninstalled;
1897 - (BOOL) upgradableAndEssential:(BOOL)essential;
1900 - (BOOL) unfiltered;
1904 - (BOOL) halfConfigured;
1905 - (BOOL) halfInstalled;
1907 - (NSString *) mode;
1910 - (NSString *) name;
1912 - (NSString *) homepage;
1913 - (NSString *) depiction;
1914 - (Address *) author;
1916 - (NSString *) support;
1918 - (NSArray *) files;
1919 - (NSArray *) warnings;
1920 - (NSArray *) applications;
1922 - (Source *) source;
1924 - (BOOL) matches:(NSString *)text;
1926 - (bool) hasSupportingRole;
1927 - (BOOL) hasTag:(NSString *)tag;
1928 - (NSString *) primaryPurpose;
1929 - (NSArray *) purposes;
1930 - (bool) isCommercial;
1932 - (void) setIndex:(size_t)index;
1934 - (CYString &) cyname;
1936 - (uint32_t) compareBySection:(NSArray *)sections;
1941 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1942 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1943 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1944 - (bool) isVisibleInSection:(NSString *)section;
1945 - (bool) isVisibleInSource:(Source *)source;
1949 uint32_t PackageChangesRadix(Package *self, void *) {
1954 uint32_t timestamp : 30;
1955 uint32_t ignored : 1;
1956 uint32_t upgradable : 1;
1960 bool upgradable([self upgradableAndEssential:YES]);
1961 value.bits.upgradable = upgradable ? 1 : 0;
1964 value.bits.timestamp = 0;
1965 value.bits.ignored = [self ignored] ? 0 : 1;
1966 value.bits.upgradable = 1;
1968 value.bits.timestamp = [self seen] >> 2;
1969 value.bits.ignored = 0;
1970 value.bits.upgradable = 0;
1973 return _not(uint32_t) - value.key;
1976 uint32_t PackagePrefixRadix(Package *self, void *context) {
1977 size_t offset(reinterpret_cast<size_t>(context));
1978 CYString &name([self cyname]);
1980 size_t size(name.size());
1983 char *text(name.data());
1986 if (!isdigit(text[0]))
1990 while (size != digits && isdigit(text[digits]))
1998 if (offset == 0 && zeros != 0) {
1999 memset(data, '0', zeros);
2000 memcpy(data + zeros, text, 4 - zeros);
2002 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2003 if (size <= offset - zeros)
2006 text += offset - zeros;
2007 size -= offset - zeros;
2010 memcpy(data, text, 4);
2012 memcpy(data, text, size);
2013 memset(data + size, 0, 4 - size);
2016 for (size_t i(0); i != 4; ++i)
2017 if (isalpha(data[i]))
2025 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2027 /* XXX: ntohl may be more honest */
2028 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2031 CYString &(*PackageName)(Package *self, SEL sel);
2033 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2034 _profile(PackageNameCompare)
2035 CYString &lhi(PackageName(lhs, @selector(cyname)));
2036 CYString &rhi(PackageName(rhs, @selector(cyname)));
2037 CFStringRef lhn(lhi), rhn(rhi);
2040 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2041 else if (rhn == NULL)
2042 return NSOrderedDescending;
2044 _profile(PackageNameCompare$NumbersLast)
2045 if (!lhi.empty() && !rhi.empty()) {
2046 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2047 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2048 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2049 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2050 return lha ? NSOrderedAscending : NSOrderedDescending;
2054 CFIndex length = CFStringGetLength(lhn);
2056 _profile(PackageNameCompare$Compare)
2057 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2062 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2063 return PackageNameCompare(*lhs, *rhs, context);
2066 struct PackageNameOrdering :
2067 std::binary_function<Package *, Package *, bool>
2069 _finline bool operator ()(Package *lhs, Package *rhs) const {
2070 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2074 @implementation Package
2076 - (NSString *) description {
2077 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2081 if (parsed_ != NULL)
2090 + (NSString *) webScriptNameForSelector:(SEL)selector {
2091 if (selector == @selector(hasTag:))
2097 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2098 return [self webScriptNameForSelector:selector] == nil;
2101 + (NSArray *) _attributeKeys {
2102 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];
2105 - (NSArray *) attributeKeys {
2106 return [[self class] _attributeKeys];
2109 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2110 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2114 if (parsed_ != NULL)
2116 @synchronized (database_) {
2117 if ([database_ era] != era_ || file_.end())
2120 ParsedPackage *parsed(new ParsedPackage);
2123 _profile(Package$parse)
2124 pkgRecords::Parser *parser;
2126 _profile(Package$parse$Lookup)
2127 parser = &[database_ records]->Lookup(file_);
2132 _profile(Package$parse$Find)
2137 {"icon", &parsed->icon_},
2138 {"depiction", &parsed->depiction_},
2139 {"homepage", &parsed->homepage_},
2140 {"website", &website},
2141 {"bugs", &parsed->bugs_},
2142 {"support", &parsed->support_},
2143 {"sponsor", &parsed->sponsor_},
2144 {"author", &parsed->author_},
2147 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2148 const char *start, *end;
2150 if (parser->Find(names[i].name_, start, end)) {
2151 CYString &value(*names[i].value_);
2152 _profile(Package$parse$Value)
2153 value.set(pool_, start, end - start);
2159 _profile(Package$parse$Tagline)
2160 const char *start, *end;
2161 if (parser->ShortDesc(start, end)) {
2162 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2165 while (stop != start && stop[-1] == '\r')
2167 parsed->tagline_.set(pool_, start, stop - start);
2171 _profile(Package$parse$Retain)
2172 if (parsed->homepage_.empty())
2173 parsed->homepage_ = website;
2174 if (parsed->homepage_ == parsed->depiction_)
2175 parsed->homepage_.clear();
2180 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2181 if ((self = [super init]) != nil) {
2182 _profile(Package$initWithVersion)
2185 database_ = database;
2186 era_ = [database era];
2190 pkgCache::PkgIterator iterator(version.ParentPkg());
2191 iterator_ = iterator;
2193 _profile(Package$initWithVersion$Version)
2194 if (!version_.end())
2195 file_ = version_.FileList();
2197 pkgCache &cache([database_ cache]);
2198 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2202 _profile(Package$initWithVersion$Cache)
2203 name_.set(NULL, iterator.Display());
2205 latest_.set(NULL, StripVersion_(version_.VerStr()));
2207 pkgCache::VerIterator current(iterator.CurrentVer());
2209 installed_.set(NULL, StripVersion_(current.VerStr()));
2212 _profile(Package$initWithVersion$Tags)
2213 pkgCache::TagIterator tag(iterator.TagList());
2215 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2217 const char *name(tag.Name());
2218 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2220 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2221 if (strcmp(name + 6, "enduser") == 0)
2223 else if (strcmp(name + 6, "hacker") == 0)
2225 else if (strcmp(name + 6, "developer") == 0)
2227 else if (strcmp(name + 6, "cydia") == 0)
2233 if (strncmp(name, "cydia::", 7) == 0) {
2234 if (strcmp(name + 7, "essential") == 0)
2236 else if (strcmp(name + 7, "obsolete") == 0)
2241 } while (!tag.end());
2245 _profile(Package$initWithVersion$Metadata)
2246 const char *mixed(iterator.Name());
2247 size_t size(strlen(mixed));
2248 char lower[size + 1];
2250 for (size_t i(0); i != size; ++i)
2251 lower[i] = mixed[i] | 0x20;
2254 PackageValue *metadata(PackageFind(lower, size));
2255 metadata_ = metadata;
2257 id_.set(NULL, metadata->name_, size);
2259 const char *latest(version_.VerStr());
2260 size_t length(strlen(latest));
2262 uint16_t vhash(hashlittle(latest, length));
2264 size_t capped(std::min<size_t>(8, length));
2265 latest = latest + length - capped;
2267 if (metadata->first_ == 0)
2268 metadata->first_ = now_;
2270 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2271 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2272 metadata->vhash_ = vhash;
2273 metadata->last_ = now_;
2274 } else if (metadata->last_ == 0)
2275 metadata->last_ = metadata->first_;
2278 _profile(Package$initWithVersion$Section)
2279 section_ = iterator.Section();
2282 _profile(Package$initWithVersion$Flags)
2283 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2284 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2289 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2290 pkgCache::VerIterator version;
2292 _profile(Package$packageWithIterator$GetCandidateVer)
2293 version = [database policy]->GetCandidateVer(iterator);
2301 _profile(Package$packageWithIterator$Allocate)
2302 package = [Package allocWithZone:zone];
2305 _profile(Package$packageWithIterator$Initialize)
2307 initWithVersion:version
2314 _profile(Package$packageWithIterator$Autorelease)
2315 package = [package autorelease];
2321 - (pkgCache::PkgIterator) iterator {
2325 - (NSString *) section {
2326 if (section$_ == nil) {
2327 if (section_ == NULL)
2330 _profile(Package$section$mappedSectionForPointer)
2331 section$_ = [database_ mappedSectionForPointer:section_];
2336 - (NSString *) simpleSection {
2337 if (NSString *section = [self section])
2338 return Simplify(section);
2343 - (NSString *) longSection {
2344 return LocalizeSection([self section]);
2347 - (NSString *) shortSection {
2348 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2351 - (NSString *) uri {
2354 pkgIndexFile *index;
2355 pkgCache::PkgFileIterator file(file_.File());
2356 if (![database_ list].FindIndex(file, index))
2358 return [NSString stringWithUTF8String:iterator_->Path];
2359 //return [NSString stringWithUTF8String:file.Site()];
2360 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2364 - (Address *) maintainer {
2365 @synchronized (database_) {
2366 if ([database_ era] != era_ || file_.end())
2369 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2370 const std::string &maintainer(parser->Maintainer());
2371 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2375 @synchronized (database_) {
2376 if ([database_ era] != era_ || version_.end())
2379 return version_->InstalledSize;
2382 - (NSString *) longDescription {
2383 @synchronized (database_) {
2384 if ([database_ era] != era_ || file_.end())
2387 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2388 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2390 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2391 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2392 if ([lines count] < 2)
2395 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2396 for (size_t i(1), e([lines count]); i != e; ++i) {
2397 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2398 [trimmed addObject:trim];
2401 return [trimmed componentsJoinedByString:@"\n"];
2404 - (NSString *) shortDescription {
2405 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2409 _profile(Package$index)
2410 CFStringRef name((CFStringRef) [self name]);
2411 if (CFStringGetLength(name) == 0)
2413 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2414 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2416 return toupper(character);
2420 - (PackageValue *) metadata {
2425 PackageValue *metadata([self metadata]);
2426 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2429 - (bool) subscribed {
2430 return [self metadata]->subscribed_;
2433 - (bool) setSubscribed:(bool)subscribed {
2434 PackageValue *metadata([self metadata]);
2435 if (metadata->subscribed_ == subscribed)
2437 metadata->subscribed_ = subscribed;
2445 - (NSString *) latest {
2449 - (NSString *) installed {
2453 - (BOOL) uninstalled {
2454 return installed_.empty();
2458 return !version_.end();
2461 - (BOOL) upgradableAndEssential:(BOOL)essential {
2462 _profile(Package$upgradableAndEssential)
2463 pkgCache::VerIterator current(iterator_.CurrentVer());
2465 return essential && essential_;
2467 return !version_.end() && version_ != current;
2471 - (BOOL) essential {
2476 return [database_ cache][iterator_].InstBroken();
2479 - (BOOL) unfiltered {
2480 _profile(Package$unfiltered$obsolete)
2481 if (_unlikely(obsolete_))
2485 _profile(Package$unfiltered$hasSupportingRole)
2486 if (_unlikely(![self hasSupportingRole]))
2494 if (![self unfiltered])
2499 _profile(Package$visible$section)
2500 section = [self section];
2503 _profile(Package$visible$isSectionVisible)
2504 if (section != nil && !isSectionVisible(section))
2512 unsigned char current(iterator_->CurrentState);
2513 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2516 - (BOOL) halfConfigured {
2517 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2520 - (BOOL) halfInstalled {
2521 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2525 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2526 return state.Mode != pkgDepCache::ModeKeep;
2529 - (NSString *) mode {
2530 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2532 switch (state.Mode) {
2533 case pkgDepCache::ModeDelete:
2534 if ((state.iFlags & pkgDepCache::Purge) != 0)
2538 case pkgDepCache::ModeKeep:
2539 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2540 return @"REINSTALL";
2541 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2545 case pkgDepCache::ModeInstall:
2546 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2547 return @"REINSTALL";
2548 else*/ switch (state.Status) {
2550 return @"DOWNGRADE";
2556 return @"NEW_INSTALL";
2567 - (NSString *) name {
2568 return name_.empty() ? id_ : name_;
2571 - (UIImage *) icon {
2572 NSString *section = [self simpleSection];
2575 if (parsed_ != NULL)
2576 if (NSString *href = parsed_->icon_)
2577 if ([href hasPrefix:@"file:///"])
2578 // XXX: correct escaping
2579 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2580 if (icon == nil) if (section != nil)
2581 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2582 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2583 if ([dicon hasPrefix:@"file:///"])
2584 // XXX: correct escaping
2585 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2587 icon = [UIImage applicationImageNamed:@"unknown.png"];
2591 - (NSString *) homepage {
2592 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2595 - (NSString *) depiction {
2596 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2599 - (Address *) sponsor {
2600 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2603 - (Address *) author {
2604 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2607 - (NSString *) support {
2608 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2611 - (NSArray *) files {
2612 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2613 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2616 fin.open([path UTF8String]);
2621 while (std::getline(fin, line))
2622 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2627 - (NSArray *) warnings {
2628 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2629 const char *name(iterator_.Name());
2631 size_t length(strlen(name));
2632 if (length < 2) invalid:
2633 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2634 else for (size_t i(0); i != length; ++i)
2636 /* XXX: technically this is not allowed */
2637 (name[i] < 'A' || name[i] > 'Z') &&
2638 (name[i] < 'a' || name[i] > 'z') &&
2639 (name[i] < '0' || name[i] > '9') &&
2640 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2643 if (strcmp(name, "cydia") != 0) {
2646 bool _private = false;
2649 bool repository = [[self section] isEqualToString:@"Repositories"];
2651 if (NSArray *files = [self files])
2652 for (NSString *file in files)
2653 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2655 else if (!user && [file isEqualToString:@"/User"])
2657 else if (!_private && [file isEqualToString:@"/private"])
2659 else if (!stash && [file isEqualToString:@"/var/stash"])
2662 /* XXX: this is not sensitive enough. only some folders are valid. */
2663 if (cydia && !repository)
2664 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2666 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2668 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2670 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2673 return [warnings count] == 0 ? nil : warnings;
2676 - (NSArray *) applications {
2677 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2679 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2681 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2682 if (NSArray *files = [self files])
2683 for (NSString *file in files)
2684 if (application_r(file)) {
2685 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2686 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2687 if ([id isEqualToString:me])
2690 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2692 display = application_r[1];
2694 NSString *bundle([file stringByDeletingLastPathComponent]);
2695 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2696 if (icon == nil || [icon length] == 0)
2698 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2700 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2701 [applications addObject:application];
2703 [application addObject:id];
2704 [application addObject:display];
2705 [application addObject:url];
2708 return [applications count] == 0 ? nil : applications;
2711 - (Source *) source {
2712 if (source_ == nil) {
2713 @synchronized (database_) {
2714 if ([database_ era] != era_ || file_.end())
2715 source_ = (Source *) [NSNull null];
2717 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2721 return source_ == (Source *) [NSNull null] ? nil : source_;
2724 - (BOOL) matches:(NSString *)text {
2730 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2731 if (range.location != NSNotFound)
2734 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2735 if (range.location != NSNotFound)
2740 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2741 if (range.location != NSNotFound)
2747 - (bool) hasSupportingRole {
2752 if ([Role_ isEqualToString:@"User"])
2756 if ([Role_ isEqualToString:@"Hacker"])
2760 if ([Role_ isEqualToString:@"Developer"])
2765 - (BOOL) hasTag:(NSString *)tag {
2766 return tags_ == nil ? NO : [tags_ containsObject:tag];
2769 - (NSString *) primaryPurpose {
2770 for (NSString *tag in tags_)
2771 if ([tag hasPrefix:@"purpose::"])
2772 return [tag substringFromIndex:9];
2776 - (NSArray *) purposes {
2777 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2778 for (NSString *tag in tags_)
2779 if ([tag hasPrefix:@"purpose::"])
2780 [purposes addObject:[tag substringFromIndex:9]];
2781 return [purposes count] == 0 ? nil : purposes;
2784 - (bool) isCommercial {
2785 return [self hasTag:@"cydia::commercial"];
2788 - (void) setIndex:(size_t)index {
2789 if (metadata_->index_ != index)
2790 metadata_->index_ = index;
2793 - (CYString &) cyname {
2794 return name_.empty() ? id_ : name_;
2797 - (uint32_t) compareBySection:(NSArray *)sections {
2798 NSString *section([self section]);
2799 for (size_t i(0), e([sections count]); i != e; ++i) {
2800 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2804 return _not(uint32_t);
2808 @synchronized (database_) {
2809 pkgProblemResolver *resolver = [database_ resolver];
2810 resolver->Clear(iterator_);
2812 pkgCacheFile &cache([database_ cache]);
2813 cache->SetReInstall(iterator_, false);
2814 cache->MarkKeep(iterator_, false);
2818 @synchronized (database_) {
2819 pkgProblemResolver *resolver = [database_ resolver];
2820 resolver->Clear(iterator_);
2821 resolver->Protect(iterator_);
2823 pkgCacheFile &cache([database_ cache]);
2824 cache->SetReInstall(iterator_, false);
2825 cache->MarkInstall(iterator_, false);
2827 pkgDepCache::StateCache &state((*cache)[iterator_]);
2828 if (!state.Install())
2829 cache->SetReInstall(iterator_, true);
2833 @synchronized (database_) {
2834 pkgProblemResolver *resolver = [database_ resolver];
2835 resolver->Clear(iterator_);
2836 resolver->Remove(iterator_);
2837 resolver->Protect(iterator_);
2839 pkgCacheFile &cache([database_ cache]);
2840 cache->SetReInstall(iterator_, false);
2841 cache->MarkDelete(iterator_, true);
2844 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2845 _profile(Package$isUnfilteredAndSearchedForBy)
2848 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2849 value &= [self unfiltered];
2852 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2853 value &= [self matches:search];
2860 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2861 if ([search length] == 0)
2864 _profile(Package$isUnfilteredAndSelectedForBy)
2867 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2868 value &= [self unfiltered];
2871 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2872 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2879 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2880 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2883 - (bool) isVisibleInSection:(NSString *)name {
2884 NSString *section([self section]);
2888 section == nil && [name length] == 0 ||
2889 [name isEqualToString:section]
2890 ) && [self visible];
2893 - (bool) isVisibleInSource:(Source *)source {
2894 return [self source] == source && [self visible];
2899 /* Section Class {{{ */
2900 @interface Section : NSObject {
2905 NSString *localized_;
2908 - (NSComparisonResult) compareByLocalized:(Section *)section;
2909 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2910 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2911 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2912 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2913 - (NSString *) name;
2920 - (void) addToCount;
2922 - (void) setCount:(size_t)count;
2923 - (NSString *) localized;
2927 @implementation Section
2931 if (localized_ != nil)
2932 [localized_ release];
2936 - (NSComparisonResult) compareByLocalized:(Section *)section {
2937 NSString *lhs(localized_);
2938 NSString *rhs([section localized]);
2940 /*if ([lhs length] != 0 && [rhs length] != 0) {
2941 unichar lhc = [lhs characterAtIndex:0];
2942 unichar rhc = [rhs characterAtIndex:0];
2944 if (isalpha(lhc) && !isalpha(rhc))
2945 return NSOrderedAscending;
2946 else if (!isalpha(lhc) && isalpha(rhc))
2947 return NSOrderedDescending;
2950 return [lhs compare:rhs options:LaxCompareOptions_];
2953 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2954 if ((self = [self initWithName:name localize:NO]) != nil) {
2955 if (localized != nil)
2956 localized_ = [localized retain];
2960 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2961 return [self initWithName:name row:0 localize:localize];
2964 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2965 if ((self = [super init]) != nil) {
2966 name_ = [name retain];
2970 localized_ = [LocalizeSection(name_) retain];
2974 /* XXX: localize the index thingees */
2975 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2976 if ((self = [super init]) != nil) {
2977 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2983 - (NSString *) name {
3003 - (void) addToCount {
3007 - (void) setCount:(size_t)count {
3011 - (NSString *) localized {
3018 static NSString *Colon_;
3019 static NSString *Elision_;
3020 static NSString *Error_;
3021 static NSString *Warning_;
3023 /* Database Implementation {{{ */
3024 @implementation Database
3026 + (Database *) sharedInstance {
3027 static Database *instance;
3028 if (instance == nil)
3029 instance = [[Database alloc] init];
3037 - (void) releasePackages {
3038 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3039 CFArrayRemoveAllValues(packages_);
3043 // XXX: actually implement this thing
3046 CFRelease(deadSources_);
3047 [self releasePackages];
3048 apr_pool_destroy(pool_);
3049 NSRecycleZone(zone_);
3053 - (void) _readCydia:(NSNumber *)fd { _pooled
3054 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3055 std::istream is(&ib);
3058 static Pcre finish_r("^finish:([^:]*)$");
3060 while (std::getline(is, line)) {
3061 const char *data(line.c_str());
3062 size_t size = line.size();
3063 lprintf("C:%s\n", data);
3065 if (finish_r(data, size)) {
3066 NSString *finish = finish_r[1];
3067 int index = [Finishes_ indexOfObject:finish];
3068 if (index != INT_MAX && index > Finish_)
3076 - (void) _readStatus:(NSNumber *)fd { _pooled
3077 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3078 std::istream is(&ib);
3081 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3082 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3084 while (std::getline(is, line)) {
3085 const char *data(line.c_str());
3086 size_t size(line.size());
3087 lprintf("S:%s\n", data);
3089 if (conffile_r(data, size)) {
3090 [delegate_ setConfigurationData:conffile_r[1]];
3091 } else if (strncmp(data, "status: ", 8) == 0) {
3092 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3093 [delegate_ setProgressTitle:string];
3094 } else if (pmstatus_r(data, size)) {
3095 std::string type([pmstatus_r[1] UTF8String]);
3096 NSString *id = pmstatus_r[2];
3098 float percent([pmstatus_r[3] floatValue]);
3099 [delegate_ setProgressPercent:(percent / 100)];
3101 NSString *string = pmstatus_r[4];
3103 if (type == "pmerror")
3104 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3105 withObject:[NSArray arrayWithObjects:string, id, nil]
3108 else if (type == "pmstatus") {
3109 [delegate_ setProgressTitle:string];
3110 } else if (type == "pmconffile")
3111 [delegate_ setConfigurationData:string];
3113 lprintf("E:unknown pmstatus\n");
3115 lprintf("E:unknown status\n");
3121 - (void) _readOutput:(NSNumber *)fd { _pooled
3122 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3123 std::istream is(&ib);
3126 while (std::getline(is, line)) {
3127 lprintf("O:%s\n", line.c_str());
3128 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3138 - (Package *) packageWithName:(NSString *)name {
3139 @synchronized (self) {
3140 if (static_cast<pkgDepCache *>(cache_) == NULL)
3142 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3143 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3147 if ((self = [super init]) != nil) {
3154 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3155 apr_pool_create(&pool_, NULL);
3157 size_t capacity(MetaFile_->active_);
3163 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3164 deadSources_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
3168 _assert(pipe(fds) != -1);
3171 _config->Set("APT::Keep-Fds::", cydiafd_);
3172 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3175 detachNewThreadSelector:@selector(_readCydia:)
3177 withObject:[NSNumber numberWithInt:fds[0]]
3180 _assert(pipe(fds) != -1);
3184 detachNewThreadSelector:@selector(_readStatus:)
3186 withObject:[NSNumber numberWithInt:fds[0]]
3189 _assert(pipe(fds) != -1);
3190 _assert(dup2(fds[0], 0) != -1);
3191 _assert(close(fds[0]) != -1);
3193 input_ = fdopen(fds[1], "a");
3195 _assert(pipe(fds) != -1);
3196 _assert(dup2(fds[1], 1) != -1);
3197 _assert(close(fds[1]) != -1);
3200 detachNewThreadSelector:@selector(_readOutput:)
3202 withObject:[NSNumber numberWithInt:fds[0]]
3207 - (pkgCacheFile &) cache {
3211 - (pkgDepCache::Policy *) policy {
3215 - (pkgRecords *) records {
3219 - (pkgProblemResolver *) resolver {
3223 - (pkgAcquire &) fetcher {
3227 - (pkgSourceList &) list {
3231 - (NSArray *) packages {
3232 return (NSArray *) packages_;
3235 - (NSArray *) sources {
3236 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3237 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3238 [sources addObject:i->second];
3239 [sources addObjectsFromArray:(NSArray *)deadSources_];
3243 - (NSArray *) issues {
3244 if (cache_->BrokenCount() == 0)
3247 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3249 for (Package *package in [self packages]) {
3250 if (![package broken])
3252 pkgCache::PkgIterator pkg([package iterator]);
3254 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3255 [entry addObject:[package name]];
3256 [issues addObject:entry];
3258 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3262 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3263 pkgCache::DepIterator start;
3264 pkgCache::DepIterator end;
3265 dep.GlobOr(start, end); // ++dep
3267 if (!cache_->IsImportantDep(end))
3269 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3272 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3273 [entry addObject:failure];
3274 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3276 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3277 if (Package *package = [self packageWithName:name])
3278 name = [package name];
3279 [failure addObject:name];
3281 pkgCache::PkgIterator target(start.TargetPkg());
3282 if (target->ProvidesList != 0)
3283 [failure addObject:@"?"];
3285 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3287 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3288 else if (!cache_[target].CandidateVerIter(cache_).end())
3289 [failure addObject:@"-"];
3290 else if (target->ProvidesList == 0)
3291 [failure addObject:@"!"];
3293 [failure addObject:@"%"];
3297 if (start.TargetVer() != 0)
3298 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3309 - (bool) popErrorWithTitle:(NSString *)title {
3311 std::string message;
3313 while (!_error->empty()) {
3315 bool warning(!_error->PopMessage(error));
3319 size_t size(error.size());
3320 if (size == 0 || error[size - 1] != '\n')
3322 error.resize(size - 1);
3324 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3326 if (!message.empty())
3331 if (fatal && !message.empty())
3332 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3337 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3338 return [self popErrorWithTitle:title] || !success;
3341 - (void) reloadData { CYPoolStart() {
3342 @synchronized (self) {
3345 [self releasePackages];
3348 CFArrayRemoveAllValues(deadSources_);
3368 apr_pool_clear(pool_);
3370 NSRecycleZone(zone_);
3371 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3373 int chk(creat("/tmp/cydia.chk", 0644));
3377 NSString *title(UCLocalize("DATABASE"));
3380 if (!cache_.Open(progress_, true)) { pop:
3382 bool warning(!_error->PopMessage(error));
3383 lprintf("cache_.Open():[%s]\n", error.c_str());
3385 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3386 [delegate_ repairWithSelector:@selector(configure)];
3387 else if (error == "The package lists or status file could not be parsed or opened.")
3388 [delegate_ repairWithSelector:@selector(update)];
3389 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3390 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3391 // else if (error == "The list of sources could not be read.")
3393 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3402 unlink("/tmp/cydia.chk");
3404 now_ = [[NSDate date] timeIntervalSince1970];
3406 policy_ = new pkgDepCache::Policy();
3407 records_ = new pkgRecords(cache_);
3408 resolver_ = new pkgProblemResolver(cache_);
3409 fetcher_ = new pkgAcquire(&status_);
3412 list_ = new pkgSourceList();
3413 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3416 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3417 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3421 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3424 if (cache_->BrokenCount() != 0) {
3425 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3428 if (cache_->BrokenCount() != 0) {
3429 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3433 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3437 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3439 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3440 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3441 // XXX: this could be more intelligent
3442 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3443 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3444 if (!cached.end()) {
3445 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3450 CFArrayAppendValue(deadSources_, [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3454 /*std::vector<Package *> packages;
3455 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3456 [packages_ release];
3461 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3462 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3463 //packages.push_back(package);
3464 CFArrayAppendValue(packages_, [package retain]);
3468 /*if (packages.empty())
3469 packages_ = [[NSArray alloc] init];
3471 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3474 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3475 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3476 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3484 /*if (!packages.empty())
3485 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3486 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3488 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3490 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3492 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3496 size_t count(CFArrayGetCount(packages_));
3497 MetaFile_->active_ = count;
3499 for (size_t index(0); index != count; ++index)
3500 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3504 } } CYPoolEnd() _trace(); }
3507 @synchronized (self) {
3509 resolver_ = new pkgProblemResolver(cache_);
3511 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3512 if (!cache_[iterator].Keep()) {
3513 cache_->MarkKeep(iterator, false);
3514 cache_->SetReInstall(iterator, false);
3519 - (void) configure {
3520 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3522 system([dpkg UTF8String]);
3527 // XXX: I don't remember this condition
3532 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3534 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3536 if ([self popErrorWithTitle:title])
3540 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3543 public pkgArchiveCleaner
3546 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3551 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3558 fetcher_->Shutdown();
3560 pkgRecords records(cache_);
3562 lock_ = new FileFd();
3563 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3565 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3567 if ([self popErrorWithTitle:title])
3571 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3574 manager_ = (_system->CreatePM(cache_));
3575 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3582 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3584 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3586 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3588 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3589 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3592 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3597 [CydiaApp retainNetworkActivityIndicator];
3599 bool failed = false;
3600 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3601 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3603 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3606 std::string uri = (*item)->DescURI();
3607 std::string error = (*item)->ErrorText;
3609 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3612 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3613 withObject:[NSArray arrayWithObjects:
3614 [NSString stringWithUTF8String:error.c_str()],
3620 [CydiaApp releaseNetworkActivityIndicator];
3628 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3630 if (_error->PendingError()) {
3635 if (result == pkgPackageManager::Failed) {
3640 if (result != pkgPackageManager::Completed) {
3645 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3647 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3649 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3650 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3653 if (![before isEqualToArray:after])
3658 NSString *title(UCLocalize("UPGRADE"));
3659 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3665 [self updateWithStatus:status_];
3668 - (void) updateWithStatus:(Status &)status {
3669 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3670 NSString *title(UCLocalize("REFRESHING_DATA"));
3673 if (!list.ReadMainList())
3674 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3677 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3678 if ([self popErrorWithTitle:title])
3681 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3682 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3683 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3685 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3689 - (void) setDelegate:(id)delegate {
3690 delegate_ = delegate;
3691 status_.setDelegate(delegate);
3692 progress_.setDelegate(delegate);
3695 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3696 SourceMap::const_iterator i(sources_.find(file->ID));
3697 return i == sources_.end() ? nil : i->second;
3700 - (NSString *) mappedSectionForPointer:(const char *)section {
3701 _H<NSString> *mapped;
3703 _profile(Database$mappedSectionForPointer$Cache)
3704 mapped = §ions_[section];
3707 if (*mapped == NULL) {
3708 size_t length(strlen(section));
3709 char spaced[length + 1];
3711 _profile(Database$mappedSectionForPointer$Replace)
3712 for (size_t index(0); index != length; ++index)
3713 spaced[index] = section[index] == '_' ? ' ' : section[index];
3714 spaced[length] = '\0';
3719 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3720 string = [NSString stringWithUTF8String:spaced];
3723 _profile(Database$mappedSectionForPointer$Map)
3724 string = [SectionMap_ objectForKey:string] ?: string;
3734 /* Web Scripting {{{ */
3735 @interface CydiaObject : NSObject {
3737 _transient id delegate_;
3740 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3743 @implementation CydiaObject
3746 [indirect_ release];
3750 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3751 if ((self = [super init]) != nil) {
3752 indirect_ = [indirect retain];
3756 - (void) setDelegate:(id)delegate {
3757 delegate_ = delegate;
3760 + (NSArray *) _attributeKeys {
3761 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3764 - (NSArray *) attributeKeys {
3765 return [[self class] _attributeKeys];
3768 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3769 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3772 - (NSString *) device {
3773 return [[UIDevice currentDevice] uniqueIdentifier];
3776 #if 0 // XXX: implement!
3777 - (NSString *) mac {
3778 if (![indirect_ promptForSensitive:@"Mac Address"])
3782 - (NSString *) serial {
3783 if (![indirect_ promptForSensitive:@"Serial #"])
3787 - (NSString *) firewire {
3788 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3792 - (NSString *) imei {
3793 if (![indirect_ promptForSensitive:@"IMEI"])
3798 + (NSString *) webScriptNameForSelector:(SEL)selector {
3799 if (selector == @selector(close))
3801 else if (selector == @selector(getInstalledPackages))
3802 return @"getInstalledPackages";
3803 else if (selector == @selector(getPackageById:))
3804 return @"getPackageById";
3805 else if (selector == @selector(installPackages:))
3806 return @"installPackages";
3807 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3808 return @"setButtonImage";
3809 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3810 return @"setButtonTitle";
3811 else if (selector == @selector(setPopupHook:))
3812 return @"setPopupHook";
3813 else if (selector == @selector(setSpecial:))
3814 return @"setSpecial";
3815 else if (selector == @selector(setToken:))
3817 else if (selector == @selector(setViewportWidth:))
3818 return @"setViewportWidth";
3819 else if (selector == @selector(supports:))
3821 else if (selector == @selector(stringWithFormat:arguments:))
3823 else if (selector == @selector(localizedStringForKey:value:table:))
3825 else if (selector == @selector(du:))
3827 else if (selector == @selector(statfs:))
3833 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3834 return [self webScriptNameForSelector:selector] == nil;
3837 - (BOOL) supports:(NSString *)feature {
3838 return [feature isEqualToString:@"window.open"];
3841 - (NSArray *) getInstalledPackages {
3842 NSArray *packages([[Database sharedInstance] packages]);
3843 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3844 for (Package *package in packages)
3845 if ([package installed] != nil)
3846 [installed addObject:package];
3850 - (Package *) getPackageById:(NSString *)id {
3851 Package *package([[Database sharedInstance] packageWithName:id]);
3856 - (NSArray *) statfs:(NSString *)path {
3859 if (path == nil || statfs([path UTF8String], &stat) == -1)
3862 return [NSArray arrayWithObjects:
3863 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3864 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3865 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3869 - (NSNumber *) du:(NSString *)path {
3870 NSNumber *value(nil);
3873 _assert(pipe(fds) != -1);
3875 pid_t pid(ExecFork());
3877 _assert(dup2(fds[1], 1) != -1);
3878 _assert(close(fds[0]) != -1);
3879 _assert(close(fds[1]) != -1);
3880 /* XXX: this should probably not use du */
3881 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3886 _assert(close(fds[1]) != -1);
3888 if (FILE *du = fdopen(fds[0], "r")) {
3890 while (fgets(line, sizeof(line), du) != NULL) {
3891 size_t length(strlen(line));
3892 while (length != 0 && line[length - 1] == '\n')
3893 line[--length] = '\0';
3894 if (char *tab = strchr(line, '\t')) {
3896 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3901 } else _assert(close(fds[0]));
3905 if (waitpid(pid, &status, 0) == -1)
3908 else _assert(false);
3917 - (void) installPackages:(NSArray *)packages {
3918 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3921 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3922 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3925 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3926 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3929 - (void) setSpecial:(id)function {
3930 [indirect_ setSpecial:function];
3933 - (void) setToken:(NSString *)token {
3936 Token_ = [token retain];
3938 [Metadata_ setObject:Token_ forKey:@"Token"];
3942 - (void) setPopupHook:(id)function {
3943 [indirect_ setPopupHook:function];
3946 - (void) setViewportWidth:(float)width {
3947 [indirect_ setViewportWidth:width];
3950 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3951 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3952 unsigned count([arguments count]);
3954 for (unsigned i(0); i != count; ++i)
3955 values[i] = [arguments objectAtIndex:i];
3956 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3959 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3960 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3962 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3964 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3970 /* @ Loading... Indicator {{{ */
3971 @interface CYLoadingIndicator : UIView {
3972 UIActivityIndicatorView *spinner_;
3977 @property (readonly, nonatomic) UILabel *label;
3978 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
3982 @implementation CYLoadingIndicator
3984 - (id)initWithFrame:(CGRect)frame {
3985 if ((self = [super initWithFrame:frame])) {
3986 container_ = [[[UIView alloc] init] autorelease];
3987 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
3989 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
3990 [spinner_ startAnimating];
3991 [container_ addSubview:spinner_];
3993 label_ = [[[UILabel alloc] init] autorelease];
3994 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
3995 [label_ setBackgroundColor:[UIColor clearColor]];
3996 [label_ setTextColor:[UIColor blackColor]];
3997 [label_ setShadowColor:[UIColor whiteColor]];
3998 [label_ setShadowOffset:CGSizeMake(0, 1)];
3999 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4000 [container_ addSubview:label_];
4002 CGSize viewsize = frame.size;
4003 CGSize spinnersize = [spinner_ bounds].size;
4004 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4005 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4007 CGRect containrect = {
4008 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4009 CGSizeMake(bothwidth, spinnersize.height)
4012 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4020 [container_ setFrame:containrect];
4021 [spinner_ setFrame:spinrect];
4022 [label_ setFrame:textrect];
4023 [self addSubview:container_];
4029 - (UILabel *)label { return label_; }
4030 - (UIActivityIndicatorView *)activityIndicatorView { return spinner_; }
4034 /* Emulated Loading Controller {{{ */
4035 @interface CYEmulatedLoadingController : CYViewController {
4036 CYLoadingIndicator *indicator_;
4038 UINavigationBar *navbar_;
4042 @implementation CYEmulatedLoadingController
4044 - (CYEmulatedLoadingController *) init {
4045 if ((self = [super init])) {
4046 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4048 indicator_ = [[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]];
4049 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4050 [[self view] addSubview:indicator_];
4051 [indicator_ release];
4053 tabbar_ = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
4054 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4055 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4056 [[self view] addSubview:tabbar_];
4059 navbar_ = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
4060 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4061 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4062 [[self view] addSubview:navbar_];
4070 /* Cydia Browser Controller {{{ */
4071 @interface CYBrowserController : BrowserController {
4072 CydiaObject *cydia_;
4077 @implementation CYBrowserController
4084 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4087 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4088 [super webView:view didClearWindowObject:window forFrame:frame];
4090 WebDataSource *source([frame dataSource]);
4091 NSURLResponse *response([source response]);
4093 NSURL *url([response URL]);
4094 NSString *scheme([url scheme]);
4095 NSString *host([url host]);
4097 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4098 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4099 NSDictionary *headers([http allHeaderFields]);
4100 [self setHeaders:headers forHost:host];
4104 [host isEqualToString:@"cydia.saurik.com"] ||
4105 [host hasSuffix:@".cydia.saurik.com"] ||
4106 [scheme isEqualToString:@"file"]
4108 [window setValue:cydia_ forKey:@"cydia"];
4111 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4112 if (System_ != NULL)
4113 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4114 if (Machine_ != NULL)
4115 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4117 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4119 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4122 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4123 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4124 [self _setMoreHeaders:copy];
4128 - (void) setDelegate:(id)delegate {
4129 [super setDelegate:delegate];
4130 [cydia_ setDelegate:delegate];
4134 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4135 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4137 WebView *webview([[webview_ _documentView] webView]);
4139 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4141 NSString *application = package == nil ? @"Cydia" : [NSString
4142 stringWithFormat:@"Cydia/%@",
4147 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4149 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4150 if (Product_ != nil)
4151 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4153 [webview setApplicationNameForUserAgent:application];
4160 /* Confirmation Controller {{{ */
4161 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4162 if (!iterator.end())
4163 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4164 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4166 pkgCache::PkgIterator package(dep.TargetPkg());
4169 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4176 @protocol ConfirmationControllerDelegate
4177 - (void) cancelAndClear:(bool)clear;
4178 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4182 @interface ConfirmationController : CYBrowserController {
4183 _transient Database *database_;
4184 UIAlertView *essential_;
4191 - (id) initWithDatabase:(Database *)database;
4195 @implementation ConfirmationController
4202 if (essential_ != nil)
4203 [essential_ release];
4207 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4208 NSString *context([alert context]);
4210 if ([context isEqualToString:@"remove"]) {
4211 if (button == [alert cancelButtonIndex]) {
4212 [self dismissModalViewControllerAnimated:YES];
4213 } else if (button == [alert firstOtherButtonIndex]) {
4216 [delegate_ confirmWithNavigationController:[self navigationController]];
4219 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4220 } else if ([context isEqualToString:@"unable"]) {
4221 [self dismissModalViewControllerAnimated:YES];
4222 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4224 [super alertView:alert clickedButtonAtIndex:button];
4228 - (void) _doContinue {
4229 [self dismissModalViewControllerAnimated:YES];
4230 [delegate_ cancelAndClear:NO];
4233 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4234 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4238 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4239 [super webView:view didClearWindowObject:window forFrame:frame];
4240 [window setValue:changes_ forKey:@"changes"];
4241 [window setValue:issues_ forKey:@"issues"];
4242 [window setValue:sizes_ forKey:@"sizes"];
4243 [window setValue:self forKey:@"queue"];
4246 - (id) initWithDatabase:(Database *)database {
4247 if ((self = [super init]) != nil) {
4248 database_ = database;
4250 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4252 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4253 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4254 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4255 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4256 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4260 pkgDepCache::Policy *policy([database_ policy]);
4262 pkgCacheFile &cache([database_ cache]);
4263 NSArray *packages = [database_ packages];
4264 for (Package *package in packages) {
4265 pkgCache::PkgIterator iterator = [package iterator];
4266 pkgDepCache::StateCache &state(cache[iterator]);
4268 NSString *name([package name]);
4270 if (state.NewInstall())
4271 [installing addObject:name];
4272 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4273 [reinstalling addObject:name];
4274 else if (state.Upgrade())
4275 [upgrading addObject:name];
4276 else if (state.Downgrade())
4277 [downgrading addObject:name];
4278 else if (state.Delete()) {
4279 if ([package essential])
4281 [removing addObject:name];
4284 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4285 substrate_ |= DepSubstrate(iterator.CurrentVer());
4290 else if (Advanced_) {
4291 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4293 essential_ = [[UIAlertView alloc]
4294 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4295 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4297 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4298 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4301 [essential_ setContext:@"remove"];
4303 essential_ = [[UIAlertView alloc]
4304 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4305 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4307 cancelButtonTitle:UCLocalize("OKAY")
4308 otherButtonTitles:nil
4311 [essential_ setContext:@"unable"];
4314 changes_ = [[NSArray alloc] initWithObjects:
4322 issues_ = [database_ issues];
4324 issues_ = [issues_ retain];
4326 sizes_ = [[NSArray alloc] initWithObjects:
4327 SizeString([database_ fetcher].FetchNeeded()),
4328 SizeString([database_ fetcher].PartialPresent()),
4331 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4333 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4334 initWithTitle:UCLocalize("CANCEL")
4335 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4336 style:UIBarButtonItemStylePlain
4338 action:@selector(cancelButtonClicked)
4343 - (void) applyRightButton {
4344 #if !AlwaysReload && !IgnoreInstall
4345 if (issues_ == nil && ![self isLoading])
4346 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4347 initWithTitle:UCLocalize("CONFIRM")
4348 style:UIBarButtonItemStylePlain
4350 action:@selector(confirmButtonClicked)
4353 [super applyRightButton];
4355 [[self navigationItem] setRightBarButtonItem:nil];
4359 - (void) cancelButtonClicked {
4360 [self dismissModalViewControllerAnimated:YES];
4361 [delegate_ cancelAndClear:YES];
4365 - (void) confirmButtonClicked {
4369 if (essential_ != nil)
4374 [delegate_ confirmWithNavigationController:[self navigationController]];
4382 /* Progress Data {{{ */
4383 @interface ProgressData : NSObject {
4385 // XXX: should these really both be _transient?
4386 _transient id target_;
4387 _transient id object_;
4390 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4397 @implementation ProgressData
4399 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4400 if ((self = [super init]) != nil) {
4401 selector_ = selector;
4421 /* Progress Controller {{{ */
4422 @interface ProgressController : CYViewController <
4423 ConfigurationDelegate,
4426 _transient Database *database_;
4427 UIProgressBar *progress_;
4428 UITextView *output_;
4429 UITextLabel *status_;
4430 UIPushButton *close_;
4432 SHA1SumValue springlist_;
4433 SHA1SumValue notifyconf_;
4437 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4439 - (void) _retachThread;
4440 - (void) _detachNewThreadData:(ProgressData *)data;
4441 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4447 @protocol ProgressControllerDelegate
4448 - (void) progressControllerIsComplete:(ProgressController *)sender;
4451 @implementation ProgressController
4454 [database_ setDelegate:nil];
4455 [progress_ release];
4464 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4465 if ((self = [super init]) != nil) {
4466 database_ = database;
4467 [database_ setDelegate:self];
4468 delegate_ = delegate;
4470 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4472 progress_ = [[UIProgressBar alloc] init];
4473 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4474 [progress_ setStyle:0];
4476 status_ = [[UITextLabel alloc] init];
4477 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4478 [status_ setColor:[UIColor whiteColor]];
4479 [status_ setBackgroundColor:[UIColor clearColor]];
4480 [status_ setCentersHorizontally:YES];
4481 //[status_ setFont:font];
4483 output_ = [[UITextView alloc] init];
4484 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4485 //[output_ setTextFont:@"Courier New"];
4486 [output_ setFont:[[output_ font] fontWithSize:12]];
4487 [output_ setTextColor:[UIColor whiteColor]];
4488 [output_ setBackgroundColor:[UIColor clearColor]];
4489 [output_ setMarginTop:0];
4490 [output_ setAllowsRubberBanding:YES];
4491 [output_ setEditable:NO];
4492 [[self view] addSubview:output_];
4494 close_ = [[UIPushButton alloc] init];
4495 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4496 [close_ setAutosizesToFit:NO];
4497 [close_ setDrawsShadow:YES];
4498 [close_ setStretchBackground:YES];
4499 [close_ setEnabled:YES];
4500 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4501 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4502 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4503 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4507 - (void) positionViews {
4508 CGRect bounds = [[self view] bounds];
4509 CGSize prgsize = [UIProgressBar defaultSize];
4512 (bounds.size.width - prgsize.width) / 2,
4513 bounds.size.height - prgsize.height - 20
4516 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4518 [progress_ setFrame:prgrect];
4519 [status_ setFrame:CGRectMake(
4521 bounds.size.height - prgsize.height - 50,
4522 bounds.size.width - 20,
4525 [output_ setFrame:CGRectMake(
4528 bounds.size.width - 20,
4529 bounds.size.height - 96
4531 [close_ setFrame:CGRectMake(
4532 (bounds.size.width - closewidth) / 2,
4533 bounds.size.height - prgsize.height - 50,
4539 - (void) viewWillAppear:(BOOL)animated {
4540 [super viewDidAppear:animated];
4541 [[self navigationItem] setHidesBackButton:YES];
4542 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4544 [self positionViews];
4547 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4548 [self positionViews];
4551 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4552 NSString *context([alert context]);
4554 if ([context isEqualToString:@"conffile"]) {
4555 FILE *input = [database_ input];
4556 if (button == [alert cancelButtonIndex])
4557 fprintf(input, "N\n");
4558 else if (button == [alert firstOtherButtonIndex])
4559 fprintf(input, "Y\n");
4564 - (void) closeButtonPushed {
4567 UpdateExternalStatus(0);
4571 [self dismissModalViewControllerAnimated:YES];
4575 [delegate_ terminateWithSuccess];
4576 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4577 [delegate_ suspendWithAnimation:YES];
4579 [delegate_ suspend];*/
4591 system("/usr/bin/sbreload");
4597 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4598 SBReboot(SBSSpringBoardServerPort());
4600 reboot2(RB_AUTOBOOT);
4605 - (void) _retachThread {
4606 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4608 [[self view] addSubview:close_];
4609 [progress_ removeFromSuperview];
4610 [status_ removeFromSuperview];
4612 [database_ popErrorWithTitle:title_];
4613 [delegate_ progressControllerIsComplete:self];
4617 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4620 MMap mmap(file, MMap::ReadOnly);
4622 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4623 if (!(notifyconf_ == sha1.Result()))
4630 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4633 MMap mmap(file, MMap::ReadOnly);
4635 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4636 if (!(springlist_ == sha1.Result()))
4642 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4643 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4644 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4645 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4646 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4650 system("su -c /usr/bin/uicache mobile");
4653 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4655 [delegate_ setStatusBarShowsProgress:NO];
4658 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4659 [[data target] performSelector:[data selector] withObject:[data object]];
4660 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4663 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4664 UpdateExternalStatus(1);
4671 title_ = [title retain];
4673 [[self navigationItem] setTitle:title_];
4675 [status_ setText:nil];
4676 [output_ setText:@""];
4677 [progress_ setProgress:0];
4679 [close_ removeFromSuperview];
4680 [[self view] addSubview:progress_];
4681 [[self view] addSubview:status_];
4683 [delegate_ setStatusBarShowsProgress:YES];
4688 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4691 MMap mmap(file, MMap::ReadOnly);
4693 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4694 notifyconf_ = sha1.Result();
4700 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4703 MMap mmap(file, MMap::ReadOnly);
4705 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4706 springlist_ = sha1.Result();
4711 detachNewThreadSelector:@selector(_detachNewThreadData:)
4713 withObject:[[[ProgressData alloc]
4714 initWithSelector:selector
4721 - (void) repairWithSelector:(SEL)selector {
4723 detachNewThreadSelector:selector
4726 title:UCLocalize("REPAIRING")
4730 - (void) setConfigurationData:(NSString *)data {
4732 performSelectorOnMainThread:@selector(_setConfigurationData:)
4738 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4739 CYActionSheet *sheet([[[CYActionSheet alloc]
4741 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4742 defaultButtonIndex:0
4745 [sheet setMessage:error];
4746 [sheet yieldToPopupAlertAnimated:YES];
4750 - (void) setProgressTitle:(NSString *)title {
4752 performSelectorOnMainThread:@selector(_setProgressTitle:)
4758 - (void) setProgressPercent:(float)percent {
4760 performSelectorOnMainThread:@selector(_setProgressPercent:)
4761 withObject:[NSNumber numberWithFloat:percent]
4766 - (void) startProgress {
4769 - (void) addProgressOutput:(NSString *)output {
4771 performSelectorOnMainThread:@selector(_addProgressOutput:)
4777 - (bool) isCancelling:(size_t)received {
4781 - (void) _setConfigurationData:(NSString *)data {
4782 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4784 if (!conffile_r(data)) {
4785 lprintf("E:invalid conffile\n");
4789 NSString *ofile = conffile_r[1];
4790 //NSString *nfile = conffile_r[2];
4792 UIAlertView *alert = [[[UIAlertView alloc]
4793 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4794 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4796 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4797 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4798 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4802 [alert setContext:@"conffile"];
4806 - (void) _setProgressTitle:(NSString *)title {
4807 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4808 for (size_t i(0), e([words count]); i != e; ++i) {
4809 NSString *word([words objectAtIndex:i]);
4810 if (Package *package = [database_ packageWithName:word])
4811 [words replaceObjectAtIndex:i withObject:[package name]];
4814 [status_ setText:[words componentsJoinedByString:@" "]];
4817 - (void) _setProgressPercent:(NSNumber *)percent {
4818 [progress_ setProgress:[percent floatValue]];
4821 - (void) _addProgressOutput:(NSString *)output {
4822 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4823 CGSize size = [output_ contentSize];
4824 CGPoint offset = [output_ contentOffset];
4825 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
4826 CGRect rect = {{0, size.height-1}, {size.width, 1}};
4827 [output_ scrollRectToVisible:rect animated:YES];
4831 - (BOOL) isRunning {
4838 /* Cell Content View {{{ */
4839 @protocol ContentDelegate
4840 - (void) drawContentRect:(CGRect)rect;
4843 @interface ContentView : UIView {
4844 _transient id<ContentDelegate> delegate_;
4849 @implementation ContentView
4851 - (id) initWithFrame:(CGRect)frame {
4852 if ((self = [super initWithFrame:frame]) != nil) {
4853 [self setNeedsDisplayOnBoundsChange:YES];
4857 - (void) setDelegate:(id<ContentDelegate>)delegate {
4858 delegate_ = delegate;
4861 - (void) drawRect:(CGRect)rect {
4862 [super drawRect:rect];
4863 [delegate_ drawContentRect:rect];
4868 /* Cydia TableView Cell {{{ */
4869 @interface CYTableViewCell : UITableViewCell {
4870 ContentView *content_;
4876 @implementation CYTableViewCell
4883 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4884 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4886 if (view == content_) {
4887 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4888 highlighted_ = highlighted;
4891 [super _updateHighlightColorsForView:view highlighted:highlighted];
4894 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4895 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4896 highlighted_ = selected;
4898 [super setSelected:selected animated:animated];
4899 [content_ setNeedsDisplay];
4905 /* Package Cell {{{ */
4906 @interface PackageCell : CYTableViewCell <
4911 NSString *description_;
4919 - (PackageCell *) init;
4920 - (void) setPackage:(Package *)package;
4922 - (void) drawContentRect:(CGRect)rect;
4926 @implementation PackageCell
4928 - (void) clearPackage {
4939 if (description_ != nil) {
4940 [description_ release];
4944 if (source_ != nil) {
4949 if (badge_ != nil) {
4954 if (placard_ != nil) {
4964 [self clearPackage];
4968 - (PackageCell *) init {
4969 CGRect frame(CGRectMake(0, 0, 320, 74));
4970 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4971 UIView *content([self contentView]);
4972 CGRect bounds([content bounds]);
4974 content_ = [[ContentView alloc] initWithFrame:bounds];
4975 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4976 [content addSubview:content_];
4978 [content_ setDelegate:self];
4979 [content_ setOpaque:YES];
4983 - (void) _setBackgroundColor {
4985 if (NSString *mode = [package_ mode]) {
4986 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4987 color = remove ? RemovingColor_ : InstallingColor_;
4989 color = [UIColor whiteColor];
4991 [content_ setBackgroundColor:color];
4992 [self setNeedsDisplay];
4995 - (NSString *) accessibilityLabel {
4996 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
4999 - (void) setPackage:(Package *)package {
5000 [self clearPackage];
5003 Source *source = [package source];
5005 icon_ = [[package icon] retain];
5006 name_ = [[package name] retain];
5009 description_ = [package longDescription];
5010 if (description_ == nil)
5011 description_ = [package shortDescription];
5012 if (description_ != nil)
5013 description_ = [description_ retain];
5015 commercial_ = [package isCommercial];
5017 package_ = [package retain];
5019 NSString *label = nil;
5020 bool trusted = false;
5022 if (source != nil) {
5023 label = [source label];
5024 trusted = [source trusted];
5025 } else if ([[package id] isEqualToString:@"firmware"])
5026 label = UCLocalize("APPLE");
5028 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5030 NSString *from(label);
5032 NSString *section = [package simpleSection];
5033 if (section != nil && ![section isEqualToString:label]) {
5034 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5035 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5038 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5039 source_ = [from retain];
5041 if (NSString *purpose = [package primaryPurpose])
5042 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5043 badge_ = [badge_ retain];
5045 if ([package installed] != nil)
5046 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
5047 placard_ = [placard_ retain];
5049 [self _setBackgroundColor];
5050 [content_ setNeedsDisplay];
5053 - (void) drawContentRect:(CGRect)rect {
5054 bool highlighted(highlighted_);
5055 float width([self bounds].size.width);
5058 CGContextRef context(UIGraphicsGetCurrentContext());
5059 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5060 CGContextFillRect(context, rect);
5065 rect.size = [icon_ size];
5067 rect.size.width /= 2;
5068 rect.size.height /= 2;
5070 rect.origin.x = 25 - rect.size.width / 2;
5071 rect.origin.y = 25 - rect.size.height / 2;
5073 [icon_ drawInRect:rect];
5076 if (badge_ != nil) {
5078 rect.size = [badge_ size];
5080 rect.size.width /= 2;
5081 rect.size.height /= 2;
5083 rect.origin.x = 36 - rect.size.width / 2;
5084 rect.origin.y = 36 - rect.size.height / 2;
5086 [badge_ drawInRect:rect];
5093 UISetColor(commercial_ ? Purple_ : Black_);
5094 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5095 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5098 UISetColor(commercial_ ? Purplish_ : Gray_);
5099 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5101 if (placard_ != nil)
5102 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5107 /* Section Cell {{{ */
5108 @interface SectionCell : CYTableViewCell <
5120 - (void) setSection:(Section *)section editing:(BOOL)editing;
5124 @implementation SectionCell
5126 - (void) clearSection {
5127 if (basic_ != nil) {
5132 if (section_ != nil) {
5142 if (count_ != nil) {
5149 [self clearSection];
5155 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5156 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5157 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5158 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5159 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5161 UIView *content([self contentView]);
5162 CGRect bounds([content bounds]);
5164 content_ = [[ContentView alloc] initWithFrame:bounds];
5165 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5166 [content addSubview:content_];
5167 [content_ setBackgroundColor:[UIColor whiteColor]];
5169 [content_ setDelegate:self];
5173 - (void) onSwitch:(id)sender {
5174 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5175 if (metadata == nil) {
5176 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5177 [Sections_ setObject:metadata forKey:basic_];
5180 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5184 - (void) setSection:(Section *)section editing:(BOOL)editing {
5185 if (editing != editing_) {
5187 [switch_ removeFromSuperview];
5189 [self addSubview:switch_];
5193 [self clearSection];
5195 if (section == nil) {
5196 name_ = [UCLocalize("ALL_PACKAGES") retain];
5199 basic_ = [section name];
5201 basic_ = [basic_ retain];
5203 section_ = [section localized];
5204 if (section_ != nil)
5205 section_ = [section_ retain];
5207 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5208 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5211 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5214 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5215 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5217 [content_ setNeedsDisplay];
5220 - (void) setFrame:(CGRect)frame {
5221 [super setFrame:frame];
5223 CGRect rect([switch_ frame]);
5224 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5227 - (NSString *) accessibilityLabel {
5231 - (void) drawContentRect:(CGRect)rect {
5232 bool highlighted(highlighted_ && !editing_);
5234 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5239 float width(rect.size.width);
5245 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5247 CGSize size = [count_ sizeWithFont:Font14_];
5251 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5257 /* File Table {{{ */
5258 @interface FileTable : CYViewController <
5259 UITableViewDataSource,
5262 _transient Database *database_;
5265 NSMutableArray *files_;
5269 - (id) initWithDatabase:(Database *)database;
5270 - (void) setPackage:(Package *)package;
5274 @implementation FileTable
5277 if (package_ != nil)
5286 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5287 return files_ == nil ? 0 : [files_ count];
5290 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5294 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5295 static NSString *reuseIdentifier = @"Cell";
5297 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5299 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5300 [cell setFont:[UIFont systemFontOfSize:16]];
5302 [cell setText:[files_ objectAtIndex:indexPath.row]];
5303 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5308 - (id) initWithDatabase:(Database *)database {
5309 if ((self = [super init]) != nil) {
5310 database_ = database;
5312 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5314 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5316 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5317 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5318 [list_ setRowHeight:24.0f];
5319 [[self view] addSubview:list_];
5321 [list_ setDataSource:self];
5322 [list_ setDelegate:self];
5326 - (void) setPackage:(Package *)package {
5327 if (package_ != nil) {
5328 [package_ autorelease];
5337 [files_ removeAllObjects];
5339 if (package != nil) {
5340 package_ = [package retain];
5341 name_ = [[package id] retain];
5343 if (NSArray *files = [package files])
5344 [files_ addObjectsFromArray:files];
5346 if ([files_ count] != 0) {
5347 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5348 [files_ removeObjectAtIndex:0];
5349 [files_ sortUsingSelector:@selector(compareByPath:)];
5351 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5352 [stack addObject:@"/"];
5354 for (int i(0), e([files_ count]); i != e; ++i) {
5355 NSString *file = [files_ objectAtIndex:i];
5356 while (![file hasPrefix:[stack lastObject]])
5357 [stack removeLastObject];
5358 NSString *directory = [stack lastObject];
5359 [stack addObject:[file stringByAppendingString:@"/"]];
5360 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5361 ([stack count] - 2) * 3, "",
5362 [file substringFromIndex:[directory length]]
5371 - (void) reloadData {
5372 [self setPackage:[database_ packageWithName:name_]];
5377 /* Package Controller {{{ */
5378 @interface CYPackageController : CYBrowserController <
5379 UIActionSheetDelegate
5381 _transient Database *database_;
5385 NSMutableArray *buttons_;
5386 UIBarButtonItem *button_;
5389 - (id) initWithDatabase:(Database *)database;
5390 - (void) setPackage:(Package *)package;
5394 @implementation CYPackageController
5397 if (package_ != nil)
5414 /* XXX: this is not safe at all... localization of /fail/ */
5415 - (void) _clickButtonWithName:(NSString *)name {
5416 if ([name isEqualToString:UCLocalize("CLEAR")])
5417 [delegate_ clearPackage:package_];
5418 else if ([name isEqualToString:UCLocalize("INSTALL")])
5419 [delegate_ installPackage:package_];
5420 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5421 [delegate_ installPackage:package_];
5422 else if ([name isEqualToString:UCLocalize("REMOVE")])
5423 [delegate_ removePackage:package_];
5424 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5425 [delegate_ installPackage:package_];
5426 else _assert(false);
5429 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5430 NSString *context([sheet context]);
5432 if ([context isEqualToString:@"modify"]) {
5433 if (button != [sheet cancelButtonIndex]) {
5434 NSString *buttonName = [buttons_ objectAtIndex:button];
5435 [self _clickButtonWithName:buttonName];
5438 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5442 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5443 [super webView:view didClearWindowObject:window forFrame:frame];
5444 [window setValue:package_ forKey:@"package"];
5447 - (bool) _allowJavaScriptPanel {
5452 - (void) _customButtonClicked {
5453 int count([buttons_ count]);
5458 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5460 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5461 [buttons addObjectsFromArray:buttons_];
5463 UIActionSheet *sheet = [[[UIActionSheet alloc]
5466 cancelButtonTitle:nil
5467 destructiveButtonTitle:nil
5468 otherButtonTitles:nil
5471 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5473 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5474 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5476 [sheet setContext:@"modify"];
5478 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5482 // We don't want to allow non-commercial packages to do custom things to the install button,
5483 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5484 - (void) customButtonClicked {
5486 [super customButtonClicked];
5488 [self _customButtonClicked];
5491 - (void) reloadButtonClicked {
5492 // Don't reload a commerical package by tapping the loading button,
5493 // but if it's not an Install button, we should forward it on.
5494 if (![package_ uninstalled])
5495 [self _customButtonClicked];
5498 - (void) applyLoadingTitle {
5499 // Don't show "Loading" as the title. Ever.
5502 - (UIBarButtonItem *) rightButton {
5507 - (id) initWithDatabase:(Database *)database {
5508 if ((self = [super init]) != nil) {
5509 database_ = database;
5510 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5511 [self loadURL:[NSURL URLWithString:CydiaURL(@"ui/package/")]];
5515 - (void) setPackage:(Package *)package {
5516 if (package_ != nil) {
5517 [package_ autorelease];
5526 [buttons_ removeAllObjects];
5528 if (package != nil) {
5531 package_ = [package retain];
5532 name_ = [[package id] retain];
5533 commercial_ = [package isCommercial];
5535 if ([package_ mode] != nil)
5536 [buttons_ addObject:UCLocalize("CLEAR")];
5537 if ([package_ source] == nil);
5538 else if ([package_ upgradableAndEssential:NO])
5539 [buttons_ addObject:UCLocalize("UPGRADE")];
5540 else if ([package_ uninstalled])
5541 [buttons_ addObject:UCLocalize("INSTALL")];
5543 [buttons_ addObject:UCLocalize("REINSTALL")];
5544 if (![package_ uninstalled])
5545 [buttons_ addObject:UCLocalize("REMOVE")];
5552 switch ([buttons_ count]) {
5553 case 0: title = nil; break;
5554 case 1: title = [buttons_ objectAtIndex:0]; break;
5555 default: title = UCLocalize("MODIFY"); break;
5558 button_ = [[UIBarButtonItem alloc]
5560 style:UIBarButtonItemStylePlain
5562 action:@selector(customButtonClicked)
5568 - (bool) isLoading {
5569 return commercial_ ? [super isLoading] : false;
5572 - (void) reloadData {
5573 [self setPackage:[database_ packageWithName:name_]];
5579 /* Package List Controller {{{ */
5580 @interface PackageListController : CYViewController <
5581 UITableViewDataSource,
5584 _transient Database *database_;
5586 NSMutableArray *packages_;
5587 NSMutableArray *sections_;
5589 NSMutableArray *index_;
5590 NSMutableDictionary *indices_;
5595 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5596 - (void) setDelegate:(id)delegate;
5597 - (void) resetCursor;
5601 @implementation PackageListController
5604 [packages_ release];
5605 [sections_ release];
5614 - (void) deselectWithAnimation:(BOOL)animated {
5615 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5618 - (void) viewDidAppear:(BOOL)animated {
5619 [super viewDidAppear:animated];
5620 [self deselectWithAnimation:animated];
5623 - (void) didSelectPackage:(Package *)package {
5624 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_] autorelease]);
5625 [view setPackage:package];
5626 [view setDelegate:delegate_];
5627 [[self navigationController] pushViewController:view animated:YES];
5630 #if TryIndexedCollation
5631 + (BOOL) hasIndexedCollation {
5632 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5636 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5637 NSInteger count([sections_ count]);
5638 return count == 0 ? 1 : count;
5641 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5642 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5644 return [[sections_ objectAtIndex:section] name];
5647 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5648 if ([sections_ count] == 0)
5650 return [[sections_ objectAtIndex:section] count];
5653 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5654 @synchronized (database_) {
5655 if ([database_ era] != era_)
5658 Section *section([sections_ objectAtIndex:[path section]]);
5659 NSInteger row([path row]);
5660 Package *package([packages_ objectAtIndex:([section row] + row)]);
5661 return [[package retain] autorelease];
5664 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5665 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5667 cell = [[[PackageCell alloc] init] autorelease];
5668 [cell setPackage:[self packageAtIndexPath:path]];
5672 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
5673 Package *package([self packageAtIndexPath:path]);
5674 package = [database_ packageWithName:[package id]];
5675 [self didSelectPackage:package];
5678 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5679 // XXX: is 20 the most optimal number here?
5680 return [packages_ count] > 20 ? index_ : nil;
5683 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5684 #if TryIndexedCollation
5685 if ([[self class] hasIndexedCollation]) {
5686 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5693 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
5694 if ((self = [super init]) != nil) {
5695 database_ = database;
5696 title_ = [title copy];
5697 [[self navigationItem] setTitle:title_];
5699 #if TryIndexedCollation
5700 if ([[self class] hasIndexedCollation])
5701 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
5704 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5706 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5708 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5709 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5711 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
5712 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5713 [list_ setRowHeight:73];
5714 [[self view] addSubview:list_];
5716 [list_ setDataSource:self];
5717 [list_ setDelegate:self];
5721 - (void) setDelegate:(id)delegate {
5722 delegate_ = delegate;
5725 - (bool) hasPackage:(Package *)package {
5729 - (void) reloadData {
5730 era_ = [database_ era];
5731 NSArray *packages = [database_ packages];
5733 [packages_ removeAllObjects];
5734 [sections_ removeAllObjects];
5736 _profile(PackageTable$reloadData$Filter)
5737 for (Package *package in packages)
5738 if ([self hasPackage:package])
5739 [packages_ addObject:package];
5742 [indices_ removeAllObjects];
5744 Section *section = nil;
5746 #if TryIndexedCollation
5747 if ([[self class] hasIndexedCollation]) {
5748 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
5749 NSArray *titles = [collation sectionIndexTitles];
5752 _profile(PackageTable$reloadData$Section)
5753 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5757 _profile(PackageTable$reloadData$Section$Package)
5758 package = [packages_ objectAtIndex:offset];
5759 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
5762 while (secidx < index) {
5765 _profile(PackageTable$reloadData$Section$Allocate)
5766 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
5769 _profile(PackageTable$reloadData$Section$Add)
5770 [sections_ addObject:section];
5774 [section addToCount];
5780 [index_ removeAllObjects];
5782 _profile(PackageTable$reloadData$Section)
5783 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5787 _profile(PackageTable$reloadData$Section$Package)
5788 package = [packages_ objectAtIndex:offset];
5789 index = [package index];
5792 if (section == nil || [section index] != index) {
5793 _profile(PackageTable$reloadData$Section$Allocate)
5794 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5797 [index_ addObject:[section name]];
5798 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5800 _profile(PackageTable$reloadData$Section$Add)
5801 [sections_ addObject:section];
5805 [section addToCount];
5810 _profile(PackageTable$reloadData$List)
5815 - (void) resetCursor {
5816 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5821 /* Filtered Package List Controller {{{ */
5822 @interface FilteredPackageListController : PackageListController {
5828 - (void) setObject:(id)object;
5829 - (void) setObject:(id)object forFilter:(SEL)filter;
5831 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5835 @implementation FilteredPackageListController
5843 - (void) setFilter:(SEL)filter {
5846 /* XXX: this is an unsafe optimization of doomy hell */
5847 Method method(class_getInstanceMethod([Package class], filter));
5848 _assert(method != NULL);
5849 imp_ = method_getImplementation(method);
5850 _assert(imp_ != NULL);
5853 - (void) setObject:(id)object {
5859 object_ = [object retain];
5862 - (void) setObject:(id)object forFilter:(SEL)filter {
5863 [self setFilter:filter];
5864 [self setObject:object];
5867 - (bool) hasPackage:(Package *)package {
5868 _profile(FilteredPackageTable$hasPackage)
5869 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5873 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5874 if ((self = [super initWithDatabase:database title:title]) != nil) {
5875 [self setFilter:filter];
5876 [self setObject:object];
5884 /* Home Controller {{{ */
5885 @interface HomeController : CYBrowserController {
5889 @implementation HomeController
5891 + (BOOL)shouldHideNavigationBar {
5895 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
5896 [super _setMoreHeaders:request];
5899 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
5900 if (UniqueID_ != nil)
5901 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5903 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
5906 - (void) aboutButtonClicked {
5907 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
5909 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
5910 [alert addButtonWithTitle:UCLocalize("CLOSE")];
5911 [alert setCancelButtonIndex:0];
5914 @"Copyright (C) 2008-2011\n"
5915 "Jay Freeman (saurik)\n"
5916 "saurik@saurik.com\n"
5917 "http://www.saurik.com/"
5923 - (void) viewWillAppear:(BOOL)animated {
5924 [super viewWillAppear:animated];
5926 if ([[self class] shouldHideNavigationBar])
5927 [[self navigationController] setNavigationBarHidden:YES animated:animated];
5930 - (void) viewWillDisappear:(BOOL)animated {
5931 [super viewWillDisappear:animated];
5933 if ([[self class] shouldHideNavigationBar])
5934 [[self navigationController] setNavigationBarHidden:NO animated:animated];
5938 if ((self = [super init]) != nil) {
5939 [self loadURL:[NSURL URLWithString:CydiaURL(@"ui/home/")]];
5941 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
5942 initWithTitle:UCLocalize("ABOUT")
5943 style:UIBarButtonItemStylePlain
5945 action:@selector(aboutButtonClicked)
5952 /* Manage Controller {{{ */
5953 @interface ManageController : CYBrowserController {
5956 - (void) queueStatusDidChange;
5959 @implementation ManageController
5962 if ((self = [super init]) != nil) {
5963 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
5965 [self loadURL:[NSURL URLWithString:CydiaURL(@"ui/manage/")]];
5967 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
5968 initWithTitle:UCLocalize("SETTINGS")
5969 style:UIBarButtonItemStylePlain
5971 action:@selector(settingsButtonClicked)
5974 [self queueStatusDidChange];
5978 - (void) settingsButtonClicked {
5979 [delegate_ showSettings];
5983 - (void) queueButtonClicked {
5987 - (void) applyLoadingTitle {
5988 // No "Loading" title.
5991 - (void) applyRightButton {
5996 - (void) queueStatusDidChange {
5998 if (!IsWildcat_ && Queuing_) {
5999 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6000 initWithTitle:UCLocalize("QUEUE")
6001 style:UIBarButtonItemStyleDone
6003 action:@selector(queueButtonClicked)
6006 [[self navigationItem] setRightBarButtonItem:nil];
6011 - (bool) isLoading {
6018 /* Refresh Bar {{{ */
6019 @interface RefreshBar : UINavigationBar {
6020 UIProgressIndicator *indicator_;
6021 UITextLabel *prompt_;
6022 UIProgressBar *progress_;
6023 UINavigationButton *cancel_;
6028 @implementation RefreshBar
6031 [indicator_ release];
6033 [progress_ release];
6038 - (void) positionViews {
6039 CGRect frame = [cancel_ frame];
6040 frame.size = [cancel_ sizeThatFits:frame.size];
6041 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6042 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6043 [cancel_ setFrame:frame];
6045 CGSize prgsize = {75, 100};
6047 [self frame].size.width - prgsize.width - 10,
6048 ([self frame].size.height - prgsize.height) / 2
6050 [progress_ setFrame:prgrect];
6052 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6053 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6054 CGRect indrect = {{indoffset, indoffset}, indsize};
6055 [indicator_ setFrame:indrect];
6057 CGSize prmsize = {215, indsize.height + 4};
6059 indoffset * 2 + indsize.width,
6060 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6062 [prompt_ setFrame:prmrect];
6065 - (void)setFrame:(CGRect)frame {
6066 [super setFrame:frame];
6068 [self positionViews];
6071 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6072 if ((self = [super initWithFrame:frame])) {
6073 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6075 [self setBarStyle:UIBarStyleBlack];
6077 UIBarStyle barstyle([self _barStyle:NO]);
6078 bool ugly(barstyle == UIBarStyleDefault);
6080 UIProgressIndicatorStyle style = ugly ?
6081 UIProgressIndicatorStyleMediumBrown :
6082 UIProgressIndicatorStyleMediumWhite;
6084 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6085 [indicator_ setStyle:style];
6086 [indicator_ startAnimation];
6087 [self addSubview:indicator_];
6089 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6090 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6091 [prompt_ setBackgroundColor:[UIColor clearColor]];
6092 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6093 [self addSubview:prompt_];
6095 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6096 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6097 [progress_ setStyle:0];
6098 [self addSubview:progress_];
6100 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6101 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6102 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6103 [cancel_ setBarStyle:barstyle];
6105 [self positionViews];
6110 [cancel_ removeFromSuperview];
6114 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6115 [progress_ setProgress:0];
6116 [self addSubview:cancel_];
6120 [cancel_ removeFromSuperview];
6123 - (void) setPrompt:(NSString *)prompt {
6124 [prompt_ setText:prompt];
6127 - (void) setProgress:(float)progress {
6128 [progress_ setProgress:progress];
6134 @class CYNavigationController;
6136 /* Cydia Tab Bar Controller {{{ */
6137 @interface CYTabBarController : UITabBarController <
6140 _transient Database *database_;
6141 RefreshBar *refreshbar_;
6145 // XXX: ok, "updatedelegate_"?...
6146 _transient NSObject<CydiaDelegate> *updatedelegate_;
6151 - (void) dropBar:(BOOL)animated;
6152 - (void) beginUpdate;
6153 - (void) raiseBar:(BOOL)animated;
6158 @implementation CYTabBarController
6160 - (void) reloadData {
6161 size_t count([[self viewControllers] count]);
6162 for (size_t i(0); i != count; ++i) {
6163 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6167 [(CYNavigationController *)[self transientViewController] reloadData];
6170 - (id) initWithDatabase:(Database *)database {
6171 if ((self = [super init]) != nil) {
6172 database_ = database;
6174 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6175 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6177 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6181 - (void) setUpdate:(NSDate *)date {
6185 - (void) beginUpdate {
6186 [refreshbar_ start];
6189 [updatedelegate_ retainNetworkActivityIndicator];
6193 detachNewThreadSelector:@selector(performUpdate)
6199 - (void) performUpdate { _pooled
6201 status.setDelegate(self);
6202 [database_ updateWithStatus:status];
6205 performSelectorOnMainThread:@selector(completeUpdate)
6211 - (void) stopUpdateWithSelector:(SEL)selector {
6213 [updatedelegate_ releaseNetworkActivityIndicator];
6215 [self raiseBar:YES];
6218 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6221 - (void) completeUpdate {
6224 [self stopUpdateWithSelector:@selector(reloadData)];
6227 - (void) cancelUpdate {
6228 [self stopUpdateWithSelector:@selector(updateData)];
6231 - (void) cancelPressed {
6232 [self cancelUpdate];
6239 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6240 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6243 - (void) startProgress {
6246 - (void) setProgressTitle:(NSString *)title {
6248 performSelectorOnMainThread:@selector(_setProgressTitle:)
6254 - (bool) isCancelling:(size_t)received {
6258 - (void) setProgressPercent:(float)percent {
6260 performSelectorOnMainThread:@selector(_setProgressPercent:)
6261 withObject:[NSNumber numberWithFloat:percent]
6266 - (void) addProgressOutput:(NSString *)output {
6268 performSelectorOnMainThread:@selector(_addProgressOutput:)
6274 - (void) _setProgressTitle:(NSString *)title {
6275 [refreshbar_ setPrompt:title];
6278 - (void) _setProgressPercent:(NSNumber *)percent {
6279 [refreshbar_ setProgress:[percent floatValue]];
6282 - (void) _addProgressOutput:(NSString *)output {
6285 - (void) setUpdateDelegate:(id)delegate {
6286 updatedelegate_ = delegate;
6289 - (CGFloat) statusBarHeight {
6290 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6291 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6293 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6297 - (UIView *) transitionView {
6298 if ([self respondsToSelector:@selector(_transitionView)])
6299 return [self _transitionView];
6301 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6304 - (void) dropBar:(BOOL)animated {
6309 UIView *transition([self transitionView]);
6310 [[self view] addSubview:refreshbar_];
6312 CGRect barframe([refreshbar_ frame]);
6314 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6315 barframe.origin.y = [self statusBarHeight];
6317 barframe.origin.y = 0;
6319 [refreshbar_ setFrame:barframe];
6322 [UIView beginAnimations:nil context:NULL];
6324 CGRect viewframe = [transition frame];
6325 viewframe.origin.y += barframe.size.height;
6326 viewframe.size.height -= barframe.size.height;
6327 [transition setFrame:viewframe];
6330 [UIView commitAnimations];
6332 // Ensure bar has the proper width for our view, it might have changed
6333 barframe.size.width = viewframe.size.width;
6334 [refreshbar_ setFrame:barframe];
6336 // XXX: fix Apple's layout bug
6337 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6340 - (void) raiseBar:(BOOL)animated {
6345 UIView *transition([self transitionView]);
6346 [refreshbar_ removeFromSuperview];
6348 CGRect barframe([refreshbar_ frame]);
6351 [UIView beginAnimations:nil context:NULL];
6353 CGRect viewframe = [transition frame];
6354 viewframe.origin.y -= barframe.size.height;
6355 viewframe.size.height += barframe.size.height;
6356 [transition setFrame:viewframe];
6359 [UIView commitAnimations];
6361 // XXX: fix Apple's layout bug
6362 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6366 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6367 // XXX: fix Apple's layout bug
6368 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6372 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6373 bool dropped(dropped_);
6378 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6383 // XXX: fix Apple's layout bug
6384 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6387 - (void) statusBarFrameChanged:(NSNotification *)notification {
6395 [refreshbar_ release];
6396 [[NSNotificationCenter defaultCenter] removeObserver:self];
6402 /* Cydia Navigation Controller {{{ */
6403 @interface CYNavigationController : UINavigationController {
6404 _transient Database *database_;
6405 _transient id<UINavigationControllerDelegate> delegate_;
6408 - (id) initWithDatabase:(Database *)database;
6409 - (void) reloadData;
6414 @implementation CYNavigationController
6420 - (void) reloadData {
6421 size_t count([[self viewControllers] count]);
6422 for (size_t i(0); i != count; ++i) {
6423 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6428 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6429 delegate_ = delegate;
6432 - (id) initWithDatabase:(Database *)database {
6433 if ((self = [super init]) != nil) {
6434 database_ = database;
6441 /* Cydia:// Protocol {{{ */
6442 @interface CydiaURLProtocol : NSURLProtocol {
6447 @implementation CydiaURLProtocol
6449 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6450 NSURL *url([request URL]);
6453 NSString *scheme([[url scheme] lowercaseString]);
6454 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6459 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6463 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6464 id<NSURLProtocolClient> client([self client]);
6466 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6468 NSData *data(UIImagePNGRepresentation(icon));
6470 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6471 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6472 [client URLProtocol:self didLoadData:data];
6473 [client URLProtocolDidFinishLoading:self];
6477 - (void) startLoading {
6478 id<NSURLProtocolClient> client([self client]);
6479 NSURLRequest *request([self request]);
6481 NSURL *url([request URL]);
6482 NSString *href([url absoluteString]);
6484 NSString *path([href substringFromIndex:8]);
6485 NSRange slash([path rangeOfString:@"/"]);
6488 if (slash.location == NSNotFound) {
6492 command = [path substringToIndex:slash.location];
6493 path = [path substringFromIndex:(slash.location + 1)];
6496 Database *database([Database sharedInstance]);
6498 if ([command isEqualToString:@"package-icon"]) {
6501 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6502 Package *package([database packageWithName:path]);
6505 UIImage *icon([package icon]);
6506 [self _returnPNGWithImage:icon forRequest:request];
6507 } else if ([command isEqualToString:@"source-icon"]) {
6510 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6511 NSString *source(Simplify(path));
6512 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6514 icon = [UIImage applicationImageNamed:@"unknown.png"];
6515 [self _returnPNGWithImage:icon forRequest:request];
6516 } else if ([command isEqualToString:@"uikit-image"]) {
6519 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6520 UIImage *icon(_UIImageWithName(path));
6521 [self _returnPNGWithImage:icon forRequest:request];
6522 } else if ([command isEqualToString:@"section-icon"]) {
6525 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6526 NSString *section(Simplify(path));
6527 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6529 icon = [UIImage applicationImageNamed:@"unknown.png"];
6530 [self _returnPNGWithImage:icon forRequest:request];
6532 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6536 - (void) stopLoading {
6542 /* Section Controller {{{ */
6543 @interface SectionController : FilteredPackageListController {
6546 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6550 @implementation SectionController
6552 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6556 title = UCLocalize("ALL_PACKAGES");
6557 } else if (![name isEqual:@""]) {
6558 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6560 title = UCLocalize("NO_SECTION");
6563 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6569 /* Sections Controller {{{ */
6570 @interface SectionsController : CYViewController <
6571 UITableViewDataSource,
6574 _transient Database *database_;
6575 NSMutableArray *sections_;
6576 NSMutableArray *filtered_;
6581 - (id) initWithDatabase:(Database *)database;
6582 - (void) reloadData;
6585 - (void) editButtonClicked;
6589 @implementation SectionsController
6592 [list_ setDataSource:nil];
6593 [list_ setDelegate:nil];
6595 [sections_ release];
6596 [filtered_ release];
6601 - (void) updateNavigationItem {
6602 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6603 if ([sections_ count] == 0) {
6604 [[self navigationItem] setRightBarButtonItem:nil];
6606 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6607 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6609 action:@selector(editButtonClicked)
6610 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6614 - (void) setEditing:(BOOL)editing {
6615 if ((editing_ = editing))
6618 [delegate_ updateData];
6620 [self updateNavigationItem];
6623 - (void) viewDidAppear:(BOOL)animated {
6624 [super viewDidAppear:animated];
6625 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6628 - (void) viewWillDisappear:(BOOL)animated {
6629 [super viewWillDisappear:animated];
6630 if (editing_) [self setEditing:NO];
6633 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6634 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6638 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6639 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6642 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6646 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6647 static NSString *reuseIdentifier = @"SectionCell";
6649 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6651 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6653 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6658 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6662 Section *section = [self sectionAtIndexPath:indexPath];
6664 SectionController *controller = [[[SectionController alloc]
6665 initWithDatabase:database_
6666 section:[section name]
6668 [controller setDelegate:delegate_];
6670 [[self navigationController] pushViewController:controller animated:YES];
6673 - (id) initWithDatabase:(Database *)database {
6674 if ((self = [super init]) != nil) {
6675 database_ = database;
6677 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6679 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6680 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6682 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6683 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6684 [list_ setRowHeight:45.0f];
6685 [[self view] addSubview:list_];
6687 [list_ setDataSource:self];
6688 [list_ setDelegate:self];
6694 - (void) reloadData {
6695 NSArray *packages = [database_ packages];
6697 [sections_ removeAllObjects];
6698 [filtered_ removeAllObjects];
6700 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6703 for (Package *package in packages) {
6704 NSString *name([package section]);
6705 NSString *key(name == nil ? @"" : name);
6709 _profile(SectionsView$reloadData$Section)
6710 section = [sections objectForKey:key];
6711 if (section == nil) {
6712 _profile(SectionsView$reloadData$Section$Allocate)
6713 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6714 [sections setObject:section forKey:key];
6719 [section addToCount];
6721 _profile(SectionsView$reloadData$Filter)
6722 if (![package valid] || ![package visible])
6730 [sections_ addObjectsFromArray:[sections allValues]];
6732 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6734 for (Section *section in sections_) {
6735 size_t count([section row]);
6739 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6740 [section setCount:count];
6741 [filtered_ addObject:section];
6744 [self updateNavigationItem];
6749 - (void) resetView {
6751 [self editButtonClicked];
6754 - (void)editButtonClicked {
6755 [self setEditing:!editing_];
6761 /* Changes Controller {{{ */
6762 @interface ChangesController : CYViewController <
6763 UITableViewDataSource,
6766 _transient Database *database_;
6768 CFMutableArrayRef packages_;
6769 NSMutableArray *sections_;
6772 BOOL hasSentFirstLoad_;
6775 - (id) initWithDatabase:(Database *)database;
6779 @implementation ChangesController
6782 [list_ setDelegate:nil];
6783 [list_ setDataSource:nil];
6785 CFRelease(packages_);
6787 [sections_ release];
6792 - (void) viewDidAppear:(BOOL)animated {
6793 [super viewDidAppear:animated];
6794 if (!hasSentFirstLoad_) {
6795 hasSentFirstLoad_ = YES;
6796 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6798 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6802 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6803 NSInteger count([sections_ count]);
6804 return count == 0 ? 1 : count;
6807 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6808 if ([sections_ count] == 0)
6810 return [[sections_ objectAtIndex:section] name];
6813 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6814 if ([sections_ count] == 0)
6816 return [[sections_ objectAtIndex:section] count];
6819 - (Package *) packageAtIndex:(NSUInteger)index {
6820 return (Package *) CFArrayGetValueAtIndex(packages_, index);
6823 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6824 @synchronized (database_) {
6825 if ([database_ era] != era_)
6828 NSUInteger sectionIndex([path section]);
6829 if (sectionIndex >= [sections_ count])
6831 Section *section([sections_ objectAtIndex:sectionIndex]);
6832 NSInteger row([path row]);
6833 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
6836 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6837 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6839 cell = [[[PackageCell alloc] init] autorelease];
6840 [cell setPackage:[self packageAtIndexPath:path]];
6844 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6845 Package *package([self packageAtIndexPath:path]);
6846 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_] autorelease]);
6847 [view setDelegate:delegate_];
6848 [view setPackage:package];
6849 [[self navigationController] pushViewController:view animated:YES];
6853 - (void) refreshButtonClicked {
6854 [delegate_ beginUpdate];
6855 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
6858 - (void) upgradeButtonClicked {
6859 [delegate_ distUpgrade];
6862 - (NSString *) title { return UCLocalize("CHANGES"); }
6864 - (id) initWithDatabase:(Database *)database {
6865 if ((self = [super init]) != nil) {
6866 database_ = database;
6867 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
6869 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
6870 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6872 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6873 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6874 [list_ setRowHeight:73];
6875 [[self view] addSubview:list_];
6877 [list_ setDataSource:self];
6878 [list_ setDelegate:self];
6882 - (void) _reloadPackages:(NSArray *)packages {
6883 CFRelease(packages_);
6884 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
6887 _profile(ChangesController$_reloadPackages$Filter)
6888 for (Package *package in packages)
6889 if ([package upgradableAndEssential:YES] || [package visible])
6890 CFArrayAppendValue(packages_, package);
6893 _profile(ChangesController$_reloadPackages$radixSort)
6894 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6899 - (void) reloadData {
6900 @synchronized (database_) {
6901 era_ = [database_ era];
6902 NSArray *packages = [database_ packages];
6904 [sections_ removeAllObjects];
6907 UIProgressHUD *hud([delegate_ addProgressHUD]);
6908 [hud setText:UCLocalize("LOADING")];
6909 //NSLog(@"HUD:%@::%@", delegate_, hud);
6910 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
6911 [delegate_ removeProgressHUD:hud];
6913 [self _reloadPackages:packages];
6916 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6917 Section *ignored = nil;
6918 Section *section = nil;
6922 bool unseens = false;
6924 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6926 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
6927 Package *package = [self packageAtIndex:offset];
6929 BOOL uae = [package upgradableAndEssential:YES];
6933 time_t seen([package seen]);
6935 if (section == nil || last != seen) {
6939 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
6942 _profile(ChangesController$reloadData$Allocate)
6943 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
6944 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6945 [sections_ addObject:section];
6949 [section addToCount];
6950 } else if ([package ignored]) {
6951 if (ignored == nil) {
6952 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
6954 [ignored addToCount];
6957 [upgradable addToCount];
6962 CFRelease(formatter);
6965 Section *last = [sections_ lastObject];
6966 size_t count = [last count];
6967 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
6968 [sections_ removeLastObject];
6971 if ([ignored count] != 0)
6972 [sections_ insertObject:ignored atIndex:0];
6974 [sections_ insertObject:upgradable atIndex:0];
6979 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6980 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
6981 style:UIBarButtonItemStylePlain
6983 action:@selector(upgradeButtonClicked)
6986 if (![delegate_ updating])
6987 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6988 initWithTitle:UCLocalize("REFRESH")
6989 style:UIBarButtonItemStylePlain
6991 action:@selector(refreshButtonClicked)
6999 /* Search Controller {{{ */
7000 @interface SearchController : FilteredPackageListController <
7003 UISearchBar *search_;
7006 - (id) initWithDatabase:(Database *)database;
7007 - (void) setSearchTerm:(NSString *)term;
7008 - (void) reloadData;
7012 @implementation SearchController
7019 - (void) setSearchTerm:(NSString *)searchTerm {
7020 [search_ setText:searchTerm];
7023 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7024 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7025 [search_ resignFirstResponder];
7029 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7030 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7034 - (id) initWithDatabase:(Database *)database {
7035 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7038 - (void)viewDidAppear:(BOOL)animated {
7039 [super viewDidAppear:animated];
7041 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7042 [search_ layoutSubviews];
7043 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7045 UITextField *textField;
7046 if ([search_ respondsToSelector:@selector(searchField)])
7047 textField = [search_ searchField];
7049 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7051 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7052 [search_ setDelegate:self];
7053 [textField setEnablesReturnKeyAutomatically:NO];
7054 [[self navigationItem] setTitleView:textField];
7058 - (void) _reloadData {
7061 - (void) reloadData {
7062 _profile(SearchController$reloadData)
7069 - (void) didSelectPackage:(Package *)package {
7070 [search_ resignFirstResponder];
7071 [super didSelectPackage:package];
7076 /* Package Settings Controller {{{ */
7077 @interface PackageSettingsController : CYViewController <
7078 UITableViewDataSource,
7081 _transient Database *database_;
7084 UITableView *table_;
7085 UISwitch *subscribedSwitch_;
7086 UISwitch *ignoredSwitch_;
7087 UITableViewCell *subscribedCell_;
7088 UITableViewCell *ignoredCell_;
7091 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7095 @implementation PackageSettingsController
7099 if (package_ != nil)
7102 [subscribedSwitch_ release];
7103 [ignoredSwitch_ release];
7104 [subscribedCell_ release];
7105 [ignoredCell_ release];
7110 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7111 if (package_ == nil)
7117 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7118 if (package_ == nil)
7124 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7125 return UCLocalize("CHANGE_PACKAGE_SETTINGS");
7128 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7129 return UCLocalize("SHOW_ALL_CHANGES_EX");
7132 - (void) onSubscribed:(id)control {
7133 bool value([control isOn]);
7134 if (package_ == nil)
7136 if ([package_ setSubscribed:value])
7137 [delegate_ updateData];
7140 - (void) onIgnored:(id)control {
7141 // TODO: set Held state - possibly call out to dpkg, etc.
7144 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7145 if (package_ == nil)
7148 switch ([indexPath row]) {
7149 case 0: return subscribedCell_;
7150 case 1: return ignoredCell_;
7158 - (NSString *) title { return UCLocalize("SETTINGS"); }
7160 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7161 if ((self = [super init])) {
7162 database_ = database;
7163 name_ = [package retain];
7165 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7167 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7168 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7169 [[self view] addSubview:table_];
7171 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7172 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7173 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7175 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7176 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7177 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7178 // Disable this switch, since it only reflects (not modifies) the ignored state.
7179 [ignoredSwitch_ setUserInteractionEnabled:NO];
7181 subscribedCell_ = [[UITableViewCell alloc] init];
7182 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7183 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7184 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7186 ignoredCell_ = [[UITableViewCell alloc] init];
7187 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7188 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7189 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7190 // FIXME: Ignored state is not saved.
7191 [ignoredCell_ setUserInteractionEnabled:NO];
7193 [table_ setDataSource:self];
7194 [table_ setDelegate:self];
7199 - (void) reloadData {
7200 if (package_ != nil)
7201 [package_ autorelease];
7202 package_ = [database_ packageWithName:name_];
7203 if (package_ != nil) {
7205 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7206 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7209 [table_ reloadData];
7214 /* Signature Controller {{{ */
7215 @interface SignatureController : CYBrowserController {
7216 _transient Database *database_;
7220 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7224 @implementation SignatureController
7231 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7233 [super webView:view didClearWindowObject:window forFrame:frame];
7236 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7237 if ((self = [super init]) != nil) {
7238 database_ = database;
7239 package_ = [package retain];
7244 - (void) reloadData {
7245 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7251 /* Installed Controller {{{ */
7252 @interface InstalledController : FilteredPackageListController {
7256 - (id) initWithDatabase:(Database *)database;
7258 - (void) updateRoleButton;
7259 - (void) queueStatusDidChange;
7263 @implementation InstalledController
7269 - (NSString *) title { return UCLocalize("INSTALLED"); }
7271 - (id) initWithDatabase:(Database *)database {
7272 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7273 [self updateRoleButton];
7274 [self queueStatusDidChange];
7279 - (void) queueButtonClicked {
7284 - (void) queueStatusDidChange {
7288 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7289 initWithTitle:UCLocalize("QUEUE")
7290 style:UIBarButtonItemStyleDone
7292 action:@selector(queueButtonClicked)
7295 [[self navigationItem] setLeftBarButtonItem:nil];
7301 - (void) updateRoleButton {
7302 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7303 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7304 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7305 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7307 action:@selector(roleButtonClicked)
7311 - (void) roleButtonClicked {
7312 [self setObject:[NSNumber numberWithBool:expert_]];
7316 [self updateRoleButton];
7322 /* Source Cell {{{ */
7323 @interface SourceCell : CYTableViewCell <
7331 - (void) setSource:(Source *)source;
7335 @implementation SourceCell
7337 - (void) clearSource {
7347 - (void) setSource:(Source *)source {
7351 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7353 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7354 icon_ = [icon_ retain];
7356 origin_ = [[source name] retain];
7357 label_ = [[source uri] retain];
7359 [content_ setNeedsDisplay];
7367 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7368 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7369 UIView *content([self contentView]);
7370 CGRect bounds([content bounds]);
7372 content_ = [[ContentView alloc] initWithFrame:bounds];
7373 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7374 [content_ setBackgroundColor:[UIColor whiteColor]];
7375 [content addSubview:content_];
7377 [content_ setDelegate:self];
7378 [content_ setOpaque:YES];
7382 - (NSString *) accessibilityLabel {
7386 - (void) drawContentRect:(CGRect)rect {
7387 bool highlighted(highlighted_);
7388 float width(rect.size.width);
7391 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7398 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7402 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7407 /* Source Controller {{{ */
7408 @interface SourceController : FilteredPackageListController {
7411 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7415 @implementation SourceController
7417 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7418 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7424 /* Sources Controller {{{ */
7425 @interface SourcesController : CYViewController <
7426 UITableViewDataSource,
7429 _transient Database *database_;
7431 NSMutableArray *sources_;
7435 UIProgressHUD *hud_;
7438 //NSURLConnection *installer_;
7439 NSURLConnection *trivial_;
7440 NSURLConnection *trivial_bz2_;
7441 NSURLConnection *trivial_gz_;
7442 //NSURLConnection *automatic_;
7447 - (id) initWithDatabase:(Database *)database;
7449 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7453 @implementation SourcesController
7455 - (void) _releaseConnection:(NSURLConnection *)connection {
7456 if (connection != nil) {
7457 [connection cancel];
7458 //[connection setDelegate:nil];
7459 [connection release];
7471 //[self _releaseConnection:installer_];
7472 [self _releaseConnection:trivial_];
7473 [self _releaseConnection:trivial_gz_];
7474 [self _releaseConnection:trivial_bz2_];
7475 //[self _releaseConnection:automatic_];
7482 - (void) viewDidAppear:(BOOL)animated {
7483 [super viewDidAppear:animated];
7484 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7487 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7488 return offset_ == 0 ? 1 : 2;
7491 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7492 switch (section + (offset_ == 0 ? 1 : 0)) {
7493 case 0: return UCLocalize("ENTERED_BY_USER");
7494 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7500 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7501 int count = [sources_ count];
7503 case 0: return (offset_ == 0 ? count : offset_);
7504 case 1: return count - offset_;
7510 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7512 switch (indexPath.section) {
7513 case 0: idx = indexPath.row; break;
7514 case 1: idx = indexPath.row + offset_; break;
7518 return [sources_ objectAtIndex:idx];
7521 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7522 static NSString *cellIdentifier = @"SourceCell";
7524 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7525 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7526 [cell setSource:[self sourceAtIndexPath:indexPath]];
7527 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7532 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7533 Source *source = [self sourceAtIndexPath:indexPath];
7535 SourceController *controller = [[[SourceController alloc]
7536 initWithDatabase:database_
7540 [controller setDelegate:delegate_];
7542 [[self navigationController] pushViewController:controller animated:YES];
7545 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7546 Source *source = [self sourceAtIndexPath:indexPath];
7547 return [source record] != nil;
7550 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7551 Source *source = [self sourceAtIndexPath:indexPath];
7552 [Sources_ removeObjectForKey:[source key]];
7553 [delegate_ syncData];
7557 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
7560 @"./", @"Distribution",
7561 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
7563 [delegate_ syncData];
7566 - (NSString *) getWarning {
7567 NSString *href(href_);
7568 NSRange colon([href rangeOfString:@"://"]);
7569 if (colon.location != NSNotFound)
7570 href = [href substringFromIndex:(colon.location + 3)];
7571 href = [href stringByAddingPercentEscapes];
7572 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7573 href = [href stringByCachingURLWithCurrentCDN];
7575 NSURL *url([NSURL URLWithString:href]);
7577 NSStringEncoding encoding;
7578 NSError *error(nil);
7580 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7581 return [warning length] == 0 ? nil : warning;
7585 - (void) _endConnection:(NSURLConnection *)connection {
7586 // XXX: the memory management in this method is horribly awkward
7588 NSURLConnection **field = NULL;
7589 if (connection == trivial_)
7591 else if (connection == trivial_bz2_)
7592 field = &trivial_bz2_;
7593 else if (connection == trivial_gz_)
7594 field = &trivial_gz_;
7595 _assert(field != NULL);
7596 [connection release];
7601 trivial_bz2_ == nil &&
7607 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
7610 UIAlertView *alert = [[[UIAlertView alloc]
7611 initWithTitle:UCLocalize("SOURCE_WARNING")
7614 cancelButtonTitle:UCLocalize("CANCEL")
7615 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
7618 [alert setContext:@"warning"];
7619 [alert setNumberOfRows:1];
7623 } else if (error_ != nil) {
7624 UIAlertView *alert = [[[UIAlertView alloc]
7625 initWithTitle:UCLocalize("VERIFICATION_ERROR")
7626 message:[error_ localizedDescription]
7628 cancelButtonTitle:UCLocalize("OK")
7629 otherButtonTitles:nil
7632 [alert setContext:@"urlerror"];
7635 UIAlertView *alert = [[[UIAlertView alloc]
7636 initWithTitle:UCLocalize("NOT_REPOSITORY")
7637 message:UCLocalize("NOT_REPOSITORY_EX")
7639 cancelButtonTitle:UCLocalize("OK")
7640 otherButtonTitles:nil
7643 [alert setContext:@"trivial"];
7647 [delegate_ setStatusBarShowsProgress:NO];
7648 [delegate_ removeProgressHUD:hud_];
7658 if (error_ != nil) {
7665 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
7666 switch ([response statusCode]) {
7672 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
7673 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
7675 error_ = [error retain];
7676 [self _endConnection:connection];
7679 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
7680 [self _endConnection:connection];
7683 - (NSString *) title { return UCLocalize("SOURCES"); }
7685 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
7686 NSMutableURLRequest *request = [NSMutableURLRequest
7687 requestWithURL:[NSURL URLWithString:href]
7688 cachePolicy:NSURLRequestUseProtocolCachePolicy
7689 timeoutInterval:120.0
7692 [request setHTTPMethod:method];
7694 if (Machine_ != NULL)
7695 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
7696 if (UniqueID_ != nil)
7697 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
7699 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
7701 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
7704 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7705 NSString *context([alert context]);
7707 if ([context isEqualToString:@"source"]) {
7710 NSString *href = [[alert textField] text];
7712 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
7714 if (![href hasSuffix:@"/"])
7715 href_ = [href stringByAppendingString:@"/"];
7718 href_ = [href_ retain];
7720 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
7721 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
7722 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
7723 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
7727 // XXX: this is stupid
7728 hud_ = [[delegate_ addProgressHUD] retain];
7729 [hud_ setText:UCLocalize("VERIFYING_URL")];
7738 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7739 } else if ([context isEqualToString:@"trivial"])
7740 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7741 else if ([context isEqualToString:@"urlerror"])
7742 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7743 else if ([context isEqualToString:@"warning"]) {
7758 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7762 - (id) initWithDatabase:(Database *)database {
7763 if ((self = [super init]) != nil) {
7764 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
7765 [self updateButtonsForEditingStatus:NO animated:NO];
7767 database_ = database;
7768 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
7770 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7771 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7772 [list_ setRowHeight:56];
7773 [[self view] addSubview:list_];
7775 [list_ setDataSource:self];
7776 [list_ setDelegate:self];
7782 - (void) reloadData {
7784 if (!list.ReadMainList())
7787 [sources_ removeAllObjects];
7788 [sources_ addObjectsFromArray:[database_ sources]];
7790 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
7793 int count([sources_ count]);
7795 for (int i = 0; i != count; i++) {
7796 if ([[sources_ objectAtIndex:i] record] == nil)
7801 [list_ setEditing:NO];
7802 [self updateButtonsForEditingStatus:NO animated:NO];
7806 - (void) showAddSourcePrompt {
7807 UIAlertView *alert = [[[UIAlertView alloc]
7808 initWithTitle:UCLocalize("ENTER_APT_URL")
7811 cancelButtonTitle:UCLocalize("CANCEL")
7812 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
7815 [alert setContext:@"source"];
7816 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
7818 [alert setNumberOfRows:1];
7819 [alert addTextFieldWithValue:@"http://" label:@""];
7821 UITextInputTraits *traits = [[alert textField] textInputTraits];
7822 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
7823 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
7824 [traits setKeyboardType:UIKeyboardTypeURL];
7825 // XXX: UIReturnKeyDone
7826 [traits setReturnKeyType:UIReturnKeyNext];
7831 - (void) addButtonClicked {
7832 [self showAddSourcePrompt];
7835 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
7836 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
7837 initWithTitle:UCLocalize("ADD")
7838 style:UIBarButtonItemStylePlain
7840 action:@selector(addButtonClicked)
7841 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
7843 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7844 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
7845 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7847 action:@selector(editButtonClicked)
7848 ] autorelease] animated:animated];
7850 if (IsWildcat_ && !editing)
7851 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7852 initWithTitle:UCLocalize("SETTINGS")
7853 style:UIBarButtonItemStylePlain
7855 action:@selector(settingsButtonClicked)
7859 - (void) settingsButtonClicked {
7860 [delegate_ showSettings];
7863 - (void) editButtonClicked {
7864 [list_ setEditing:![list_ isEditing] animated:YES];
7866 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
7872 /* Settings Controller {{{ */
7873 @interface SettingsController : CYViewController <
7874 UITableViewDataSource,
7877 _transient Database *database_;
7878 // XXX: ok, "roledelegate_"?...
7879 _transient id roledelegate_;
7880 UITableView *table_;
7881 UISegmentedControl *segment_;
7885 - (void) showDoneButton;
7886 - (void) resizeSegmentedControl;
7890 @implementation SettingsController
7894 [container_ release];
7899 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7900 if ((self = [super init])) {
7901 database_ = database;
7902 roledelegate_ = delegate;
7904 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7906 NSArray *items = [NSArray arrayWithObjects:
7908 UCLocalize("HACKER"),
7909 UCLocalize("DEVELOPER"),
7911 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7912 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7913 [container_ addSubview:segment_];
7916 if ([Role_ isEqualToString:@"User"]) index = 0;
7917 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7918 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7920 [segment_ setSelectedSegmentIndex:index];
7921 [self showDoneButton];
7924 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7925 [self resizeSegmentedControl];
7927 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7928 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7929 [table_ setDelegate:self];
7930 [table_ setDataSource:self];
7931 [[self view] addSubview:table_];
7932 [table_ reloadData];
7936 - (void) resizeSegmentedControl {
7937 CGFloat width = [[self view] frame].size.width;
7938 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7941 - (void) viewWillAppear:(BOOL)animated {
7942 [super viewWillAppear:animated];
7944 [self resizeSegmentedControl];
7947 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7948 [self resizeSegmentedControl];
7951 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7952 [self resizeSegmentedControl];
7956 NSString *role(nil);
7958 switch ([segment_ selectedSegmentIndex]) {
7959 case 0: role = @"User"; break;
7960 case 1: role = @"Hacker"; break;
7961 case 2: role = @"Developer"; break;
7966 if (![role isEqualToString:Role_]) {
7967 bool rolling(Role_ == nil);
7970 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7974 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7978 [roledelegate_ loadData];
7980 [roledelegate_ updateData];
7984 - (void) segmentChanged:(UISegmentedControl *)control {
7985 [self showDoneButton];
7988 - (void) saveAndClose {
7991 [[self navigationItem] setRightBarButtonItem:nil];
7992 [[self navigationController] dismissModalViewControllerAnimated:YES];
7995 - (void) doneButtonClicked {
7996 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7997 [spinner startAnimating];
7998 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7999 [[self navigationItem] setRightBarButtonItem:spinItem];
8001 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8004 - (void) showDoneButton {
8005 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8006 initWithTitle:UCLocalize("DONE")
8007 style:UIBarButtonItemStyleDone
8009 action:@selector(doneButtonClicked)
8010 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8013 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8014 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8018 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8022 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8023 return nil; // This method is required by the protocol.
8026 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8028 return UCLocalize("ROLE_EX");
8030 return [NSString stringWithFormat:
8031 @"%@: %@\n%@: %@\n%@: %@",
8032 UCLocalize("USER"), UCLocalize("USER_EX"),
8033 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8034 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8039 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8040 return section == 3 ? 44.0f : 0;
8043 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8044 return section == 3 ? container_ : nil;
8049 /* Stash Controller {{{ */
8050 @interface StashController : CYViewController {
8051 // XXX: just delete these things
8052 _transient UIActivityIndicatorView *spinner_;
8053 _transient UILabel *status_;
8054 _transient UILabel *caption_;
8058 @implementation StashController
8060 if ((self = [super init])) {
8061 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8063 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8064 CGRect spinrect = [spinner_ frame];
8065 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8066 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8067 [spinner_ setFrame:spinrect];
8068 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8069 [[self view] addSubview:spinner_];
8070 [spinner_ startAnimating];
8073 captrect.size.width = [[self view] frame].size.width;
8074 captrect.size.height = 40.0f;
8075 captrect.origin.x = 0;
8076 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8077 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8078 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8079 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8080 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8081 [caption_ setTextColor:[UIColor whiteColor]];
8082 [caption_ setBackgroundColor:[UIColor clearColor]];
8083 [caption_ setShadowColor:[UIColor blackColor]];
8084 [caption_ setTextAlignment:UITextAlignmentCenter];
8085 [[self view] addSubview:caption_];
8088 statusrect.size.width = [[self view] frame].size.width;
8089 statusrect.size.height = 30.0f;
8090 statusrect.origin.x = 0;
8091 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8092 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8093 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8094 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8095 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8096 [status_ setTextColor:[UIColor whiteColor]];
8097 [status_ setBackgroundColor:[UIColor clearColor]];
8098 [status_ setShadowColor:[UIColor blackColor]];
8099 [status_ setTextAlignment:UITextAlignmentCenter];
8100 [[self view] addSubview:status_];
8107 @interface Cydia : UIApplication <
8108 ConfirmationControllerDelegate,
8109 ProgressControllerDelegate,
8111 UINavigationControllerDelegate,
8112 UITabBarControllerDelegate
8114 // XXX: evaluate all fields for _transient
8117 CYTabBarController *tabbar_;
8119 NSMutableArray *essential_;
8120 NSMutableArray *broken_;
8122 Database *database_;
8129 StashController *stash_;
8138 @implementation Cydia
8140 - (void) beginUpdate {
8141 [tabbar_ beginUpdate];
8145 return [tabbar_ updating];
8149 if ([broken_ count] != 0) {
8150 int count = [broken_ count];
8152 UIAlertView *alert = [[[UIAlertView alloc]
8153 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8154 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8156 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8157 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8160 [alert setContext:@"fixhalf"];
8162 } else if (!Ignored_ && [essential_ count] != 0) {
8163 int count = [essential_ count];
8165 UIAlertView *alert = [[[UIAlertView alloc]
8166 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8167 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8169 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8170 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8173 [alert setContext:@"upgrade"];
8178 - (void) _saveConfig {
8184 NSString *error(nil);
8186 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8188 NSError *error(nil);
8189 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8190 NSLog(@"failure to save metadata data: %@", error);
8195 NSLog(@"failure to serialize metadata: %@", error);
8200 // Navigation controller for the queuing badge.
8201 - (CYNavigationController *) queueNavigationController {
8202 NSArray *controllers = [tabbar_ viewControllers];
8203 return [controllers objectAtIndex:3];
8206 - (void) _updateData {
8209 [tabbar_ reloadData];
8211 CYNavigationController *navigation = [self queueNavigationController];
8213 id queuedelegate = nil;
8214 if ([[navigation viewControllers] count] > 0)
8215 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8217 [queuedelegate queueStatusDidChange];
8218 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8221 - (void) _refreshIfPossible {
8222 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8224 bool recently = false;
8225 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8226 if (update != nil) {
8227 NSTimeInterval interval([update timeIntervalSinceNow]);
8228 if (interval <= 0 && interval > -(15*60))
8232 // Don't automatic refresh if:
8233 // - We already refreshed recently.
8234 // - We already auto-refreshed this launch.
8235 // - Auto-refresh is disabled.
8236 if (recently || loaded_ || ManualRefresh) {
8237 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8239 // If we are cancelling due to ManualRefresh or a recent refresh
8240 // we need to make sure it knows it's already loaded.
8244 // We are going to load, so remember that.
8248 SCNetworkReachabilityFlags flags; {
8249 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8250 SCNetworkReachabilityGetFlags(reachability, &flags);
8251 CFRelease(reachability);
8254 // XXX: this elaborate mess is what Apple is using to determine this? :(
8255 // XXX: do we care if the user has to intervene? maybe that's ok?
8257 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8258 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8259 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8260 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8261 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8262 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8266 // If we can reach the server, auto-refresh!
8268 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8273 - (void) refreshIfPossible {
8274 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8277 - (void) _reloadData {
8278 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8279 [hud setText:UCLocalize("RELOADING_DATA")];
8281 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8284 [self removeProgressHUD:hud];
8288 [essential_ removeAllObjects];
8289 [broken_ removeAllObjects];
8291 NSArray *packages([database_ packages]);
8292 for (Package *package in packages) {
8294 [broken_ addObject:package];
8295 if ([package upgradableAndEssential:NO]) {
8296 if ([package essential])
8297 [essential_ addObject:package];
8302 NSLog(@"changes:#%u", changes);
8304 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8307 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8308 [changesItem setBadgeValue:badge];
8309 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8310 [self setApplicationIconBadgeNumber:changes];
8313 [changesItem setBadgeValue:nil];
8314 [changesItem setAnimatedBadge:NO];
8315 [self setApplicationIconBadgeNumber:0];
8320 [self refreshIfPossible];
8323 - (void) updateData {
8332 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8333 _assert(file != NULL);
8335 for (NSString *key in [Sources_ allKeys]) {
8336 NSDictionary *source([Sources_ objectForKey:key]);
8338 fprintf(file, "%s %s %s\n",
8339 [[source objectForKey:@"Type"] UTF8String],
8340 [[source objectForKey:@"URI"] UTF8String],
8341 [[source objectForKey:@"Distribution"] UTF8String]
8349 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8350 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8352 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8353 [tabbar_ presentModalViewController:navigation animated:YES];
8356 detachNewThreadSelector:@selector(update_)
8359 title:UCLocalize("UPDATING_SOURCES")
8363 - (void) reloadData {
8364 @synchronized (self) {
8370 pkgProblemResolver *resolver = [database_ resolver];
8372 resolver->InstallProtect();
8373 if (!resolver->Resolve(true))
8378 if (![database_ prepare])
8381 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8382 [page setDelegate:self];
8383 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8384 [confirm_ setDelegate:self];
8387 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8388 [tabbar_ presentModalViewController:confirm_ animated:YES];
8394 @synchronized (self) {
8399 - (void) clearPackage:(Package *)package {
8400 @synchronized (self) {
8407 - (void) installPackages:(NSArray *)packages {
8408 @synchronized (self) {
8409 for (Package *package in packages)
8416 - (void) installPackage:(Package *)package {
8417 @synchronized (self) {
8424 - (void) removePackage:(Package *)package {
8425 @synchronized (self) {
8432 - (void) distUpgrade {
8433 @synchronized (self) {
8434 if (![database_ upgrade])
8441 @synchronized (self) {
8446 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8449 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8451 if (navigation != nil) {
8452 [navigation pushViewController:progress animated:YES];
8454 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8456 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8457 [tabbar_ presentModalViewController:navigation animated:YES];
8461 detachNewThreadSelector:@selector(perform)
8464 title:UCLocalize("RUNNING")
8470 - (void) progressControllerIsComplete:(ProgressController *)progress {
8475 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8476 CYNavigationController *controller = (CYNavigationController *) viewController;
8478 if ([[controller viewControllers] count] == 0) {
8479 int index = [[tabbar_ viewControllers] indexOfObjectIdenticalTo:controller];
8480 CYViewController *root = nil;
8483 root = [[[HomeController alloc] init] autorelease];
8484 else if (index == 1)
8485 root = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
8486 else if (index == 2)
8487 root = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
8491 root = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8492 else if (index == 4)
8493 root = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8494 else if (index == 5)
8495 root = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8498 root = [[[ManageController alloc] init] autorelease];
8499 else if (index == 4)
8500 root = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8503 [root setDelegate:self];
8506 [controller setViewControllers:[NSArray arrayWithObject:root]];
8510 - (void) showSettings {
8511 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
8512 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8514 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8515 [tabbar_ presentModalViewController:nav animated:YES];
8518 - (void) retainNetworkActivityIndicator {
8519 if (activity_++ == 0)
8520 [self setNetworkActivityIndicatorVisible:YES];
8523 - (void) releaseNetworkActivityIndicator {
8524 if (--activity_ == 0)
8525 [self setNetworkActivityIndicatorVisible:NO];
8528 - (void) cancelAndClear:(bool)clear {
8529 @synchronized (self) {
8541 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8542 NSString *context([alert context]);
8544 if ([context isEqualToString:@"fixhalf"]) {
8545 if (button == [alert firstOtherButtonIndex]) {
8546 @synchronized (self) {
8547 for (Package *broken in broken_) {
8550 NSString *id = [broken id];
8551 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8552 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8553 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8554 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8560 } else if (button == [alert cancelButtonIndex]) {
8561 [broken_ removeAllObjects];
8565 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8566 } else if ([context isEqualToString:@"upgrade"]) {
8567 if (button == [alert firstOtherButtonIndex]) {
8568 @synchronized (self) {
8569 for (Package *essential in essential_)
8570 [essential install];
8575 } else if (button == [alert firstOtherButtonIndex] + 1) {
8577 } else if (button == [alert cancelButtonIndex]) {
8581 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8585 - (void) system:(NSString *)command { _pooled
8587 system([command UTF8String]);
8591 - (void) applicationWillSuspend {
8593 [super applicationWillSuspend];
8596 - (BOOL) isSafeToSuspend {
8597 // Use external process status API internally.
8598 // This is probably a really bad idea.
8599 // XXX: what is the point of this? does this solve anything at all?
8600 uint64_t status = 0;
8602 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8603 notify_get_state(notify_token, &status);
8604 notify_cancel(notify_token);
8607 return locked_ == 0 && status == 0;
8610 - (void) applicationSuspend:(__GSEvent *)event {
8611 if ([self isSafeToSuspend])
8612 [super applicationSuspend:event];
8615 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8616 if ([self isSafeToSuspend])
8617 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8620 - (void) _setSuspended:(BOOL)value {
8621 if ([self isSafeToSuspend])
8622 [super _setSuspended:value];
8625 - (UIProgressHUD *) addProgressHUD {
8626 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8627 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8629 [window_ setUserInteractionEnabled:NO];
8632 UIViewController *target = tabbar_;
8633 while ([target modalViewController] != nil) target = [target modalViewController];
8634 [[target view] addSubview:hud];
8640 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8642 [hud removeFromSuperview];
8643 [window_ setUserInteractionEnabled:YES];
8647 - (CYViewController *) pageForPackage:(NSString *)name {
8648 if (Package *package = [database_ packageWithName:name]) {
8649 CYPackageController *view = [[[CYPackageController alloc] initWithDatabase:database_] autorelease];
8650 [view setPackage:package];
8653 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8654 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8655 CYBrowserController *browser = [[[CYBrowserController alloc] init] autorelease];
8656 [browser loadURL:url];
8661 - (CYViewController *) pageForURL:(NSURL *)url {
8662 NSString *scheme([[url scheme] lowercaseString]);
8663 if ([[url absoluteString] length] <= [scheme length] + 3)
8665 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
8666 NSArray *components([path pathComponents]);
8668 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
8669 return [self pageForPackage:[components objectAtIndex:1]];
8671 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
8674 NSString *base([components objectAtIndex:0]);
8676 CYViewController *controller = nil;
8678 if ([base isEqualToString:@"url"]) {
8679 // This kind of URL can contain slashes in the argument, so we can't parse them below.
8680 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
8681 controller = [[[CYBrowserController alloc] init] autorelease];
8682 [(CYBrowserController *)controller loadURL:[NSURL URLWithString:destination]];
8683 } else if ([components count] == 1) {
8684 if ([base isEqualToString:@"sources"]) {
8685 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8688 if ([base isEqualToString:@"home"]) {
8689 controller = [[[HomeController alloc] init] autorelease];
8692 if ([base isEqualToString:@"sections"]) {
8693 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
8696 if ([base isEqualToString:@"search"]) {
8697 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8700 if ([base isEqualToString:@"changes"]) {
8701 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
8704 if ([base isEqualToString:@"installed"]) {
8705 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8707 } else if ([components count] == 2) {
8708 NSString *argument = [components objectAtIndex:1];
8710 if ([base isEqualToString:@"package"]) {
8711 controller = [self pageForPackage:argument];
8714 if ([base isEqualToString:@"search"]) {
8715 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8716 [(SearchController *)controller setSearchTerm:argument];
8719 if ([base isEqualToString:@"sections"]) {
8720 if ([argument isEqualToString:@"all"])
8722 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
8725 if ([base isEqualToString:@"sources"]) {
8726 if ([argument isEqualToString:@"add"]) {
8727 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8728 [(SourcesController *)controller showAddSourcePrompt];
8730 NSArray *sources = [database_ sources];
8731 for (Source *source in sources) {
8732 if ([[source name] caseInsensitiveCompare:argument] == NSOrderedSame) {
8733 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
8740 if ([base isEqualToString:@"launch"]) {
8741 [self launchApplicationWithIdentifier:argument suspended:NO];
8744 } else if ([components count] == 3) {
8745 NSString *arg1 = [components objectAtIndex:1];
8746 NSString *arg2 = [components objectAtIndex:2];
8748 if ([base isEqualToString:@"package"]) {
8749 if ([arg2 isEqualToString:@"settings"]) {
8750 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
8751 } else if ([arg2 isEqualToString:@"signature"]) {
8752 controller = [[[SignatureController alloc] initWithDatabase:database_ package:arg1] autorelease];
8753 } else if ([arg2 isEqualToString:@"files"]) {
8754 if (Package *package = [database_ packageWithName:arg1]) {
8755 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8756 [(FileTable *)controller setPackage:package];
8762 [controller setDelegate:self];
8766 - (BOOL) openCydiaURL:(NSURL *)url {
8767 CYViewController *page([self pageForURL:url]);
8770 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
8771 [nav setViewControllers:[NSArray arrayWithObject:page]];
8772 [tabbar_ setTransientViewController:nav];
8778 - (void) applicationOpenURL:(NSURL *)url {
8779 [super applicationOpenURL:url];
8781 if (!loaded_) starturl_ = [url retain];
8782 else [self openCydiaURL:url];
8785 - (void) applicationWillResignActive:(UIApplication *)application {
8786 // Stop refreshing if you get a phone call or lock the device.
8787 if ([tabbar_ updating])
8788 [tabbar_ cancelUpdate];
8790 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8791 [super applicationWillResignActive:application];
8794 - (void) addStashController {
8796 stash_ = [[StashController alloc] init];
8797 [window_ addSubview:[stash_ view]];
8800 - (void) removeStashController {
8801 [[stash_ view] removeFromSuperview];
8807 [self setIdleTimerDisabled:YES];
8809 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8810 [self setStatusBarShowsProgress:YES];
8811 UpdateExternalStatus(1);
8813 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8815 UpdateExternalStatus(0);
8816 [self setStatusBarShowsProgress:NO];
8818 [self removeStashController];
8820 if (ExecFork() == 0) {
8821 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8822 perror("launchctl stop");
8826 - (void) setupViewControllers {
8827 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8828 [tabbar_ setDelegate:self];
8830 NSMutableArray *items([NSMutableArray arrayWithObjects:
8831 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
8832 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
8833 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
8834 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
8838 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
8839 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
8841 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
8844 NSMutableArray *controllers([NSMutableArray array]);
8845 for (UITabBarItem *item in items) {
8846 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8847 [controller setTabBarItem:item];
8848 [controllers addObject:controller];
8850 [tabbar_ setViewControllers:controllers];
8852 [tabbar_ setUpdateDelegate:self];
8855 - (CYEmulatedLoadingController *)showEmulatedLoadingControllerInView:(UIView *)view {
8856 static CYEmulatedLoadingController *fake = [[CYEmulatedLoadingController alloc] init];
8858 [view addSubview:[fake view]];
8860 [[fake view] removeFromSuperview];
8866 - (void) applicationDidFinishLaunching:(id)unused {
8870 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
8871 [self setApplicationSupportsShakeToEdit:NO];
8873 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
8874 initWithMemoryCapacity:524288
8875 diskCapacity:10485760
8876 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
8879 [CYBrowserController _initialize];
8881 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8883 Font12_ = [[UIFont systemFontOfSize:12] retain];
8884 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8885 Font14_ = [[UIFont systemFontOfSize:14] retain];
8886 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8887 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8889 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8890 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8892 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
8893 [window_ orderFront:self];
8894 [window_ makeKey:self];
8895 [window_ setHidden:NO];
8898 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8899 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8900 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8901 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8902 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8903 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8904 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8905 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8906 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8909 [self addStashController];
8910 // XXX: this would be much cleaner as a yieldToSelector:
8911 // that way the removeStashController could happen right here inline
8912 // we also could no longer require the useless stash_ field anymore
8913 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8917 database_ = [Database sharedInstance];
8919 [window_ setUserInteractionEnabled:NO];
8920 [self setupViewControllers];
8921 [self showEmulatedLoadingControllerInView:window_];
8923 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8930 [window_ setUserInteractionEnabled:YES];
8932 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
8933 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8935 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8936 [[self showEmulatedLoadingControllerInView:window_] presentModalViewController:nav animated:YES];
8940 if ([[self showEmulatedLoadingControllerInView:window_] modalViewController] != nil)
8941 [[self showEmulatedLoadingControllerInView:window_] dismissModalViewControllerAnimated:YES];
8942 [window_ setUserInteractionEnabled:NO];
8948 [window_ addSubview:[tabbar_ view]];
8949 [self showEmulatedLoadingControllerInView:nil];
8950 [window_ setUserInteractionEnabled:YES];
8952 // Show the home page.
8953 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:0];
8954 [navigation setViewControllers:[NSArray arrayWithObject:[self pageForURL:[NSURL URLWithString:@"cydia://home"]]]];
8956 // (Try to) show the startup URL.
8957 if (starturl_ != nil) {
8958 [self openCydiaURL:starturl_];
8959 [starturl_ release];
8964 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8965 if (item != nil && IsWildcat_) {
8966 [sheet showFromBarButtonItem:item animated:YES];
8968 [sheet showInView:window_];
8975 id Alloc_(id self, SEL selector) {
8976 id object = alloc_(self, selector);
8977 lprintf("[%s]A-%p\n", self->isa->name, object);
8982 id Dealloc_(id self, SEL selector) {
8983 id object = dealloc_(self, selector);
8984 lprintf("[%s]D-%p\n", self->isa->name, object);
8988 Class $WebDefaultUIKitDelegate;
8990 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8991 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8992 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8993 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8996 static NSNumber *shouldPlayKeyboardSounds;
9000 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9002 case 1104: // Keyboard Button Clicked
9003 case 1105: // Keyboard Delete Repeated
9004 if (shouldPlayKeyboardSounds == nil) {
9005 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9006 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9009 if (![shouldPlayKeyboardSounds boolValue])
9013 _UIHardware$_playSystemSound$(self, _cmd, sound);
9017 Class $UIApplication;
9019 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9020 static BOOL initialized = NO;
9021 static BOOL started = NO;
9023 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9024 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9026 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9027 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9028 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9029 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9031 if (initialized && !enabled) {
9033 [bundle performSelector:@selector(_accessibilityStopServer)];
9034 } else if (enabled) {
9038 [bundle performSelector:@selector(_accessibilityStartServer)];
9044 int main(int argc, char *argv[]) { _pooled
9047 if (Class $UIDevice = objc_getClass("UIDevice")) {
9048 UIDevice *device([$UIDevice currentDevice]);
9049 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9053 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9055 /* Library Hacks {{{ */
9056 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9058 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9059 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9060 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9061 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9062 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9065 $UIHardware = objc_getClass("UIHardware");
9066 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9067 if (UIHardware$_playSystemSound$ != NULL) {
9068 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9069 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9072 $UIApplication = objc_getClass("UIApplication");
9073 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9074 if (UIApplication$_updateApplicationAccessibility != NULL) {
9075 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9076 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9079 /* Set Locale {{{ */
9080 Locale_ = CFLocaleCopyCurrent();
9081 Languages_ = [NSLocale preferredLanguages];
9082 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9083 //NSLog(@"%@", [Languages_ description]);
9086 if (Languages_ == nil || [Languages_ count] == 0)
9087 // XXX: consider just setting to C and then falling through?
9090 lang = [[Languages_ objectAtIndex:0] UTF8String];
9091 setenv("LANG", lang, true);
9094 //std::setlocale(LC_ALL, lang);
9095 NSLog(@"Setting Language: %s", lang);
9098 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9100 /* Parse Arguments {{{ */
9101 bool substrate(false);
9107 for (int argi(1); argi != argc; ++argi)
9108 if (strcmp(argv[argi], "--") == 0) {
9110 argv[argi] = argv[0];
9116 for (int argi(1); argi != arge; ++argi)
9117 if (strcmp(args[argi], "--substrate") == 0)
9120 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9124 App_ = [[NSBundle mainBundle] bundlePath];
9125 Home_ = NSHomeDirectory();
9131 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9132 alloc_ = alloc->method_imp;
9133 alloc->method_imp = (IMP) &Alloc_;*/
9135 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9136 dealloc_ = dealloc->method_imp;
9137 dealloc->method_imp = (IMP) &Dealloc_;*/
9139 /* System Information {{{ */
9143 size = sizeof(maxproc);
9144 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9145 perror("sysctlbyname(\"kern.maxproc\", ?)");
9146 else if (maxproc < 64) {
9148 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9149 perror("sysctlbyname(\"kern.maxproc\", #)");
9152 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9153 char *osversion = new char[size];
9154 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9155 perror("sysctlbyname(\"kern.osversion\", ?)");
9157 System_ = [NSString stringWithUTF8String:osversion];
9159 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9160 char *machine = new char[size];
9161 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9162 perror("sysctlbyname(\"hw.machine\", ?)");
9166 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9167 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9168 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9169 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9173 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9174 NSData *data((NSData *) ecid);
9175 size_t length([data length]);
9176 uint8_t bytes[length];
9177 [data getBytes:bytes];
9178 char string[length * 2 + 1];
9179 for (size_t i(0); i != length; ++i)
9180 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9181 ChipID_ = [NSString stringWithUTF8String:string];
9185 IOObjectRelease(service);
9189 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9191 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9192 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9193 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9195 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9196 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9197 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9199 if (mcc != NULL && mnc != NULL)
9200 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9207 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9208 Build_ = [system objectForKey:@"ProductBuildVersion"];
9209 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9210 Product_ = [info objectForKey:@"SafariProductVersion"];
9211 Safari_ = [info objectForKey:@"CFBundleVersion"];
9214 /* Load Database {{{ */
9216 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9218 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9220 if (Metadata_ == NULL)
9221 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9223 Settings_ = [Metadata_ objectForKey:@"Settings"];
9225 Packages_ = [Metadata_ objectForKey:@"Packages"];
9226 Sections_ = [Metadata_ objectForKey:@"Sections"];
9227 Sources_ = [Metadata_ objectForKey:@"Sources"];
9229 Token_ = [Metadata_ objectForKey:@"Token"];
9232 if (Settings_ != nil)
9233 Role_ = [Settings_ objectForKey:@"Role"];
9235 if (Sections_ == nil) {
9236 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9237 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9240 if (Sources_ == nil) {
9241 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9242 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9247 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9250 if (Packages_ != nil) {
9251 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
9253 [Metadata_ removeObjectForKey:@"Packages"];
9258 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9260 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9261 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9262 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9263 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9264 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9265 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9267 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9269 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9270 unlink("/tmp/.cydia.fw");
9272 } else if (access("/User", F_OK) != 0 || version < 2) {
9275 system("/usr/libexec/cydia/firmware.sh");
9279 _assert([[NSFileManager defaultManager]
9280 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9281 withIntermediateDirectories:YES
9286 if (access("/tmp/cydia.chk", F_OK) == 0) {
9287 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9288 _assert(errno == ENOENT);
9289 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9290 _assert(errno == ENOENT);
9293 /* APT Initialization {{{ */
9294 _assert(pkgInitConfig(*_config));
9295 _assert(pkgInitSystem(*_config, _system));
9298 _config->Set("APT::Acquire::Translation", lang);
9300 // XXX: this timeout might be important :(
9301 //_config->Set("Acquire::http::Timeout", 15);
9303 _config->Set("Acquire::http::MaxParallel", 3);
9305 /* Color Choices {{{ */
9306 space_ = CGColorSpaceCreateDeviceRGB();
9308 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9309 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9310 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9311 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9312 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9313 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9314 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9315 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9316 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9318 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9319 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9321 /* UIKit Configuration {{{ */
9322 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9323 if ($GSFontSetUseLegacyFontMetrics != NULL)
9324 $GSFontSetUseLegacyFontMetrics(YES);
9326 // XXX: I have a feeling this was important
9327 //UIKeyboardDisableAutomaticAppearance();
9330 Colon_ = UCLocalize("COLON_DELIMITED");
9331 Elision_ = UCLocalize("ELISION");
9332 Error_ = UCLocalize("ERROR");
9333 Warning_ = UCLocalize("WARNING");
9336 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9338 CGColorSpaceRelease(space_);